<?php
/* ── persist active project ─────────────────────────────────── */
$_pid  = (int)$project['id'];
$_pname = json_encode($project['business_name'] ?? '');
$_pdomain = json_encode($project['website_url'] ?? '');
?>
<script>
(function(){try{localStorage.setItem('savit_project',JSON.stringify({id:<?= $_pid ?>,name:<?= $_pname ?>,domain:<?= $_pdomain ?>}));}catch(_){}}());
</script>
<?php
/* ── base URL (set by header.php as $analyticsBase) ─────────── */
$base = $analyticsBase ?? '';

/* ── data shortcuts ─────────────────────────────────────────── */
$s       = $report['snapshot']     ?? [];
$prev    = $report['previous']     ?? null;
$cats    = $report['categories']   ?? [];
$roas    = $report['roas']         ?? 0;
$leadVal = $report['lead_value']   ?? 0;
$health  = $report['health_score'] ?? 0;
$hcls    = $health >= 70 ? 'success' : ($health >= 50 ? 'warning' : 'danger');
$hcolor  = $health >= 70 ? '#22c55e' : ($health >= 50 ? '#f59e0b' : '#ef4444');
$projName = $project['business_name'] ?? '';

/* ── Comparison mode ─────────────────────────────────────────── */
$compareMode  = $compareMode ?? 'period';
$cmpRange     = $report['compare_range'] ?? [];
$cmpStart     = $cmpRange['start'] ?? '';
$cmpEnd       = $cmpRange['end']   ?? '';
$hasComparison = $prev !== null;

$qsNoAud  = "project={$_pid}&start={$start}&end={$end}&compare={$compareMode}";
$qsBase   = "{$qsNoAud}&audience={$audience}";
$audienceForExport = ($audience === 'business_owner') ? 'business' : $audience;

/* ── comparison helpers ─────────────────────────────────────── */
function v(array $snap, string $key, float $fallback = 0): float {
    return (float)($snap[$key] ?? $fallback);
}
function fmt(float $v, string $f = 'n'): string {
    return match($f) {
        'inr'   => '₹' . (abs($v) >= 100000 ? number_format($v/100000,1).'L' : number_format($v,0)),
        'pct'   => number_format($v, 2) . '%',
        'dec'   => number_format($v, 1),
        'x'     => number_format($v, 1) . 'x',
        'pos'   => number_format($v, 1),
        default => number_format($v),
    };
}
function delta(float $curr, float $p): array {
    $abs = $curr - $p;
    $pct = $p != 0 ? round($abs / $p * 100, 1) : null;
    return ['abs' => $abs, 'pct' => $pct, 'up' => $abs >= 0];
}
function deltaHtml(float $curr, ?array $prevSnap, string $key, bool $invertGood = false): string {
    if ($prevSnap === null) return '';
    $p = (float)($prevSnap[$key] ?? 0);
    $d = delta($curr, $p);
    if ($d['pct'] === null) return '';
    $good  = $invertGood ? !$d['up'] : $d['up'];
    $color = $good ? '#16a34a' : '#dc2626';
    $arrow = $d['up'] ? '▲' : '▼';
    $sign  = $d['up'] ? '+' : '';
    return "<span style='color:{$color};font-size:.75rem;font-weight:600;'>{$arrow} {$sign}" . number_format($d['abs']) . " ({$sign}{$d['pct']}%)</span>";
}
function prevLine(?array $prevSnap, string $key, string $f = 'n'): string {
    if ($prevSnap === null) return '';
    return '<span style="color:#94a3b8;font-size:.72rem;">prev: ' . fmt((float)($prevSnap[$key] ?? 0), $f) . '</span>';
}

/* ── period presets ─────────────────────────────────────────── */
$presets = [
    ['label' => '7d',   'days' => 7],
    ['label' => '14d',  'days' => 14],
    ['label' => '30d',  'days' => 30],
    ['label' => '90d',  'days' => 90],
    ['label' => '6mo',  'days' => 180],
    ['label' => 'YoY',  'days' => 365],
];
?>

<!-- ── BREADCRUMB ────────────────────────────────────────────────────────── -->
<nav class="mb-2" style="font-size:.78rem;color:#94a3b8;">
  <a href="<?= htmlspecialchars($base) ?>/" style="color:#94a3b8;text-decoration:none;">Analytics</a>
  <span class="mx-1">›</span>
  <a href="<?= htmlspecialchars($base) ?>/report" style="color:#94a3b8;text-decoration:none;">Reports</a>
  <span class="mx-1">›</span>
  <span style="color:#0f172a;"><?= htmlspecialchars($projName) ?></span>
</nav>

<!-- ── TOP BAR ─────────────────────────────────────────────────────────── -->
<div class="rpt-topbar d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
  <div class="d-flex align-items-center gap-2">
    <!-- Prev project -->
    <?php if (!empty($prevProject)): ?>
    <a href="?project=<?= (int)$prevProject['id'] ?>&start=<?= $start ?>&end=<?= $end ?>&audience=<?= $audience ?>&compare=<?= $compareMode ?>"
       class="btn btn-sm btn-light border" title="<?= htmlspecialchars($prevProject['business_name']) ?>">
      <i class="bi bi-chevron-left"></i>
    </a>
    <?php else: ?>
    <button class="btn btn-sm btn-light border" disabled><i class="bi bi-chevron-left"></i></button>
    <?php endif; ?>

    <div>
      <div class="fw-bold fs-5 lh-sm"><?= htmlspecialchars($projName) ?></div>
      <div class="text-muted small"><?= htmlspecialchars($project['business_category'] ?? '') ?>
        <?php if ($project['manager_name'] ?? ''): ?>&nbsp;·&nbsp;<?= htmlspecialchars($project['manager_name'] ?? '') ?><?php endif; ?>
      </div>
    </div>

    <!-- Next project -->
    <?php if (!empty($nextProject)): ?>
    <a href="?project=<?= (int)$nextProject['id'] ?>&start=<?= $start ?>&end=<?= $end ?>&audience=<?= $audience ?>&compare=<?= $compareMode ?>"
       class="btn btn-sm btn-light border" title="<?= htmlspecialchars($nextProject['business_name']) ?>">
      <i class="bi bi-chevron-right"></i>
    </a>
    <?php else: ?>
    <button class="btn btn-sm btn-light border" disabled><i class="bi bi-chevron-right"></i></button>
    <?php endif; ?>
  </div>

  <!-- Audience tabs + Export -->
  <div class="d-flex align-items-center gap-2 flex-wrap">
    <div class="btn-group btn-group-sm">
      <?php foreach (['client' => 'Client', 'business_owner' => 'Business', 'team' => 'Team'] as $aud => $lbl): ?>
      <a href="?<?= $qsNoAud ?>&audience=<?= $aud ?>"
         class="btn <?= $audience === $aud ? 'btn-dark' : 'btn-outline-secondary' ?>">
        <?= $lbl ?>
      </a>
      <?php endforeach; ?>
    </div>
    <div class="dropdown">
      <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
        <i class="bi bi-download me-1"></i>Export
      </button>
      <ul class="dropdown-menu dropdown-menu-end">
        <li><a class="dropdown-item" href="<?= htmlspecialchars($base) ?>/api/projects/<?= $_pid ?>/export/excel?start=<?= $start ?>&end=<?= $end ?>&audience=<?= htmlspecialchars($audienceForExport) ?>">
          <i class="bi bi-file-earmark-excel me-2 text-success"></i>Excel
        </a></li>
        <li><a class="dropdown-item" href="javascript:window.print()">
          <i class="bi bi-printer me-2"></i>Print / PDF
        </a></li>
        <li><a class="dropdown-item" href="<?= htmlspecialchars($base) ?>/slides?<?= $qsBase ?>" target="_blank">
          <i class="bi bi-easel me-2 text-primary"></i>Presentation
        </a></li>
      </ul>
    </div>
    <a href="<?= htmlspecialchars($base) ?>/projects/<?= $_pid ?>" class="btn btn-sm btn-outline-secondary" title="Project detail & run tracker">
      <i class="bi bi-play-fill"></i>
    </a>
  </div>
</div>

<!-- ── PERIOD CONTROLS ─────────────────────────────────────────────────── -->
<div class="d-flex align-items-center gap-2 flex-wrap mb-2">
  <div class="btn-group btn-group-sm" id="period-preset-btns">
    <?php foreach ($presets as $pr):
      $ps = date('Y-m-d', strtotime("-{$pr['days']} days"));
      $pe = date('Y-m-d');
      $active = ($start === $ps && $end === $pe);
    ?>
    <a href="?project=<?= $_pid ?>&start=<?= $ps ?>&end=<?= $pe ?>&audience=<?= $audience ?>&compare=<?= $compareMode ?>"
       class="btn btn-sm <?= $active ? 'btn-dark' : 'btn-outline-secondary' ?>">
      <?= $pr['label'] ?>
    </a>
    <?php endforeach; ?>
  </div>
  <form method="GET" class="d-flex align-items-center gap-1">
    <input type="hidden" name="project"  value="<?= $_pid ?>">
    <input type="hidden" name="audience" value="<?= htmlspecialchars($audience) ?>">
    <input type="hidden" name="compare"  value="<?= htmlspecialchars($compareMode) ?>">
    <input type="date" name="start" value="<?= $start ?>" class="form-control form-control-sm" style="width:130px;">
    <span class="text-muted">–</span>
    <input type="date" name="end"   value="<?= $end ?>"   class="form-control form-control-sm" style="width:130px;">
    <button class="btn btn-sm btn-outline-primary">Apply</button>
  </form>
</div>

<!-- ── COMPARE MODE SELECTOR ─────────────────────────────────────────── -->
<div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
  <div class="d-flex align-items-center gap-1">
    <span class="text-muted small fw-semibold me-1">Compare:</span>
    <?php
    $compareModes = [
      'period' => 'Prev Period',
      'month'  => 'Prev Month',
      'year'   => 'Prev Year',
    ];
    foreach ($compareModes as $modeKey => $modeLabel):
      $href = "?project={$_pid}&start={$start}&end={$end}&audience={$audience}&compare={$modeKey}";
      $isActive = $compareMode === $modeKey;
    ?>
    <a href="<?= $href ?>" id="cmp-btn-<?= $modeKey ?>"
       class="btn btn-sm <?= $isActive ? 'btn-primary' : 'btn-outline-secondary' ?>">
      <?= $modeLabel ?>
    </a>
    <?php endforeach; ?>
  </div>

  <?php if ($cmpStart && $cmpEnd): ?>
  <div class="text-muted small" id="cmp-status-bar">
    Comparing <strong><?= date('d M', strtotime($start)) ?> – <?= date('d M Y', strtotime($end)) ?></strong>
    vs
    <?php if ($hasComparison): ?>
      <strong class="text-success"><?= date('d M', strtotime($cmpStart)) ?> – <?= date('d M Y', strtotime($cmpEnd)) ?></strong>
    <?php else: ?>
      <strong><?= date('d M', strtotime($cmpStart)) ?> – <?= date('d M Y', strtotime($cmpEnd)) ?></strong>
      <span id="cmp-fetch-badge" class="badge bg-secondary ms-1">
        <span class="spinner-border spinner-border-sm me-1" style="width:.6rem;height:.6rem;"></span>Fetching comparison…
      </span>
    <?php endif; ?>
  </div>
  <?php endif; ?>
</div>

<?php if (!empty($report['error'])): ?>
<div class="alert alert-warning">
  <i class="bi bi-exclamation-triangle me-2"></i><?= htmlspecialchars($report['error']) ?>
</div>
<?php else: ?>

<!-- ── HERO ROW ────────────────────────────────────────────────────────── -->
<div class="row g-3 mb-3">

  <!-- Health Score -->
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Health Score</div>
      <div class="rpt-big" style="color:<?= $hcolor ?>;"><?= $health ?><span style="font-size:.7em;color:#94a3b8;">/100</span></div>
      <div class="mt-1">
        <span class="badge" style="background:<?= $hcolor ?>20;color:<?= $hcolor ?>;font-size:.7rem;">
          <?= $health >= 70 ? 'Healthy' : ($health >= 50 ? 'Monitor' : 'At Risk') ?>
        </span>
      </div>
    </div>
  </div>

  <!-- ROAS -->
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">ROAS</div>
      <div class="rpt-big" style="color:#7c3aed;"><?= number_format($roas, 1) ?>x</div>
      <div class="rpt-sub">return on retainer</div>
    </div>
  </div>

  <!-- Lead Value -->
  <?php if ($audience !== 'client'): ?>
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Est. Lead Value</div>
      <div class="rpt-big" style="color:#0284c7;"><?= fmt($leadVal, 'inr') ?></div>
      <div class="rpt-sub">from <?= number_format(v($s,'total_leads')) ?> leads</div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Organic Sessions -->
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Organic Sessions</div>
      <div class="rpt-big"><?= fmt(v($s,'organic_sessions')) ?></div>
      <div><?= deltaHtml(v($s,'organic_sessions'), $prev, 'organic_sessions') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'organic_sessions') ?></div>
    </div>
  </div>

  <!-- GSC Clicks -->
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">GSC Clicks</div>
      <div class="rpt-big"><?= fmt(v($s,'gsc_clicks')) ?></div>
      <div><?= deltaHtml(v($s,'gsc_clicks'), $prev, 'gsc_clicks') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'gsc_clicks') ?></div>
    </div>
  </div>

  <!-- Total Leads -->
  <div class="col-6 col-md-4 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Total Leads</div>
      <div class="rpt-big" style="color:#0891b2;"><?= fmt(v($s,'total_leads')) ?></div>
      <div><?= deltaHtml(v($s,'total_leads'), $prev, 'total_leads') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'total_leads') ?></div>
    </div>
  </div>

</div>

<!-- ── SECOND KPI ROW (hidden for Business Owner — too technical) ─────── -->
<?php if ($audience !== 'business_owner'): ?>
<div class="row g-3 mb-4">

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Impressions</div>
      <div class="rpt-med"><?= fmt(v($s,'gsc_impressions')) ?></div>
      <div><?= deltaHtml(v($s,'gsc_impressions'), $prev, 'gsc_impressions') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'gsc_impressions') ?></div>
    </div>
  </div>

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Avg. Position</div>
      <div class="rpt-med"><?= fmt(v($s,'gsc_position'), 'pos') ?></div>
      <div><?= deltaHtml(v($s,'gsc_position'), $prev, 'gsc_position', true) ?></div>
      <div class="mt-1"><?= prevLine($prev, 'gsc_position', 'pos') ?></div>
    </div>
  </div>

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">CTR</div>
      <div class="rpt-med"><?= number_format(v($s,'gsc_ctr') * 100, 2) ?>%</div>
      <?php if ($prev): $pCtr = v($prev,'gsc_ctr'); $cCtr = v($s,'gsc_ctr'); $d = delta($cCtr*100, $pCtr*100); ?>
      <div style="color:<?= $d['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.75rem;font-weight:600;">
        <?= $d['up'] ? '▲' : '▼' ?> <?= $d['up'] ? '+' : '' ?><?= $d['pct'] ?>%
      </div>
      <div class="mt-1"><span style="color:#94a3b8;font-size:.72rem;">prev: <?= number_format($pCtr*100,2) ?>%</span></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">New Users</div>
      <div class="rpt-med"><?= fmt(v($s,'new_users')) ?></div>
      <div><?= deltaHtml(v($s,'new_users'), $prev, 'new_users') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'new_users') ?></div>
    </div>
  </div>

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">AI / LLM</div>
      <div class="rpt-med"><?= fmt(v($s,'llm_total')) ?></div>
      <div><?= deltaHtml(v($s,'llm_total'), $prev, 'llm_total') ?></div>
      <div class="mt-1"><?= prevLine($prev, 'llm_total') ?></div>
    </div>
  </div>

  <div class="col-6 col-md-3 col-lg-2">
    <div class="rpt-card h-100 text-center">
      <div class="rpt-label">Engagement Rate</div>
      <div class="rpt-med"><?= number_format(v($s,'organic_engagement_rate') * 100, 1) ?>%</div>
      <?php if ($prev): $pEr = v($prev,'organic_engagement_rate'); $cEr = v($s,'organic_engagement_rate'); $d2 = delta($cEr*100, $pEr*100); ?>
      <div style="color:<?= $d2['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.75rem;font-weight:600;">
        <?= $d2['up'] ? '▲' : '▼' ?> <?= $d2['up'] ? '+' : '' ?><?= $d2['pct'] ?>%
      </div>
      <div class="mt-1"><span style="color:#94a3b8;font-size:.72rem;">prev: <?= number_format($pEr*100,1) ?>%</span></div>
      <?php endif; ?>
    </div>
  </div>

</div>
<?php endif; // end business_owner filter ?>

<!-- ── TREND CHART ──────────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2 py-2">
    <div class="fw-semibold">Trend</div>
    <div class="d-flex align-items-center gap-2 flex-wrap">
      <!-- Metric selector -->
      <div class="btn-group btn-group-sm" id="trend-metric">
        <button class="btn btn-dark active"       data-metric="sessions">Sessions</button>
        <button class="btn btn-outline-secondary" data-metric="clicks">Clicks</button>
        <button class="btn btn-outline-secondary" data-metric="impressions">Impressions</button>
        <button class="btn btn-outline-secondary" data-metric="leads">Leads</button>
        <button class="btn btn-outline-secondary" data-metric="users">Users</button>
      </div>
      <!-- GroupBy -->
      <div class="btn-group btn-group-sm" id="trend-groupby">
        <button class="btn btn-outline-secondary active" data-groupby="day">Daily</button>
        <button class="btn btn-outline-secondary"        data-groupby="week">Weekly</button>
        <button class="btn btn-outline-secondary"        data-groupby="month">Monthly</button>
      </div>
      <!-- Chart type -->
      <div class="btn-group btn-group-sm" id="trend-charttype">
        <button class="btn btn-outline-secondary active" data-charttype="line"
                title="Line"><i class="bi bi-graph-up"></i></button>
        <button class="btn btn-outline-secondary" data-charttype="bar"
                title="Bar"><i class="bi bi-bar-chart-fill"></i></button>
        <button class="btn btn-outline-secondary" data-charttype="area"
                title="Area"><i class="bi bi-reception-4"></i></button>
      </div>
    </div>
  </div>
  <div class="card-body" style="position:relative;min-height:260px;">
    <div id="trend-loading" class="text-center py-5 text-muted" style="display:none;">
      <div class="spinner-border spinner-border-sm me-2"></div>Loading trend data…
    </div>
    <canvas id="trend-chart" style="max-height:280px;"></canvas>
  </div>
</div>

<!-- ── LEAD CATEGORIES ─────────────────────────────────────────────────── -->
<?php if (!empty($cats)): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header fw-semibold">Lead Categories</div>
  <div class="card-body py-2">
    <?php
    $maxTotal = max(1, ...array_column($cats, 'total'));
    $prevCatMap = [];
    if ($prev && !empty($prev['lead_category_totals'])) {
        $prevCatMap = is_array($prev['lead_category_totals']) ? $prev['lead_category_totals'] : (json_decode($prev['lead_category_totals'], true) ?? []);
    }
    foreach ($cats as $cat):
        $total    = (int)$cat['total'];
        $barPct   = round($total / $maxTotal * 100);
        $prevTotal = (int)($prevCatMap[$cat['key']] ?? 0);
        $d        = $prevTotal > 0 ? delta($total, $prevTotal) : null;
    ?>
    <div class="d-flex align-items-center gap-3 py-2 border-bottom" style="min-height:52px;">
      <div style="width:110px;flex-shrink:0;">
        <div class="fw-medium small"><?= htmlspecialchars($cat['label']) ?></div>
        <?php if ($audience !== 'client' && ($cat['effective_cpl'] ?? 0) > 0): ?>
        <div style="font-size:.65rem;color:#94a3b8;">₹<?= number_format($cat['effective_cpl']) ?> CPL<?= $cat['using_override'] ? '*' : '' ?></div>
        <?php endif; ?>
      </div>
      <div style="flex:1;">
        <div class="progress" style="height:8px;background:#f1f5f9;border-radius:4px;">
          <div class="progress-bar" style="width:<?= $barPct ?>%;background:#7c3aed;border-radius:4px;transition:width .4s;"></div>
        </div>
      </div>
      <div style="width:50px;text-align:right;font-weight:700;font-size:1rem;"><?= number_format($total) ?></div>
      <div style="width:130px;">
        <?php if ($d !== null): ?>
        <span style="color:<?= $d['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.75rem;font-weight:600;">
          <?= $d['up'] ? '▲ +' : '▼ ' ?><?= number_format($d['abs']) ?> / <?= $d['up'] ? '+' : '' ?><?= $d['pct'] ?>%
        </span>
        <div style="color:#94a3b8;font-size:.65rem;">prev: <?= number_format($prevTotal) ?></div>
        <?php else: ?>
        <span style="color:#94a3b8;font-size:.72rem;">no comparison</span>
        <?php endif; ?>
      </div>
      <?php if ($audience !== 'client' && ($cat['value'] ?? 0) > 0): ?>
      <div style="width:80px;text-align:right;color:#0284c7;font-size:.8rem;font-weight:600;">
        ₹<?= number_format($cat['value']) ?>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- ── GSC BRANDED / NON-BRANDED ──────────────────────────────────────── -->
<div class="row g-3 mb-4">
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header fw-semibold">Branded vs Non-Branded</div>
      <div class="card-body">
        <?php
        $bc  = v($s,'branded_clicks');      $nbc = v($s,'non_branded_clicks');
        $bi  = v($s,'branded_impressions'); $nbi = v($s,'non_branded_impressions');
        $pbc = $prev ? v($prev,'branded_clicks') : null;
        $pnbc= $prev ? v($prev,'non_branded_clicks') : null;
        $pbi = $prev ? v($prev,'branded_impressions') : null;
        $pnbi= $prev ? v($prev,'non_branded_impressions') : null;
        $tc  = max(1, $bc + $nbc);
        $ti  = max(1, $bi + $nbi);
        $bPct= round($bc / $tc * 100);
        ?>
        <div class="row g-3">
          <?php foreach ([
            ['Branded Clicks',       $bc,  $pbc,  $bPct,       'primary'],
            ['Non-Branded Clicks',   $nbc, $pnbc, 100-$bPct,  'success'],
            ['Branded Impr.',        $bi,  $pbi,  round($bi/$ti*100), 'primary'],
            ['Non-Branded Impr.',    $nbi, $pnbi, round($nbi/$ti*100),'success'],
          ] as [$lbl, $val, $pval, $pct, $col]): ?>
          <div class="col-6">
            <div style="font-size:.75rem;color:#64748b;margin-bottom:3px;"><?= $lbl ?></div>
            <div style="font-size:1.1rem;font-weight:700;"><?= number_format($val) ?></div>
            <div class="progress my-1" style="height:5px;">
              <div class="progress-bar bg-<?= $col ?>" style="width:<?= $pct ?>%"></div>
            </div>
            <div class="d-flex justify-content-between">
              <span style="font-size:.65rem;color:#94a3b8;"><?= $pct ?>% of total</span>
              <?php if ($pval !== null): $d3 = delta($val, $pval); ?>
              <span style="color:<?= $d3['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.65rem;font-weight:600;">
                <?= $d3['up'] ? '+' : '' ?><?= $d3['pct'] ?>%
              </span>
              <?php endif; ?>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- AI / LLM -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header fw-semibold">AI / LLM Traffic</div>
      <div class="card-body">
        <?php
        $llmSources = ['chatgpt' => 'ChatGPT','claude' => 'Claude','perplexity' => 'Perplexity','gemini' => 'Gemini','copilot' => 'Copilot'];
        $llmMax = max(1, ...array_map(fn($k) => v($s, 'ref_'.$k), array_keys($llmSources)));
        foreach ($llmSources as $k => $lbl):
            $val  = v($s, 'ref_'.$k);
            $pval = $prev ? v($prev, 'ref_'.$k) : null;
            $barW = round($val / $llmMax * 100);
            $d4   = ($pval !== null && $pval > 0) ? delta($val, $pval) : null;
        ?>
        <div class="d-flex align-items-center gap-2 mb-2">
          <div style="width:72px;font-size:.75rem;color:#64748b;flex-shrink:0;"><?= $lbl ?></div>
          <div class="flex-grow-1">
            <div class="progress" style="height:6px;background:#f1f5f9;">
              <div class="progress-bar" style="width:<?= $barW ?>%;background:#a78bfa;"></div>
            </div>
          </div>
          <div style="width:40px;text-align:right;font-size:.85rem;font-weight:600;"><?= number_format($val) ?></div>
          <?php if ($d4): ?>
          <div style="width:60px;text-align:right;font-size:.65rem;font-weight:600;color:<?= $d4['up'] ? '#16a34a' : '#dc2626' ?>;">
            <?= $d4['up'] ? '+' : '' ?><?= $d4['pct'] ?>%
          </div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <div class="border-top pt-2 mt-2 d-flex justify-content-between align-items-center">
          <span style="font-size:.75rem;color:#64748b;">AI Overview Appearances</span>
          <strong><?= number_format(v($s,'ai_overview')) ?></strong>
          <?php if ($prev): $d5 = delta(v($s,'ai_overview'), v($prev,'ai_overview')); ?>
          <span style="color:<?= $d5['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.7rem;font-weight:600;">
            <?= $d5['up'] ? '+' : '' ?><?= $d5['pct'] ?>%
          </span>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── CHANNEL BREAKDOWN (team) ──────────────────────────────────────────── -->
<?php if ($audience === 'team'): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header fw-semibold">Traffic Channels</div>
  <div class="card-body">
    <div class="row g-3">
      <?php foreach ([
        ['Organic',  'organic_sessions',  '#7c3aed'],
        ['Paid',     'paid_sessions',     '#0284c7'],
        ['Direct',   'direct_sessions',   '#0891b2'],
        ['Social',   'social_sessions',   '#16a34a'],
        ['Referral', 'referral_sessions', '#d97706'],
      ] as [$lbl, $key, $col]):
        $val = v($s,$key);
        $pval= $prev ? v($prev,$key) : null;
        $total = max(1, v($s,'organic_sessions')+v($s,'paid_sessions')+v($s,'direct_sessions')+v($s,'social_sessions')+v($s,'referral_sessions'));
        $pct = round($val/$total*100);
        $d6  = ($pval !== null && $pval > 0) ? delta($val, $pval) : null;
      ?>
      <div class="col-6 col-md-4 col-lg-2">
        <div class="rpt-card text-center h-100">
          <div class="rpt-label"><?= $lbl ?></div>
          <div style="font-size:1.3rem;font-weight:700;color:<?= $col ?>;"><?= number_format($val) ?></div>
          <div style="font-size:.7rem;color:#94a3b8;"><?= $pct ?>% of total</div>
          <?php if ($d6): ?>
          <div style="color:<?= $d6['up'] ? '#16a34a' : '#dc2626' ?>;font-size:.72rem;font-weight:600;margin-top:3px;">
            <?= $d6['up'] ? '▲ +' : '▼ ' ?><?= number_format($d6['abs']) ?> (<?= $d6['up'] ? '+' : '' ?><?= $d6['pct'] ?>%)
          </div>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- ── TOP QUERIES ─────────────────────────────────────────────────────── -->
<?php if ($audience !== 'business_owner'): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header fw-semibold d-flex justify-content-between align-items-center">
    <span>Top Queries</span>
    <span class="text-muted small" id="queries-count"></span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover align-middle mb-0 no-datatable">
      <thead class="table-light">
        <tr>
          <th>Query</th>
          <th class="text-end">Clicks</th>
          <th class="text-end">Impr.</th>
          <th class="text-end">CTR</th>
          <th class="text-end">Position</th>
        </tr>
      </thead>
      <tbody id="queries-tbody">
        <tr><td colspan="5" class="text-center py-3 text-muted"><div class="spinner-border spinner-border-sm me-1"></div>Loading…</td></tr>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<!-- ── EVENT DRILL-DOWN (team) ──────────────────────────────────────────── -->
<?php if ($audience === 'team' && !empty($report['event_drill'])): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header fw-semibold">Lead Event Drill-Down</div>
  <div class="table-responsive">
    <table class="table table-sm align-middle mb-0 no-datatable">
      <thead class="table-light">
        <tr><th>Category</th><th>Event Name</th><th class="text-end">Organic Count</th></tr>
      </thead>
      <tbody>
        <?php foreach ($report['event_drill'] as $e): ?>
        <tr>
          <td><span class="badge" style="background:#7c3aed22;color:#7c3aed;"><?= htmlspecialchars($e['category_key']) ?></span></td>
          <td class="small"><?= htmlspecialchars($e['event_name']) ?></td>
          <td class="text-end fw-semibold"><?= number_format($e['organic_count']) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<!-- ── PAGE-LEVEL (team) ──────────────────────────────────────────────── -->
<?php if ($audience === 'team'): ?>
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header fw-semibold d-flex justify-content-between align-items-center">
    <span>Page Performance</span>
    <input type="text" id="page-search" class="form-control form-control-sm ms-auto" style="max-width:200px;" placeholder="Filter pages…">
  </div>
  <div class="table-responsive" style="max-height:400px;overflow-y:auto;">
    <table class="table table-sm table-hover align-middle mb-0 no-datatable">
      <thead class="table-light sticky-top">
        <tr><th>URL</th><th class="text-end">Sessions</th><th class="text-end">Clicks</th><th class="text-end">Impr.</th><th class="text-end">CTR</th><th class="text-end">Position</th></tr>
      </thead>
      <tbody id="pages-tbody">
        <tr><td colspan="6" class="text-center py-3 text-muted"><div class="spinner-border spinner-border-sm me-1"></div>Loading…</td></tr>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php endif; // !error ?>

<!-- ── STYLES ─────────────────────────────────────────────────────────── -->
<style>
.rpt-card { background:#fff; border-radius:10px; padding:14px 12px; box-shadow:0 1px 4px rgba(0,0,0,.06); }
.rpt-label { font-size:.72rem; color:#64748b; text-transform:uppercase; letter-spacing:.04em; margin-bottom:4px; }
.rpt-big   { font-size:1.7rem; font-weight:800; line-height:1.1; color:#0f172a; }
.rpt-med   { font-size:1.25rem; font-weight:700; color:#0f172a; }
.rpt-sub   { font-size:.7rem; color:#94a3b8; margin-top:2px; }
@media print {
  #sidebar,.savit-topbar,form,.btn-group,.dropdown,#trend-chart,#trend-loading,.card-header .btn-group { display:none!important; }
  #main-content { margin-left:0!important; }
  .card { break-inside:avoid; box-shadow:none!important; border:1px solid #e2e8f0!important; }
}
</style>

<!-- ── SCRIPTS ────────────────────────────────────────────────────────── -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
(function () {
  const base      = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  const projectId = <?= $_pid ?>;
  const start     = <?= json_encode((string)$start) ?>;
  const end       = <?= json_encode((string)$end) ?>;
  const audience  = <?= json_encode((string)$audience) ?>;

  function esc(s) {
    const d = document.createElement('div');
    d.appendChild(document.createTextNode(String(s || '')));
    return d.innerHTML;
  }

  // ── Queries ───────────────────────────────────────────────────────────
  (async () => {
    const tbody = document.getElementById('queries-tbody');
    const cnt   = document.getElementById('queries-count');
    if (!tbody) return;
    try {
      const limit = audience === 'team' ? 100 : 10;
      const r = await fetch(`${base}/api/projects/${projectId}/query-data?start=${start}&end=${end}&limit=${limit}`);
      const j = await r.json();
      const rows = j.data || [];
      if (cnt) cnt.textContent = rows.length + ' queries';
      if (!rows.length) { tbody.innerHTML = '<tr><td colspan="5" class="text-muted text-center py-3">No query data for this period.</td></tr>'; return; }
      tbody.innerHTML = rows.map(q => `<tr>
        <td class="small">${esc(q.query)}</td>
        <td class="text-end small fw-medium">${(+q.clicks).toLocaleString()}</td>
        <td class="text-end small">${(+q.impressions).toLocaleString()}</td>
        <td class="text-end small">${(q.ctr * 100).toFixed(2)}%</td>
        <td class="text-end small">${(+q.position).toFixed(1)}</td>
      </tr>`).join('');
    } catch (e) { tbody.innerHTML = '<tr><td colspan="5" class="text-muted text-center">Failed to load queries.</td></tr>'; }
  })();

  // ── Pages ─────────────────────────────────────────────────────────────
  let allPages = [];
  (async () => {
    const tbody = document.getElementById('pages-tbody');
    if (!tbody) return;
    try {
      const r = await fetch(`${base}/api/projects/${projectId}/page-data?start=${start}&end=${end}&limit=200`);
      const j = await r.json();
      allPages = j.data || [];
      renderPages(allPages);
    } catch { tbody.innerHTML = '<tr><td colspan="6" class="text-muted text-center">Failed to load pages.</td></tr>'; }
  })();
  function renderPages(rows) {
    const tbody = document.getElementById('pages-tbody');
    if (!tbody) return;
    if (!rows.length) { tbody.innerHTML = '<tr><td colspan="6" class="text-muted text-center py-3">No page data.</td></tr>'; return; }
    tbody.innerHTML = rows.map(p => `<tr>
      <td class="small text-truncate" style="max-width:260px;" title="${esc(p.url)}">${esc(p.url)}</td>
      <td class="text-end small">${(+p.ga4_sessions).toLocaleString()}</td>
      <td class="text-end small">${(+p.gsc_clicks).toLocaleString()}</td>
      <td class="text-end small">${(+p.gsc_impressions).toLocaleString()}</td>
      <td class="text-end small">${(p.gsc_ctr * 100).toFixed(2)}%</td>
      <td class="text-end small">${(+p.gsc_position).toFixed(1)}</td>
    </tr>`).join('');
  }
  document.getElementById('page-search')?.addEventListener('input', e => {
    const q = e.target.value.toLowerCase();
    renderPages(q ? allPages.filter(p => p.url.toLowerCase().includes(q)) : allPages);
  });

  // ── Trend chart ───────────────────────────────────────────────────────
  let chart     = null;
  // Restore last selected metric from sessionStorage
  let currentMetric    = sessionStorage.getItem('rpt_metric')    || 'sessions';
  let currentGroupBy   = sessionStorage.getItem('rpt_groupby')   || 'day';
  let currentChartType = sessionStorage.getItem('rpt_charttype') || 'line';
  // Highlight the restored buttons
  document.querySelectorAll('#trend-metric [data-metric]').forEach(b => {
    b.classList.toggle('btn-dark', b.dataset.metric === currentMetric);
    b.classList.toggle('btn-outline-secondary', b.dataset.metric !== currentMetric);
  });
  document.querySelectorAll('#trend-groupby [data-groupby]').forEach(b => {
    b.classList.toggle('active', b.dataset.groupby === currentGroupBy);
  });
  document.querySelectorAll('#trend-charttype [data-charttype]').forEach(b => {
    b.classList.toggle('active', b.dataset.charttype === currentChartType);
  });

  const metricColors = {
    sessions:    '#7c3aed',
    clicks:      '#0284c7',
    impressions: '#0891b2',
    leads:       '#d97706',
    users:       '#16a34a',
  };

  async function loadTrend(metric, groupBy) {
    const canvas  = document.getElementById('trend-chart');
    const loading = document.getElementById('trend-loading');
    if (!canvas) return;

    loading.style.display = 'block';
    canvas.style.display  = 'none';

    try {
      const r = await fetch(`${base}/api/projects/${projectId}/trend?metric=${metric}&groupBy=${groupBy}&start=${start}&end=${end}`);
      const j = await r.json();
      const d = j.data;
      if (!d || d.error) { loading.textContent = d?.error || 'No trend data'; return; }

      loading.style.display = 'none';
      canvas.style.display  = 'block';

      const color  = metricColors[metric] || '#7c3aed';
      const isBar  = currentChartType === 'bar';
      const isArea = currentChartType === 'area';
      const chartType = isBar ? 'bar' : 'line';

      const datasets = [
        {
          label: d.period_label,
          data: d.current,
          borderColor: color,
          backgroundColor: isBar ? color + 'cc' : (isArea ? color + '28' : color + '18'),
          borderWidth: isBar ? 0 : 2.5,
          tension: isBar ? 0 : 0.35,
          fill: isBar ? false : (isArea ? true : false),
          pointRadius: isBar ? 0 : (d.current.length > 60 ? 0 : 3),
          pointHoverRadius: isBar ? 0 : 5,
          borderRadius: isBar ? 4 : 0,
        },
        {
          label: d.prev_period_label,
          data: d.previous,
          borderColor: '#94a3b8',
          backgroundColor: isBar ? '#94a3b866' : 'transparent',
          borderWidth: isBar ? 0 : 1.5,
          borderDash: isBar ? [] : [5, 4],
          tension: isBar ? 0 : 0.35,
          fill: false,
          pointRadius: 0,
          pointHoverRadius: isBar ? 0 : 4,
          borderRadius: isBar ? 4 : 0,
        },
      ];

      if (chart) chart.destroy();
      chart = new Chart(canvas, {
        type: chartType,
        data: { labels: d.labels, datasets },
        options: {
          responsive: true,
          maintainAspectRatio: true,
          interaction: { mode: 'index', intersect: false },
          plugins: {
            legend: { position: 'top', labels: { usePointStyle: true, boxWidth: 8, font: { size: 11 } } },
            tooltip: {
              callbacks: {
                label: ctx => `${ctx.dataset.label}: ${ctx.parsed.y.toLocaleString()}`,
              },
            },
          },
          scales: {
            x: {
              stacked: false,
              grid: { display: false },
              ticks: { font: { size: 11 }, maxTicksLimit: 14 },
            },
            y: {
              beginAtZero: true,
              grid: { color: '#f1f5f9' },
              ticks: { font: { size: 11 }, callback: v => v >= 1000 ? (v/1000).toFixed(1)+'k' : v },
            },
          },
        },
      });
    } catch (e) {
      loading.innerHTML = '<i class="bi bi-exclamation-triangle text-warning me-1"></i>Trend unavailable — run the tracker to fetch data, or check Google OAuth connection.';
      loading.style.display = 'block';
      canvas.style.display  = 'none';
    }
  }

  // Metric toggle
  document.getElementById('trend-metric')?.addEventListener('click', e => {
    const btn = e.target.closest('[data-metric]');
    if (!btn) return;
    document.querySelectorAll('#trend-metric .btn').forEach(b => { b.classList.remove('btn-dark'); b.classList.add('btn-outline-secondary'); });
    btn.classList.remove('btn-outline-secondary'); btn.classList.add('btn-dark');
    currentMetric = btn.dataset.metric;
    sessionStorage.setItem('rpt_metric', currentMetric);
    loadTrend(currentMetric, currentGroupBy);
  });

  // GroupBy toggle
  document.getElementById('trend-groupby')?.addEventListener('click', e => {
    const btn = e.target.closest('[data-groupby]');
    if (!btn) return;
    document.querySelectorAll('#trend-groupby .btn').forEach(b => { b.classList.remove('active'); });
    btn.classList.add('active');
    currentGroupBy = btn.dataset.groupby;
    sessionStorage.setItem('rpt_groupby', currentGroupBy);
    loadTrend(currentMetric, currentGroupBy);
  });

  // Chart type toggle
  document.getElementById('trend-charttype')?.addEventListener('click', e => {
    const btn = e.target.closest('[data-charttype]');
    if (!btn) return;
    document.querySelectorAll('#trend-charttype .btn').forEach(b => { b.classList.remove('active'); });
    btn.classList.add('active');
    currentChartType = btn.dataset.charttype;
    sessionStorage.setItem('rpt_charttype', currentChartType);
    loadTrend(currentMetric, currentGroupBy);
  });

  // Initial load
  loadTrend(currentMetric, currentGroupBy);

  // ── Auto-fetch comparison period if missing ────────────────────────────
  (async function autoFetchComparison() {
    const badge = document.getElementById('cmp-fetch-badge');
    if (!badge) return; // comparison data already present

    <?php if (!$hasComparison && $cmpStart && $cmpEnd): ?>
    try {
      const r = await fetch(`${base}/api/projects/${projectId}/fetch-comparison`, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ cmp_start: '<?= $cmpStart ?>', cmp_end: '<?= $cmpEnd ?>' }),
      });
      const j = await r.json();
      if (j.success) {
        badge.innerHTML = '<i class="bi bi-check-circle me-1"></i>Done — reloading…';
        badge.className = 'badge bg-success ms-1';
        setTimeout(() => window.location.reload(), 800);
      } else {
        badge.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i>' + (j.message || 'Fetch failed');
        badge.className = 'badge bg-warning text-dark ms-1';
      }
    } catch (e) {
      badge.innerHTML = '<i class="bi bi-x-circle me-1"></i>Network error';
      badge.className = 'badge bg-danger ms-1';
    }
    <?php endif; ?>
  })();
})();
</script>
