<?php
$base     = $analyticsBase ?? '';
$audience = $audience ?? 'client';
$start    = $start ?? date('Y-m-d', strtotime('-30 days'));
$end      = $end   ?? date('Y-m-d');
?>

<div class="d-flex align-items-center justify-content-between mb-3">
  <div>
    <h4 class="fw-bold mb-0">Reports</h4>
    <p class="text-muted small mb-0">Select a project to view its report.</p>
  </div>
  <div class="d-flex gap-2 align-items-center">
    <div class="btn-group btn-group-sm" id="audience-preset">
      <button class="btn btn-outline-secondary <?= $audience === 'business_owner' ? 'active' : '' ?>" data-audience="business_owner">Business Owner</button>
      <button class="btn btn-outline-secondary <?= $audience === 'client'         ? 'active' : '' ?>" data-audience="client">Client</button>
      <button class="btn btn-outline-secondary <?= $audience === 'team'           ? 'active' : '' ?>" data-audience="team">Team</button>
    </div>
    <input type="date" id="date-start" class="form-control form-control-sm" style="width:140px;" value="<?= htmlspecialchars($start) ?>">
    <span class="text-muted small">to</span>
    <input type="date" id="date-end"   class="form-control form-control-sm" style="width:140px;" value="<?= htmlspecialchars($end) ?>">
  </div>
</div>

<!-- Search -->
<div class="mb-3">
  <input type="text" id="picker-search" class="form-control" placeholder="&#128269; Search projects by name, category or manager…" autocomplete="off">
</div>
<div id="picker-empty" class="text-center text-muted py-5 d-none">
  <i class="bi bi-search fs-2 d-block mb-2 opacity-50"></i>No projects match your search.
</div>

<div class="row g-3" id="project-grid">
<?php foreach ($projects as $p): ?>
  <div class="col-12 col-md-6 col-lg-4 project-card-col"
       data-name="<?= htmlspecialchars(strtolower($p['business_name'])) ?>"
       data-category="<?= htmlspecialchars(strtolower($p['business_category'] ?? '')) ?>"
       data-manager="<?= htmlspecialchars(strtolower($p['manager_name'] ?? '')) ?>">
    <a href="#" class="project-pick-link text-decoration-none" data-id="<?= (int)$p['id'] ?>">
      <div class="card border-0 shadow-sm h-100 hover-lift">
        <div class="card-body">
          <div class="d-flex align-items-start gap-2 mb-2">
            <div class="sb-logo sb-logo-sm" style="background:#a78bfa;color:#fff;flex-shrink:0;">
              <?= strtoupper(substr($p['business_name'], 0, 1)) ?>
            </div>
            <div>
              <div class="fw-semibold lh-sm"><?= htmlspecialchars($p['business_name']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($p['business_category'] ?? '') ?></div>
            </div>
          </div>
          <?php if (!empty($p['manager_name'])): ?>
          <div class="small text-muted mt-1"><i class="bi bi-person me-1"></i><?= htmlspecialchars($p['manager_name']) ?></div>
          <?php endif; ?>
        </div>
      </div>
    </a>
  </div>
<?php endforeach; ?>
</div>

<?php if (empty($projects)): ?>
<div class="text-center py-5 text-muted">
  <i class="bi bi-folder2-open fs-1 d-block mb-2"></i>
  No projects found. Add a project first via the Content Engine.
</div>
<?php endif; ?>

<style>
.hover-lift { transition: transform .15s, box-shadow .15s; }
.hover-lift:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.1) !important; }
.sb-logo-sm { width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.85rem; }
</style>

<script>
(function () {
  const base     = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  let audience   = document.querySelector('#audience-preset .active')?.dataset.audience || 'client';
  let startDate  = document.getElementById('date-start').value;
  let endDate    = document.getElementById('date-end').value;

  document.getElementById('audience-preset').addEventListener('click', e => {
    const btn = e.target.closest('[data-audience]');
    if (!btn) return;
    document.querySelectorAll('#audience-preset .btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    audience = btn.dataset.audience;
  });

  document.getElementById('date-start').addEventListener('change', e => startDate = e.target.value);
  document.getElementById('date-end').addEventListener('change',   e => endDate   = e.target.value);

  document.getElementById('project-grid').addEventListener('click', e => {
    const link = e.target.closest('.project-pick-link');
    if (!link) return;
    e.preventDefault();
    const id   = link.dataset.id;
    const card = link.closest('.project-card-col');
    const name = card?.dataset.name || '';
    try { localStorage.setItem('savit_project', JSON.stringify({ id: +id, name, domain: '' })); } catch(_){}
    window.location.href = `${base}/report?project=${id}&start=${startDate}&end=${endDate}&audience=${audience}`;
  });

  // ── Search / filter ───────────────────────────────────────────────────────
  document.getElementById('picker-search')?.addEventListener('input', e => {
    const q     = e.target.value.toLowerCase().trim();
    const cols  = document.querySelectorAll('#project-grid .project-card-col');
    let visible = 0;
    cols.forEach(col => {
      const match = !q || col.dataset.name.includes(q) ||
                    (col.dataset.category || '').includes(q) ||
                    (col.dataset.manager  || '').includes(q);
      col.style.display = match ? '' : 'none';
      if (match) visible++;
    });
    const empty = document.getElementById('picker-empty');
    if (empty) empty.classList.toggle('d-none', visible > 0);
  });
})();
</script>
