<?php
$base    = $analyticsBase ?? '';
$pid     = (int)$project['id'];
$snaps   = $snapshots ?? [];
$grouped = $grouped   ?? [];

$metrics = [
    ['key' => 'organic_sessions',  'label' => 'Sessions',    'fmt' => 'n',   'invertGood' => false],
    ['key' => 'gsc_clicks',        'label' => 'Clicks',      'fmt' => 'n',   'invertGood' => false],
    ['key' => 'gsc_impressions',   'label' => 'Impressions', 'fmt' => 'n',   'invertGood' => false],
    ['key' => 'gsc_position',      'label' => 'Position',    'fmt' => 'dec', 'invertGood' => true],
    ['key' => 'total_leads',       'label' => 'Leads',       'fmt' => 'n',   'invertGood' => false],
    ['key' => 'llm_total',         'label' => 'AI/LLM',      'fmt' => 'n',   'invertGood' => false],
];

function snapFmt(float $v, string $f): string {
    return match($f) {
        'dec' => number_format($v, 1),
        'pct' => number_format($v * 100, 1) . '%',
        default => number_format($v),
    };
}
function snapDelta(array $cur, ?array $prev, string $key, bool $invertGood): array {
    $c = (float)($cur[$key] ?? 0);
    $p = $prev ? (float)($prev[$key] ?? 0) : null;
    if ($p === null || $p == 0) return ['c' => $c, 'p' => null, 'pct' => null, 'dir' => 0, 'good' => null];
    $pct = round(($c - $p) / $p * 100, 1);
    $up  = $c >= $p;
    return ['c' => $c, 'p' => $p, 'pct' => $pct, 'dir' => $up ? 1 : -1, 'good' => $invertGood ? !$up : $up];
}
?>
<script>
(function(){
  try {
    localStorage.setItem('savit_project', JSON.stringify({
      id: <?= $pid ?>,
      name: <?= json_encode($project['business_name'] ?? '') ?>,
      domain: <?= json_encode($project['website_url'] ?? '') ?>
    }));
    if (window.savitProject) window.savitProject.set(<?= $pid ?>, <?= json_encode($project['business_name'] ?? '') ?>, <?= json_encode($project['website_url'] ?? '') ?>);
  } catch(_) {}
})();
</script>

<!-- Page header -->
<div class="d-flex align-items-center gap-3 mb-4">
  <a href="<?= htmlspecialchars($base) ?>/" class="btn btn-sm btn-light"><i class="bi bi-arrow-left"></i></a>
  <div class="flex-grow-1">
    <h4 class="fw-bold mb-0"><?= htmlspecialchars($project['business_name']) ?></h4>
    <p class="text-muted small mb-0">
      <?= htmlspecialchars($project['business_category'] ?? '') ?>
      <?php if ($project['manager_name'] ?? ''): ?>&nbsp;·&nbsp;Manager: <?= htmlspecialchars($project['manager_name']) ?><?php endif; ?>
      <?php if ($project['website_url'] ?? ''): ?>&nbsp;·&nbsp;<a href="<?= htmlspecialchars($project['website_url']) ?>" target="_blank" class="text-muted"><?= htmlspecialchars($project['website_url']) ?></a><?php endif; ?>
    </p>
  </div>
  <a href="<?= htmlspecialchars(str_replace('/Analytics/public', '', $base)) ?>/Content/public/projects/<?= $pid ?>/edit#tab-tracking"
     class="btn btn-sm btn-outline-secondary"><i class="bi bi-gear me-1"></i>Settings</a>
</div>

<!-- Run Tracker controls -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-body py-2">
    <div class="d-flex align-items-center gap-2 flex-wrap">
      <span class="small fw-semibold text-muted">Run Tracker:</span>
      <div class="btn-group btn-group-sm" id="period-presets">
        <button class="btn btn-outline-secondary" data-days="7">7d</button>
        <button class="btn btn-outline-secondary active" data-days="30">30d</button>
        <button class="btn btn-outline-secondary" data-days="90">90d</button>
        <button class="btn btn-outline-secondary" data-days="180">6mo</button>
        <button class="btn btn-outline-secondary" data-days="365">YoY</button>
      </div>
      <input type="date" id="date-start" class="form-control form-control-sm" style="width:130px;" value="<?= date('Y-m-d', strtotime('-30 days')) ?>">
      <span class="text-muted small">–</span>
      <input type="date" id="date-end" class="form-control form-control-sm" style="width:130px;" value="<?= date('Y-m-d') ?>">
      <button class="btn btn-sm btn-primary" id="fetch-btn" type="button">
        <i class="bi bi-play-fill me-1"></i>Run
      </button>
      <span id="fetch-status" class="small text-muted"></span>
      <div class="ms-auto d-flex gap-2">
        <a href="#" id="report-link" class="btn btn-sm btn-outline-primary">
          <i class="bi bi-file-earmark-bar-graph me-1"></i>Report
        </a>
        <a href="#" id="slides-link" class="btn btn-sm btn-outline-secondary" target="_blank">
          <i class="bi bi-easel me-1"></i>Slides
        </a>
      </div>
    </div>
  </div>
</div>

<?php
// ── Snapshot history: grouped by period length ──────────────────────────────
// Only compare same-length periods. Each snapshot's _prev is the true previous
// same-duration period, looked up from DB (not just the next row in list).

// Pre-compute per-group max values for bar scaling
$groupMaxVals = [];
foreach ($grouped as $gLabel => $gSnaps) {
    foreach ($metrics as $m) {
        $vals = array_map(fn($s) => (float)($s[$m['key']] ?? 0), $gSnaps);
        $groupMaxVals[$gLabel][$m['key']] = max(1, ...$vals);
    }
}

$groupLabels = [
    '7d'  => ['label' => '7-Day Windows',  'desc' => 'Weekly tracker runs — each compared to the immediately preceding 7-day window'],
    '14d' => ['label' => '14-Day Windows', 'desc' => 'Fortnightly tracker runs — each vs the preceding 14 days'],
    '30d' => ['label' => 'Monthly Windows','desc' => 'Monthly tracker runs — each vs the preceding 30-day window'],
    '90d' => ['label' => 'Quarterly',      'desc' => 'Quarterly windows — each vs the preceding 90 days'],
    '180d'=> ['label' => 'Half-Yearly',    'desc' => '180-day windows — each vs the preceding 6 months'],
    'YoY' => ['label' => 'Year-over-Year', 'desc' => 'Annual windows — each vs same period previous year'],
];
?>

<div class="row g-4">
  <!-- Snapshot History grouped -->
  <div class="col-12">
    <?php if (empty($grouped)): ?>
    <div class="card border-0 shadow-sm">
      <div class="card-body text-center text-muted py-5">
        <i class="bi bi-graph-up-arrow d-block mb-2 opacity-25" style="font-size:2.5rem;"></i>
        No snapshots yet. Select a period above and click <strong>Run</strong>.
      </div>
    </div>
    <?php else: ?>

    <?php foreach ($grouped as $gLabel => $gSnaps):
      $gInfo    = $groupLabels[$gLabel] ?? ['label' => $gLabel, 'desc' => ''];
      $gMaxVals = $groupMaxVals[$gLabel];
      $isFirst  = array_key_first($grouped) === $gLabel;
    ?>
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-header d-flex align-items-center gap-2 py-2"
           style="cursor:pointer;" data-bs-toggle="collapse" data-bs-target="#group-<?= $gLabel ?>">
        <span class="badge bg-primary-subtle text-primary" style="font-size:.72rem;font-weight:700;"><?= $gLabel ?></span>
        <span class="fw-semibold"><?= $gInfo['label'] ?></span>
        <span class="text-muted small"><?= $gInfo['desc'] ?></span>
        <span class="ms-auto text-muted small"><?= count($gSnaps) ?> run<?= count($gSnaps) !== 1 ? 's' : '' ?>
          <i class="bi bi-chevron-down ms-1" style="font-size:.7rem;"></i></span>
      </div>

      <div class="collapse <?= $isFirst ? 'show' : '' ?>" id="group-<?= $gLabel ?>">
        <!-- Legend (first group only) -->
        <?php if ($isFirst): ?>
        <div class="d-flex gap-3 align-items-center px-3 pt-2" style="font-size:.72rem;color:#64748b;">
          <span><span style="display:inline-block;width:8px;height:8px;border-radius:2px;background:#22c55e;margin-right:3px;"></span>Better vs prev</span>
          <span><span style="display:inline-block;width:8px;height:8px;border-radius:2px;background:#ef4444;margin-right:3px;"></span>Worse vs prev</span>
          <span><span style="display:inline-block;width:8px;height:8px;border-radius:2px;background:#e2e8f0;margin-right:3px;"></span>No prior data to compare</span>
        </div>
        <?php endif; ?>

        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0 no-datatable" style="min-width:860px;">
            <thead class="table-light" style="font-size:.72rem;">
              <tr>
                <th style="min-width:140px;">Period</th>
                <?php foreach ($metrics as $m): ?>
                <th class="text-end" style="min-width:100px;"><?= $m['label'] ?></th>
                <?php endforeach; ?>
                <th class="text-center" style="min-width:65px;">Health</th>
                <th style="min-width:55px;"></th>
              </tr>
            </thead>
            <tbody>
            <?php foreach ($gSnaps as $idx => $cur):
              $prev     = $cur['_prev'] ?? null;
              $isLatest = $idx === 0;

              // Health from sessions + leads trend vs true previous period
              $sesD = snapDelta($cur, $prev, 'organic_sessions', false);
              $ldsD = snapDelta($cur, $prev, 'total_leads', false);
              $rowH = 50;
              if ($sesD['pct'] !== null) $rowH += min(20, max(-20, (int)($sesD['pct'] / 2.5)));
              if ($ldsD['pct'] !== null) $rowH += min(20, max(-20, (int)($ldsD['pct'] / 2.5)));
              $rowH  = max(0, min(100, $rowH));
              $hCol  = $rowH >= 70 ? '#22c55e' : ($rowH >= 50 ? '#f59e0b' : '#ef4444');
            ?>
            <tr style="<?= $isLatest ? 'background:#f8fafc;' : '' ?>">
              <td style="font-size:.78rem;white-space:nowrap;">
                <?php if ($isLatest): ?>
                <span class="badge bg-primary-subtle text-primary me-1" style="font-size:.58rem;">Latest</span>
                <?php endif; ?>
                <strong><?= date('d M', strtotime($cur['period_start'])) ?></strong>
                &nbsp;–&nbsp;<?= date('d M Y', strtotime($cur['period_end'])) ?>
                <?php if ($prev): ?>
                <div style="font-size:.63rem;color:#94a3b8;">
                  vs <?= date('d M', strtotime($prev['period_start'])) ?> – <?= date('d M Y', strtotime($prev['period_end'])) ?>
                </div>
                <?php endif; ?>
              </td>

              <?php foreach ($metrics as $m):
                $d    = snapDelta($cur, $prev, $m['key'], $m['invertGood']);
                $val  = (float)($cur[$m['key']] ?? 0);
                $mMax = $gMaxVals[$m['key']];
                $barW = $mMax > 0 ? min(100, round($val / $mMax * 100)) : 0;
                $barFill = $d['good'] === null ? '#cbd5e1' : ($d['good'] ? '#22c55e' : '#ef4444');
                $textC   = $d['good'] === null ? '#94a3b8' : ($d['good'] ? '#16a34a' : '#dc2626');
              ?>
              <td style="min-width:100px;padding:6px 8px;">
                <div class="d-flex align-items-center justify-content-end gap-1">
                  <span style="font-size:.82rem;font-weight:<?= $isLatest ? 600 : 400 ?>;"><?= snapFmt($val, $m['fmt']) ?></span>
                  <?php if ($d['pct'] !== null): $sign = $d['dir'] >= 0 ? '+' : ''; ?>
                  <span style="font-size:.65rem;font-weight:700;color:<?= $textC ?>;">
                    <?= $d['dir'] >= 0 ? '▲' : '▼' ?><?= $sign . $d['pct'] ?>%
                  </span>
                  <?php endif; ?>
                </div>
                <div style="height:4px;background:#f1f5f9;border-radius:2px;overflow:hidden;margin-top:3px;">
                  <div style="height:100%;width:<?= $barW ?>%;background:<?= $barFill ?>;border-radius:2px;"></div>
                </div>
                <?php if ($d['p'] !== null): ?>
                <div style="font-size:.62rem;color:#94a3b8;text-align:right;margin-top:1px;">prev: <?= snapFmt($d['p'], $m['fmt']) ?></div>
                <?php endif; ?>
              </td>
              <?php endforeach; ?>

              <td class="text-center" style="padding:6px 8px;">
                <span style="font-size:.8rem;font-weight:700;color:<?= $hCol ?>;"><?= $rowH ?></span>
                <div style="height:3px;background:#f1f5f9;border-radius:2px;overflow:hidden;width:36px;margin:2px auto 0;">
                  <div style="height:100%;width:<?= $rowH ?>%;background:<?= $hCol ?>;border-radius:2px;"></div>
                </div>
              </td>

              <td class="text-end" style="padding:6px 8px;">
                <a href="<?= htmlspecialchars($base) ?>/report?project=<?= $pid ?>&start=<?= $cur['period_start'] ?>&end=<?= $cur['period_end'] ?>&audience=client"
                   class="btn btn-outline-secondary py-0 px-2" style="font-size:.68rem;white-space:nowrap;">View →</a>
              </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?></div>

  <!-- Project Config summary (compact) -->
  <div class="col-md-6 col-lg-4">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header fw-semibold py-2 d-flex justify-content-between align-items-center">
        Project Config
        <a href="<?= htmlspecialchars(str_replace('/Analytics/public', '', $base)) ?>/Content/public/projects/<?= $pid ?>/edit#tab-tracking"
           class="btn btn-xs btn-outline-secondary py-0 px-2" style="font-size:.7rem;">Edit</a>
      </div>
      <div class="card-body small">
        <?php $configItems = [
          'GA4 Property ID' => $project['ga4_property_id'] ?? null,
          'GSC Site URL'    => $project['gsc_site_url']    ?? null,
          'Brand Regex'     => $project['brand_term_regex'] ?? null,
          'Revenue Managed' => $project['revenue_managed'] ? '₹' . number_format($project['revenue_managed']) : null,
          'Business Category' => $project['business_category'] ?? null,
          'Manager'         => $project['manager_name']     ?? null,
          'Lead Categories' => count($project['lead_categories'] ?? []) . ' configured',
        ]; ?>
        <?php foreach ($configItems as $label => $val): ?>
        <div class="d-flex justify-content-between py-1 border-bottom" style="font-size:.8rem;">
          <span class="text-muted"><?= $label ?></span>
          <span class="fw-medium text-end" style="max-width:55%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= htmlspecialchars($val ?? '—') ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- Lead categories quick view -->
  <?php if (!empty($project['lead_categories'])): ?>
  <div class="col-md-6 col-lg-4">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header fw-semibold py-2">Lead Categories</div>
      <div class="card-body py-2">
        <?php foreach ($project['lead_categories'] as $cat): ?>
        <div class="d-flex justify-content-between align-items-center py-1 border-bottom" style="font-size:.8rem;">
          <span class="fw-medium"><?= htmlspecialchars($cat['label'] ?? $cat['key']) ?></span>
          <span class="text-muted"><?= count($cat['events'] ?? []) ?> event<?= count($cat['events'] ?? []) !== 1 ? 's' : '' ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Latest snapshot KPI strip -->
  <?php if (!empty($snaps)): $latest = $snaps[0]; ?>
  <div class="col-12">
    <div class="card border-0 shadow-sm">
      <div class="card-header fw-semibold py-2">Latest Snapshot KPIs
        <span class="text-muted small ms-2"><?= date('d M', strtotime($latest['period_start'])) ?> – <?= date('d M Y', strtotime($latest['period_end'])) ?></span>
      </div>
      <div class="card-body">
        <div class="row g-2">
          <?php
          $kpis = [
            ['label'=>'Sessions',    'val'=>$latest['organic_sessions']  ?? 0, 'color'=>'#7c3aed'],
            ['label'=>'Clicks',      'val'=>$latest['gsc_clicks']        ?? 0, 'color'=>'#0284c7'],
            ['label'=>'Impressions', 'val'=>$latest['gsc_impressions']   ?? 0, 'color'=>'#0891b2'],
            ['label'=>'Position',    'val'=>number_format($latest['gsc_position'] ?? 0, 1), 'color'=>'#64748b', 'noFmt'=>true],
            ['label'=>'Leads',       'val'=>$latest['total_leads']       ?? 0, 'color'=>'#d97706'],
            ['label'=>'Overall Users','val'=>$latest['overall_users']    ?? 0, 'color'=>'#16a34a'],
            ['label'=>'AI/LLM',      'val'=>$latest['llm_total']         ?? 0, 'color'=>'#8b5cf6'],
            ['label'=>'Branded Imp.','val'=>$latest['branded_impressions'] ?? 0, 'color'=>'#0369a1'],
          ];
          foreach ($kpis as $k): ?>
          <div class="col-6 col-md-3 col-lg-2">
            <div style="background:#f8fafc;border-radius:8px;padding:10px 12px;border-left:3px solid <?= $k['color'] ?>;">
              <div style="font-size:.68rem;color:#64748b;text-transform:uppercase;letter-spacing:.04em;"><?= $k['label'] ?></div>
              <div style="font-size:1.2rem;font-weight:700;color:<?= $k['color'] ?>;">
                <?= isset($k['noFmt']) ? $k['val'] : number_format($k['val']) ?>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
(function () {
  const base = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  const pid  = <?= $pid ?>;
  let start  = document.getElementById('date-start').value;
  let end    = document.getElementById('date-end').value;

  function updateLinks() {
    const qs = `project=${pid}&start=${start}&end=${end}&audience=client`;
    document.getElementById('report-link').href = base + '/report?' + qs;
    document.getElementById('slides-link').href = base + '/slides?' + qs;
  }
  updateLinks();

  document.getElementById('period-presets').addEventListener('click', e => {
    const btn = e.target.closest('[data-days]');
    if (!btn) return;
    document.querySelectorAll('#period-presets .btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const d = +btn.dataset.days;
    end   = new Date().toISOString().split('T')[0];
    start = new Date(Date.now() - d * 864e5).toISOString().split('T')[0];
    document.getElementById('date-start').value = start;
    document.getElementById('date-end').value   = end;
    updateLinks();
  });
  document.getElementById('date-start').addEventListener('change', e => { start = e.target.value; updateLinks(); });
  document.getElementById('date-end').addEventListener('change',   e => { end   = e.target.value; updateLinks(); });

  document.getElementById('fetch-btn').addEventListener('click', async () => {
    const btn    = document.getElementById('fetch-btn');
    const status = document.getElementById('fetch-status');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Running…';
    status.innerHTML = '<span class="text-muted">Fetching GA4 + GSC data…</span>';
    try {
      const r = await fetch(base + '/api/projects/' + pid + '/fetch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ start, end, period_type: 'custom' }),
      });
      const j = await r.json();
      if (j.data?.success || j.success) {
        btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Done';
        btn.className = btn.className.replace('btn-primary', 'btn-success');
        status.innerHTML = '<span class="text-success">Saved — reloading…</span>';
        setTimeout(() => location.reload(), 900);
      } else {
        status.innerHTML = `<span class="text-danger">${j.data?.message || j.message || 'Failed'}</span>`;
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-play-fill me-1"></i>Run';
      }
    } catch (e) {
      status.innerHTML = `<span class="text-danger">Error: ${e.message}</span>`;
      btn.disabled = false;
      btn.innerHTML = '<i class="bi bi-play-fill me-1"></i>Run';
    }
  });
})();
</script>
