<?php
/**
 * Savit Unified Dashboard — entry point for all engines.
 * Connects to the shared DB. Dynamic data is fetched client-side from engine APIs.
 */

// ── Load shared platform bootstrap ──────────────────────────────────────────
define('SAVIT_ROOT', __DIR__);
require_once __DIR__ . '/Common/bootstrap.php';

// ── Bootstrap ROOT_PATH so Audit autoloader works (ProjectRepository etc.) ───
define('ROOT_PATH',  __DIR__ . '/Audit');
define('VIEWS_PATH', ROOT_PATH . '/views');

ini_set('display_errors', '1');
error_reporting(E_ALL);

spl_autoload_register(function (string $class): void {
    $prefix = 'Crawl\\';
    if (strpos($class, $prefix) !== 0) return;
    $file = ROOT_PATH . '/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
    if (file_exists($file)) require_once $file;
});

// Compute URL bases
$scriptDir  = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])), '/'); // /Savit
$auditBase  = $scriptDir . '/Audit/public';
$contentBase= $scriptDir . '/Content';

// Load projects with health data
$projects = (new \Crawl\Repositories\ProjectRepository())->allWithHealth();

// OAuth connection status for all projects
$projectIds  = array_column($projects, 'id');
$oauthMap    = (new \Crawl\Repositories\OAuthTokenRepository())->connectedMap(array_map('intval', $projectIds));

// Enrich with health score + oauth status
$projects = array_map(function (array $p) use ($oauthMap): array {
    $p['health_score'] = \Crawl\Repositories\ProjectRepository::computeHealthScore($p);
    $connections = $oauthMap[(int)$p['id']] ?? [];
    $p['ga4_connected'] = isset($connections['ga4']);
    $p['gsc_connected'] = isset($connections['gsc']);
    $p['gbp_connected'] = isset($connections['gbp']);
    return $p;
}, $projects);

// Pull latest analytics snapshot per project
$analyticsSnaps = [];
try {
    $db = \Crawl\Lib\Database::getInstance();
    $snapRows = $db->fetchAll("
        SELECT s.project_id, s.organic_sessions, s.gsc_clicks, s.gsc_impressions,
               s.gsc_position, s.total_leads, s.llm_total, s.branded_impressions,
               s.overall_users, s.period_start, s.period_end
        FROM analytics_snapshots s
        INNER JOIN (
            SELECT project_id, MAX(id) AS max_id FROM analytics_snapshots GROUP BY project_id
        ) latest ON latest.project_id = s.project_id AND latest.max_id = s.id
    ");
    foreach ($snapRows as $sr) {
        $analyticsSnaps[(int)$sr['project_id']] = $sr;
    }
} catch (\Throwable) {}

// Enrich with analytics snapshot data
$projects = array_map(function (array $p) use ($analyticsSnaps, $oauthMap): array {
    $p['analytics'] = $analyticsSnaps[(int)$p['id']] ?? null;
    $snap = $p['analytics'];
    // Compute analytics health from sessions + leads trend (if snap available)
    $p['analytics_health'] = $snap ? min(100, max(0, 50 + (int)(($snap['total_leads'] ?? 0) > 0 ? 20 : 0) + (int)(($snap['gsc_clicks'] ?? 0) > 0 ? 20 : 0) + (int)(($snap['organic_sessions'] ?? 0) > 200 ? 10 : 0))) : null;
    return $p;
}, $projects);

$totalProjects = count($projects);
$healthy  = count(array_filter($projects, fn($p) => $p['health_score'] >= 80 && $p['latest_run_id']));
$warnings = count(array_filter($projects, fn($p) => $p['health_score'] >= 60 && $p['health_score'] < 80 && $p['latest_run_id']));
$critical = count(array_filter($projects, fn($p) => $p['health_score'] > 0 && $p['health_score'] < 60));
$analyticsConnected = count(array_filter($projects, fn($p) => $p['ga4_connected'] || $p['gsc_connected']));
$totalLeads   = array_sum(array_map(fn($p) => (int)(($p['analytics']['total_leads'] ?? 0)), $projects));
$totalSessions = array_sum(array_map(fn($p) => (int)(($p['analytics']['organic_sessions'] ?? 0)), $projects));
$noCrawl = count(array_filter($projects, fn($p) => empty($p['latest_run_id'])));

$oauthError   = htmlspecialchars($_GET['oauth_error']   ?? '');
$oauthSuccess = htmlspecialchars($_GET['oauth_success'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="savit-base" content="<?= htmlspecialchars($scriptDir) ?>">
  <meta name="audit-base" content="<?= htmlspecialchars($auditBase) ?>">
  <title>Dashboard — Savit</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
  <link rel="stylesheet" href="<?= htmlspecialchars($scriptDir) ?>/Common/assets/css/savit.css">
  <style>
    .health-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
    .conn-badge { font-size: .65rem; padding: 2px 6px; border-radius: 4px; font-weight: 600; }
    .perf-cell  { font-size: .8rem; color: #475569; }
    .project-row:hover { background: #f8fafc !important; cursor: pointer; }
    .project-row td { vertical-align: middle; }
    .score-pill { font-size: .75rem; font-weight: 700; padding: 3px 8px; border-radius: 20px; }
    #perf-loading-row td { padding: 6px 12px; color: #94a3b8; font-size: .75rem; }
  </style>
</head>
<body>
<div class="d-flex" id="app-wrapper">

  <!-- Sidebar -->
  <aside class="sidebar" id="sidebar">
    <a href="<?= htmlspecialchars($scriptDir) ?>/" class="sidebar-brand">
      <div class="sb-logo">S</div>
      <div>
        <div class="logo-text">Savit</div>
        <div class="logo-sub">Unified SEO Suite</div>
      </div>
    </a>

    <div class="sidebar-section">Engines</div>
    <nav class="sidebar-nav">
      <a href="<?= htmlspecialchars($scriptDir) ?>/" class="sb-engine-link active">
        <i class="bi bi-grid-3x3-gap-fill"></i><span>Dashboard</span>
        <span class="sb-active-dot" style="background:#818cf8;"></span>
      </a>
      <a href="<?= htmlspecialchars($contentBase) ?>/"
         class="sb-engine-link"
         id="dash-content-link"
         data-engine="content"
         data-base="<?= htmlspecialchars($contentBase) ?>">
        <i class="bi bi-lightning-fill"></i><span>Content Engine</span>
      </a>
      <a href="<?= htmlspecialchars($auditBase) ?>/"
         class="sb-engine-link"
         id="dash-audit-link"
         data-engine="audit"
         data-base="<?= htmlspecialchars($auditBase) ?>">
        <i class="bi bi-search"></i><span>Audit Engine</span>
      </a>
      <a href="<?= htmlspecialchars($scriptDir) ?>/Analytics/public/"
         class="sb-engine-link"
         id="dash-analytics-link"
         data-engine="analytics"
         data-base="<?= htmlspecialchars($scriptDir) ?>/Analytics/public">
        <i class="bi bi-bar-chart-line-fill"></i><span>Analytics</span>
      </a>
      <a href="<?= htmlspecialchars($scriptDir) ?>/PPC/media_plan.php" class="sb-engine-link">
        <i class="bi bi-bar-chart-fill"></i><span>PPC Engine</span>
      </a>
    </nav>

    <hr class="sidebar-divider">

    <div class="sidebar-section">Dashboard</div>
    <nav class="sidebar-nav">
      <a href="<?= htmlspecialchars($scriptDir) ?>/" class="active">
        <i class="bi bi-grid-3x3-gap"></i><span>All Projects</span>
      </a>
      <a href="<?= htmlspecialchars($contentBase) ?>/projects/create">
        <i class="bi bi-plus-circle"></i><span>New Project</span>
      </a>
    </nav>

    <div class="sidebar-footer">
      <small>Savit v1.0 &middot; Dashboard</small>
    </div>
  </aside>
  <script>
  document.addEventListener('DOMContentLoaded', function () {
    try {
      var proj = JSON.parse(localStorage.getItem('savit_project') || 'null');
      if (!proj || !proj.id) return;
      var end   = new Date().toISOString().split('T')[0];
      var start = new Date(Date.now() - 30 * 864e5).toISOString().split('T')[0];
      var auditEl     = document.getElementById('dash-audit-link');
      var analyticsEl = document.getElementById('dash-analytics-link');
      var contentEl   = document.getElementById('dash-content-link');
      if (auditEl)     auditEl.href     = auditEl.dataset.base + '/?p=' + proj.id;
      if (analyticsEl) analyticsEl.href = analyticsEl.dataset.base + '/report?project=' + proj.id + '&start=' + start + '&end=' + end + '&audience=client';
      if (contentEl)   contentEl.href   = contentEl.dataset.base + '/projects/' + proj.id + '/edit';
    } catch (_) {}
  });
  </script>

  <!-- Main content -->
  <div class="flex-grow-1 d-flex flex-column min-vh-100" id="main-content">

    <!-- Topbar -->
    <div class="savit-topbar">
      <div class="topbar-left">
        <button class="topbar-toggle" id="sidebar-toggle">
          <i class="bi bi-list" style="font-size:18px;"></i>
        </button>
        <span class="topbar-title">Projects Dashboard</span>
      </div>
      <div class="topbar-right">
        <span class="topbar-engine-badge" style="background:rgba(99,102,241,.1);color:#6366f1;">
          <i class="bi bi-grid-3x3-gap me-1"></i>Savit Platform
        </span>
      </div>
    </div>

    <!-- Page content -->
    <div class="p-4 flex-grow-1">

      <?php if ($oauthError): ?>
      <div class="alert alert-danger alert-dismissible mb-3">
        <i class="bi bi-exclamation-triangle me-2"></i>OAuth error: <?= $oauthError ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if ($oauthSuccess): ?>
      <div class="alert alert-success alert-dismissible mb-3">
        <i class="bi bi-check-circle me-2"></i><?= strtoupper($oauthSuccess) ?> connected successfully.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>

      <!-- Header -->
      <div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-2">
        <div>
          <h4 class="fw-bold mb-0">All Projects</h4>
          <p class="text-muted small mb-0">Click any row to open the Analytics report for that project.</p>
        </div>
        <a href="<?= htmlspecialchars($contentBase) ?>/projects/create" class="btn btn-sm btn-primary">
          <i class="bi bi-plus-lg me-1"></i>New Project
        </a>
      </div>

      <!-- Summary KPI strip -->
      <div class="row g-3 mb-4">
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100">
            <div class="text-muted small">Total Clients</div>
            <div class="fs-3 fw-bold"><?= $totalProjects ?></div>
            <div style="font-size:.68rem;color:#94a3b8;"><?= $noCrawl ?> not yet audited</div>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100" style="border-left:3px solid #22c55e!important;">
            <div class="text-muted small">Audit Healthy</div>
            <div class="fs-3 fw-bold text-success"><?= $healthy ?></div>
            <div style="font-size:.68rem;color:#94a3b8;">Score ≥ 80</div>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100" style="border-left:3px solid #f59e0b!important;">
            <div class="text-muted small">Needs Attention</div>
            <div class="fs-3 fw-bold text-warning"><?= $warnings ?></div>
            <div style="font-size:.68rem;color:#94a3b8;">Score 60–79</div>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100" style="border-left:3px solid #ef4444!important;">
            <div class="text-muted small">Critical Issues</div>
            <div class="fs-3 fw-bold text-danger"><?= $critical ?></div>
            <div style="font-size:.68rem;color:#94a3b8;">Score &lt; 60</div>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100" style="border-left:3px solid #7c3aed!important;">
            <div class="text-muted small">Organic Sessions</div>
            <div class="fs-3 fw-bold" style="color:#7c3aed;"><?= number_format($totalSessions) ?></div>
            <div style="font-size:.68rem;color:#94a3b8;">Latest snapshot</div>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="card border-0 shadow-sm p-3 text-center h-100" style="border-left:3px solid #0284c7!important;">
            <div class="text-muted small">Total Leads</div>
            <div class="fs-3 fw-bold" style="color:#0284c7;"><?= number_format($totalLeads) ?></div>
            <div style="font-size:.68rem;color:#94a3b8;"><?= $analyticsConnected ?> with GA4/GSC</div>
          </div>
        </div>
      </div>

      <!-- Projects table -->
      <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
          <div class="table-responsive table-scroll-wrap" id="projects-scroll">
            <table class="table table-hover mb-0 no-datatable table-sticky-col" id="projects-table" style="white-space:nowrap;min-width:960px;">
              <thead class="table-light" style="font-size:.78rem;">
                <tr>
                  <th style="min-width:180px;">Project</th>
                  <th style="min-width:90px;">Audit<br><span style="font-weight:400;font-size:.7rem;color:#94a3b8;">Health Score</span></th>
                  <th style="min-width:80px;">Issues<br><span style="font-weight:400;font-size:.7rem;color:#94a3b8;">Errors</span></th>
                  <th style="min-width:90px;">Last Crawl</th>
                  <th class="text-end" style="min-width:80px;">Sessions<br><span style="font-weight:400;font-size:.7rem;color:#94a3b8;">Organic</span></th>
                  <th class="text-end" style="min-width:80px;">GSC Clicks</th>
                  <th class="text-end" style="min-width:70px;">Leads</th>
                  <th class="text-end" style="min-width:80px;">Position<br><span style="font-weight:400;font-size:.7rem;color:#94a3b8;">Avg GSC</span></th>
                  <th class="text-center" style="min-width:110px;">Connect</th>
                  <th style="min-width:80px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($projects as $p):
                  $score     = $p['health_score'];
                  $hasCrawl  = !empty($p['latest_run_id']);
                  $scoreColor= $score >= 80 ? '#22c55e' : ($score >= 60 ? '#f59e0b' : ($score > 0 ? '#ef4444' : '#94a3b8'));
                  $date      = $p['finished_at'] ? date('d M', strtotime($p['finished_at'])) : '—';
                  $errCount  = (int)($p['error_pages'] ?? 0);
                  $domain    = $p['crawl_domain'] ?: ($p['website_url'] ?? '—');
                  $auditUrl  = $auditBase . '/?p=' . $p['id'];
                  $snap      = $p['analytics'] ?? null;
                ?>
                <tr class="project-row" style="cursor:pointer;" data-id="<?= (int)$p['id'] ?>"
                    data-audit-url="<?= htmlspecialchars($auditUrl) ?>"
                    data-name="<?= htmlspecialchars($p['business_name']) ?>"
                    data-domain="<?= htmlspecialchars($p['website_url'] ?? $p['crawl_domain'] ?? '') ?>"
                    data-ga4="<?= $p['ga4_connected'] ? '1' : '0' ?>"
                    data-gsc="<?= $p['gsc_connected'] ? '1' : '0' ?>"
                    data-gbp="<?= $p['gbp_connected'] ? '1' : '0' ?>">

                  <!-- Project Name -->
                  <td>
                    <div class="fw-semibold" style="max-width:175px;overflow:hidden;text-overflow:ellipsis;" title="<?= htmlspecialchars($p['business_name']) ?>">
                      <?= htmlspecialchars($p['business_name']) ?>
                    </div>
                    <div class="text-muted" style="font-size:.68rem;max-width:175px;overflow:hidden;text-overflow:ellipsis;"><?= htmlspecialchars($domain) ?></div>
                  </td>

                  <!-- Audit Health -->
                  <td>
                    <?php if ($hasCrawl && $score > 0): ?>
                    <div class="d-flex align-items-center gap-1">
                      <span style="width:8px;height:8px;border-radius:50%;background:<?= $scoreColor ?>;flex-shrink:0;"></span>
                      <span style="font-weight:700;color:<?= $scoreColor ?>;"><?= $score ?></span>
                    </div>
                    <div style="height:3px;background:#f1f5f9;border-radius:2px;overflow:hidden;width:48px;margin-top:3px;">
                      <div style="height:100%;width:<?= $score ?>%;background:<?= $scoreColor ?>;border-radius:2px;"></div>
                    </div>
                    <?php else: ?>
                    <span style="color:#94a3b8;font-size:.75rem;"><?= $hasCrawl ? '—' : 'No crawl' ?></span>
                    <?php endif; ?>
                  </td>

                  <!-- Issues -->
                  <td>
                    <?php if ($hasCrawl): ?>
                    <span class="badge <?= $errCount > 0 ? 'bg-danger-subtle text-danger' : 'bg-success-subtle text-success' ?>" style="font-size:.7rem;">
                      <?= $errCount ?> err<?= $errCount !== 1 ? 's' : '' ?>
                    </span>
                    <?php else: ?><span class="text-muted small">—</span><?php endif; ?>
                  </td>

                  <!-- Last Crawl -->
                  <td class="small text-muted"><?= $date ?></td>

                  <!-- Sessions (from analytics snapshot) -->
                  <td class="text-end small">
                    <?= $snap ? '<span style="font-weight:600;color:#7c3aed;">' . number_format($snap['organic_sessions'] ?? 0) . '</span>' : '<span class="text-muted">—</span>' ?>
                  </td>

                  <!-- Clicks -->
                  <td class="text-end small">
                    <?= $snap ? number_format($snap['gsc_clicks'] ?? 0) : '<span class="text-muted">—</span>' ?>
                  </td>

                  <!-- Leads -->
                  <td class="text-end small">
                    <?php if ($snap && ($snap['total_leads'] ?? 0) > 0): ?>
                    <span style="font-weight:700;color:#d97706;"><?= number_format($snap['total_leads']) ?></span>
                    <?php elseif ($snap): ?><span class="text-muted">0</span>
                    <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                  </td>

                  <!-- Avg Position -->
                  <td class="text-end small">
                    <?php
                    $pos = $snap ? (float)($snap['gsc_position'] ?? 0) : 0;
                    $posColor = $pos > 0 && $pos <= 3 ? '#22c55e' : ($pos <= 10 ? '#f59e0b' : ($pos <= 20 ? '#94a3b8' : '#ef4444'));
                    ?>
                    <?= $snap && $pos > 0 ? '<span style="color:' . $posColor . ';font-weight:600;">' . number_format($pos, 1) . '</span>' : '<span class="text-muted">—</span>' ?>
                  </td>

                  <!-- Connections -->
                  <td class="text-center">
                    <span class="conn-badge <?= $p['ga4_connected'] ? 'bg-success-subtle text-success' : 'bg-light text-muted' ?> me-1" title="GA4">GA4</span>
                    <span class="conn-badge <?= $p['gsc_connected'] ? 'bg-success-subtle text-success' : 'bg-light text-muted' ?> me-1" title="GSC">GSC</span>
                    <span class="conn-badge <?= $p['gbp_connected'] ? 'bg-success-subtle text-success' : 'bg-light text-muted' ?>" title="GBP">GBP</span>
                  </td>

                  <!-- Actions -->
                  <td onclick="event.stopPropagation();">
                    <div class="d-flex gap-1 justify-content-center">
                      <a href="<?= htmlspecialchars($contentBase) ?>/projects/<?= (int)$p['id'] ?>/edit"
                         class="btn btn-sm btn-outline-secondary py-0 px-2" title="Settings"><i class="bi bi-gear"></i></a>
                      <a href="<?= htmlspecialchars($auditBase) ?>/?p=<?= (int)$p['id'] ?>"
                         class="btn btn-sm btn-outline-primary py-0 px-2" title="Audit"><i class="bi bi-search"></i></a>
                    </div>
                  </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($projects)): ?>
                <tr><td colspan="10" class="text-center text-muted py-5">
                  <i class="bi bi-collection" style="font-size:2rem;opacity:.3;"></i>
                  <div class="mt-2">No projects yet. <a href="<?= htmlspecialchars($contentBase) ?>/projects/create">Create your first →</a></div>
                </td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div><!-- /p-4 -->
  </div><!-- /main-content -->
</div><!-- /app-wrapper -->

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="<?= htmlspecialchars($scriptDir) ?>/Common/assets/js/savit-tables.js?v=3"></script>
<script>
(function () {
  const auditBase = document.querySelector('meta[name="audit-base"]').content;

  // Sidebar toggle
  document.getElementById('sidebar-toggle')?.addEventListener('click', () => {
    document.getElementById('sidebar').classList.toggle('collapsed');
  });

  // Overflow fade hint for wide tables
  function checkOverflow(el) {
    if (!el) return;
    el.classList.toggle('has-overflow', el.scrollWidth > el.clientWidth + 4);
  }
  const scrollEl = document.getElementById('projects-scroll');
  checkOverflow(scrollEl);
  window.addEventListener('resize', () => checkOverflow(scrollEl));
  scrollEl?.addEventListener('scroll', () => {
    if (!scrollEl) return;
    const atEnd = scrollEl.scrollLeft + scrollEl.clientWidth >= scrollEl.scrollWidth - 8;
    scrollEl.classList.toggle('has-overflow', !atEnd && scrollEl.scrollWidth > scrollEl.clientWidth + 4);
  });

  // Row click → navigate to Analytics report for this project
  const analyticsBase = '/<?= trim($scriptDir, '/') ?>/Analytics/public';
  const end   = new Date().toISOString().split('T')[0];
  const start = new Date(Date.now() - 30 * 864e5).toISOString().split('T')[0];

  document.querySelectorAll('.project-row').forEach((row) => {
    row.addEventListener('click', (e) => {
      if (e.target.closest('a,button')) return;
      const id     = row.dataset.id;
      const name   = row.dataset.name   || '';
      const domain = row.dataset.domain || '';
      localStorage.setItem('savit_project', JSON.stringify({ id: +id, name, domain }));
      window.location.href = analyticsBase + '/report?project=' + id +
                             '&start=' + start + '&end=' + end + '&audience=client';
    });
    row.style.cursor = 'pointer';
  });

  // Lazy-load performance data for connected projects
  const rows = Array.from(document.querySelectorAll('.project-row'));

  async function loadPerf(row) {
    const id        = row.dataset.id;
    const ga4Conn   = row.dataset.ga4 === '1';
    const gscConn   = row.dataset.gsc === '1';

    const [sessEl, posEl] = [
      document.getElementById('perf-sessions-' + id),
      document.getElementById('perf-position-' + id),
    ];

    try {
      if (ga4Conn && sessEl) {
        const r = await fetch(auditBase + '/api/projects/' + id + '/performance/overview?days=30');
        const j = await r.json();
        if (j.success && j.data && !j.data.error) {
          sessEl.textContent = (j.data.sessions || 0).toLocaleString('en-IN');
        } else {
          sessEl.innerHTML = '<span class="text-muted">—</span>';
        }
      }

      if (gscConn && posEl) {
        const r = await fetch(auditBase + '/api/projects/' + id + '/performance/search?days=30');
        const j = await r.json();
        if (j.success && j.data?.summary && !j.data.summary.error) {
          const pos = j.data.summary.position;
          posEl.textContent = pos > 0 ? pos.toFixed(1) : '—';
        } else {
          posEl.innerHTML = '<span class="text-muted">—</span>';
        }
      }
    } catch (_) {
      if (sessEl) sessEl.innerHTML = '<span class="text-muted">—</span>';
      if (posEl)  posEl.innerHTML  = '<span class="text-muted">—</span>';
    }
  }

  // Load in batches to avoid hammering the API
  async function loadAllPerf() {
    const connected = rows.filter(r => r.dataset.ga4 === '1' || r.dataset.gsc === '1');
    for (const row of connected) {
      await loadPerf(row);
    }
  }

  loadAllPerf();
})();
</script>
</body>
</html>
