<?php
// basePath is set by header.php — available in scope
?>

<!-- Health Board toolbar -->
<div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-2">
  <div>
    <h4 class="fw-bold mb-0">Client Health Board</h4>
    <p class="text-muted small mb-0">Live health snapshot across all projects. Click a card to open the full audit.</p>
  </div>
  <div class="d-flex gap-2">
    <button class="btn btn-sm btn-outline-secondary" id="refresh-board-btn" type="button">
      <i class="bi bi-arrow-clockwise me-1"></i>Refresh
    </button>
    <a href="<?= htmlspecialchars($savitBase ?? '') ?>/Content/projects/create"
       class="btn btn-sm btn-primary">
      <i class="bi bi-plus-lg me-1"></i>New Project
    </a>
  </div>
</div>

<!-- Stats bar -->
<div class="row g-3 mb-4" id="board-stats" style="display:none!important;">
  <div class="col-6 col-md-3">
    <div class="card border-0 bg-light p-3 text-center">
      <div class="text-muted small">Total Projects</div>
      <div id="stat-total" class="fs-4 fw-bold">—</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 bg-success-subtle p-3 text-center">
      <div class="text-muted small">Healthy (≥80)</div>
      <div id="stat-healthy" class="fs-4 fw-bold text-success">—</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 bg-warning-subtle p-3 text-center">
      <div class="text-muted small">Needs Attention (60–79)</div>
      <div id="stat-warning" class="fs-4 fw-bold text-warning">—</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 bg-danger-subtle p-3 text-center">
      <div class="text-muted small">Critical (&lt;60)</div>
      <div id="stat-critical" class="fs-4 fw-bold text-danger">—</div>
    </div>
  </div>
</div>

<!-- Loading state -->
<div id="board-loading" class="text-center py-5">
  <div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading…</span></div>
  <div class="text-muted small mt-2">Fetching health data for all projects…</div>
</div>

<!-- Error state -->
<div id="board-error" class="d-none alert alert-danger"></div>

<!-- Project cards grid -->
<div class="row g-3" id="health-board-grid"></div>

<script>
(function () {
  const base = (document.querySelector('meta[name="base-url"]') || {}).content || '';

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

  function scoreColor(score) {
    if (score >= 80) return '#22c55e';
    if (score >= 60) return '#f59e0b';
    return '#ef4444';
  }

  function scoreBgClass(score) {
    if (score >= 80) return 'success';
    if (score >= 60) return 'warning';
    return 'danger';
  }

  function healthRing(score) {
    const r     = 32;
    const circ  = +(2 * Math.PI * r).toFixed(1);
    const dash  = +((score / 100) * circ).toFixed(1);
    const color = scoreColor(score);
    return `<svg width="80" height="80" viewBox="0 0 80 80" style="flex-shrink:0;">
      <circle cx="40" cy="40" r="${r}" fill="none" stroke="#e5e7eb" stroke-width="6"/>
      <circle cx="40" cy="40" r="${r}" fill="none" stroke="${color}" stroke-width="6"
              stroke-dasharray="${dash} ${circ}" stroke-linecap="round"
              transform="rotate(-90 40 40)" style="transition:stroke-dasharray .6s"/>
      <text x="40" y="45" text-anchor="middle" font-size="15" font-weight="700"
            fill="${color}" font-family="Inter,sans-serif">${score}</text>
    </svg>`;
  }

  function renderCards(projects) {
    const grid = document.getElementById('health-board-grid');
    if (!projects.length) {
      grid.innerHTML = `<div class="col-12 text-center py-5 text-muted">
        <i class="bi bi-collection" style="font-size:3rem;opacity:.3;"></i>
        <div class="mt-2">No projects found. <a href="${escHtml(base)}/../Content/projects/create">Create one in the Content Engine →</a></div>
      </div>`;
      return;
    }

    // Update stats bar
    const healthy  = projects.filter(p => p.health_score >= 80).length;
    const warnings = projects.filter(p => p.health_score >= 60 && p.health_score < 80).length;
    const critical = projects.filter(p => p.health_score > 0 && p.health_score < 60).length;
    document.getElementById('stat-total').textContent   = projects.length;
    document.getElementById('stat-healthy').textContent = healthy;
    document.getElementById('stat-warning').textContent = warnings;
    document.getElementById('stat-critical').textContent= critical;
    document.getElementById('board-stats').style.removeProperty('display');

    grid.innerHTML = projects.map(p => {
      const score     = p.health_score || 0;
      const hasCrawl  = !!p.latest_run_id;
      const running   = p.crawl_status === 'running';
      const cls       = scoreBgClass(score);

      const dateFmt = p.finished_at
        ? new Date(p.finished_at).toLocaleDateString('en-IN', {day:'2-digit', month:'short', year:'numeric'})
        : '—';

      const statusBadge = running
        ? `<span class="badge bg-warning-subtle text-warning"><i class="bi bi-circle-fill me-1" style="font-size:.5rem;"></i>Crawling</span>`
        : p.crawl_status === 'completed'
          ? `<span class="badge bg-success-subtle text-success">Last: ${dateFmt}</span>`
          : `<span class="badge bg-secondary-subtle text-secondary">No crawl yet</span>`;

      const issueChips = [];
      if (p.error_pages   > 0) issueChips.push(`<span class="badge bg-danger-subtle text-danger">${p.error_pages} error${p.error_pages>1?'s':''}</span>`);
      if (p.missing_title > 0) issueChips.push(`<span class="badge bg-warning-subtle text-warning">${p.missing_title} missing title${p.missing_title>1?'s':''}</span>`);
      if (p.thin_content  > 0) issueChips.push(`<span class="badge bg-secondary-subtle text-secondary">${p.thin_content} thin page${p.thin_content>1?'s':''}</span>`);

      const ring    = hasCrawl ? healthRing(score) : `<div style="width:80px;height:80px;border-radius:50%;background:#f3f4f6;display:flex;align-items:center;justify-content:center;"><i class="bi bi-dash text-muted fs-4"></i></div>`;
      const auditUrl  = `${base}/?p=${p.id}`;
      const reportUrl = hasCrawl ? `${base}/report?p=${p.id}&run=${p.latest_run_id}` : null;
      const domain    = p.crawl_domain || p.website_url || '—';

      return `<div class="col-md-6 col-xl-4">
        <div class="card border-0 shadow-sm h-100 project-health-card" style="transition:box-shadow .2s;">
          <div class="card-body d-flex flex-column gap-3">

            <!-- Top row: ring + meta -->
            <div class="d-flex align-items-center gap-3">
              ${ring}
              <div class="min-w-0 flex-grow-1">
                <h6 class="fw-semibold mb-1 text-truncate" title="${escHtml(p.business_name)}">${escHtml(p.business_name)}</h6>
                <p class="text-muted small mb-1 text-truncate" title="${escHtml(domain)}">${escHtml(domain)}</p>
                ${statusBadge}
              </div>
              ${hasCrawl ? `<span class="badge bg-${cls}-subtle text-${cls} fs-6 flex-shrink-0">${score}/100</span>` : ''}
            </div>

            <!-- Stats row -->
            <div class="d-flex gap-3 text-center small" ${!hasCrawl ? 'style="opacity:.4;"' : ''}>
              <div>
                <div class="fw-semibold">${(p.crawl_total||0).toLocaleString()}</div>
                <div class="text-muted" style="font-size:.7rem;">Pages</div>
              </div>
              <div>
                <div class="fw-semibold ${p.error_pages > 0 ? 'text-danger' : ''}">${p.error_pages||0}</div>
                <div class="text-muted" style="font-size:.7rem;">Errors</div>
              </div>
              <div>
                <div class="fw-semibold ${p.missing_title > 0 ? 'text-warning' : ''}">${p.missing_title||0}</div>
                <div class="text-muted" style="font-size:.7rem;">No Title</div>
              </div>
              <div>
                <div class="fw-semibold ${p.thin_content > 0 ? 'text-secondary' : ''}">${p.thin_content||0}</div>
                <div class="text-muted" style="font-size:.7rem;">Thin</div>
              </div>
            </div>

            <!-- Issue chips -->
            <div class="d-flex flex-wrap gap-1 min-h-0" style="min-height:1.5rem;">
              ${issueChips.length ? issueChips.join('') : (hasCrawl ? '<span class="text-success small"><i class="bi bi-check-circle me-1"></i>No critical issues</span>' : '<span class="text-muted small">Run a crawl to get health data</span>')}
            </div>

            <!-- Action buttons -->
            <div class="mt-auto d-flex gap-2">
              <a href="${escHtml(auditUrl)}" class="btn btn-sm btn-primary flex-fill">
                <i class="bi bi-search me-1"></i>View Audit
              </a>
              ${reportUrl ? `<a href="${escHtml(reportUrl)}" class="btn btn-sm btn-outline-secondary" target="_blank" title="Open Client Report">
                <i class="bi bi-file-earmark-bar-graph"></i>
              </a>` : ''}
              <a href="${escHtml(auditUrl)}&action=crawl" class="btn btn-sm btn-outline-secondary" title="Start New Crawl">
                <i class="bi bi-play-fill"></i>
              </a>
            </div>

          </div>
        </div>
      </div>`;
    }).join('');
  }

  async function loadBoard() {
    const loading = document.getElementById('board-loading');
    const errEl   = document.getElementById('board-error');
    const grid    = document.getElementById('health-board-grid');
    loading.classList.remove('d-none');
    errEl.classList.add('d-none');
    grid.innerHTML = '';

    try {
      const res  = await fetch(base + '/api/projects/health-summary');
      const json = await res.json();
      if (!json.success) throw new Error(json.message || 'API error');
      loading.classList.add('d-none');
      renderCards(json.data || []);
    } catch (e) {
      loading.classList.add('d-none');
      errEl.textContent = 'Failed to load health data: ' + e.message;
      errEl.classList.remove('d-none');
    }
  }

  document.getElementById('refresh-board-btn').addEventListener('click', loadBoard);

  // Hover lift effect
  document.addEventListener('mouseover', (e) => {
    const card = e.target.closest('.project-health-card');
    if (card) card.style.boxShadow = '0 8px 24px rgba(0,0,0,.12)';
  });
  document.addEventListener('mouseout', (e) => {
    const card = e.target.closest('.project-health-card');
    if (card) card.style.boxShadow = '';
  });

  loadBoard();
})();
</script>
