<?php
$reportProject = $project ?? null;
$reportProjId  = (int)($projectId ?? 0);
$reportRunId   = (int)($runId ?? 0);
?>

<style>
/* Print styles */
@media print {
  #sidebar, .savit-topbar, #report-toolbar { display: none !important; }
  #main-content { margin-left: 0 !important; }
  .card { break-inside: avoid; }
  .page-break { page-break-before: always; }
  body { font-size: 11pt; }
  .no-print { display: none !important; }
}
.report-score-ring { display: inline-block; }
</style>

<!-- Report toolbar -->
<div id="report-toolbar" class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-2 no-print">
  <div>
    <h4 class="fw-bold mb-0">Audit Report</h4>
    <p class="text-muted small mb-0">Printable client report — use the Print button or Ctrl+P.</p>
  </div>
  <div class="d-flex gap-2 align-items-center">
    <select id="report-run-select" class="form-select form-select-sm" style="max-width:240px;">
      <option value="">Loading runs…</option>
    </select>
    <button class="btn btn-sm btn-outline-secondary" id="load-report-btn" type="button">
      <i class="bi bi-arrow-clockwise me-1"></i>Load
    </button>
    <button class="btn btn-sm btn-primary" onclick="window.print()" type="button">
      <i class="bi bi-printer me-1"></i>Print / PDF
    </button>
    <?php if ($reportProject): ?>
    <a href="#" class="btn btn-sm btn-outline-primary no-print" id="back-audit-btn">
      <i class="bi bi-search me-1"></i>Back to Audit
    </a>
    <?php endif; ?>
  </div>
</div>

<!-- Report content -->
<div id="report-content">

  <!-- Header -->
  <div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
      <div class="d-flex align-items-start justify-content-between flex-wrap gap-3">
        <div>
          <h2 class="fw-bold mb-1" id="rpt-business-name">
            <?= htmlspecialchars($reportProject['business_name'] ?? 'Select a project') ?>
          </h2>
          <p class="text-muted mb-1" id="rpt-domain">
            <?= htmlspecialchars($reportProject['website_url'] ?? '') ?>
          </p>
          <p class="text-muted small mb-0">
            <i class="bi bi-calendar2 me-1"></i>Report generated: <span id="rpt-date"><?= date('d M Y') ?></span>
            &nbsp;&middot;&nbsp;
            <i class="bi bi-hash me-1"></i>Crawl Run: <span id="rpt-run-id"><?= $reportRunId ?: '—' ?></span>
          </p>
        </div>
        <!-- Health score ring -->
        <div class="text-center" id="rpt-score-container">
          <svg width="100" height="100" viewBox="0 0 100 100" id="rpt-score-svg">
            <circle cx="50" cy="50" r="40" fill="none" stroke="#e5e7eb" stroke-width="8"/>
            <circle cx="50" cy="50" r="40" fill="none" stroke="#e5e7eb" stroke-width="8"
                    id="rpt-score-arc" stroke-linecap="round" transform="rotate(-90 50 50)"/>
            <text x="50" y="55" text-anchor="middle" font-size="22" font-weight="700"
                  fill="#374151" font-family="Inter,sans-serif" id="rpt-score-text">—</text>
          </svg>
          <div class="small text-muted mt-1">Health Score</div>
        </div>
      </div>
    </div>
  </div>

  <!-- Loading + error states -->
  <div id="rpt-loading" class="text-center py-5 d-none">
    <div class="spinner-border text-primary"></div>
    <div class="small text-muted mt-2">Loading report data…</div>
  </div>
  <div id="rpt-error" class="alert alert-danger d-none"></div>

  <!-- What Changed (auto-diff) -->
  <div id="rpt-diff-section" class="d-none">
    <div class="card border-0 shadow-sm mb-4">
      <div class="card-header fw-semibold d-flex align-items-center gap-2">
        <i class="bi bi-arrow-left-right text-primary"></i> What Changed Since Last Crawl
      </div>
      <div class="card-body">
        <div class="row g-3 mb-3" id="rpt-diff-kpis"></div>
        <div class="row g-3">
          <div class="col-md-6" id="rpt-new-issues-col"></div>
          <div class="col-md-6" id="rpt-fixed-issues-col"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Key Metrics -->
  <div class="row g-3 mb-4" id="rpt-metrics-row"></div>

  <!-- Action Queue (tiers) -->
  <div class="card border-0 shadow-sm mb-4" id="rpt-queue-card" style="display:none!important;">
    <div class="card-header fw-semibold d-flex align-items-center gap-2">
      <i class="bi bi-list-task text-primary"></i> Action Queue
    </div>
    <div class="card-body" id="rpt-action-queue"></div>
  </div>

  <!-- Site statistics -->
  <div class="row g-3 mb-4" id="rpt-stats-row"></div>

  <!-- Footer -->
  <div class="text-muted small text-center py-3 border-top">
    Generated by <strong>Savit Audit Engine</strong> &middot;
    <span id="rpt-footer-domain"></span> &middot;
    <?= date('d M Y, H:i') ?>
  </div>

</div>

<script>
(function () {
  const base      = (document.querySelector('meta[name="base-url"]') || {}).content || '';
  const initProjId= <?= (int)($reportProjId ?? 0) ?>;
  const initRunId = <?= (int)($reportRunId  ?? 0) ?>;

  let currentProjId = initProjId;
  let currentRunId  = initRunId;

  // ── Helpers ─────────────────────────────────────────────────────────────
  function qs(id) { return document.getElementById(id); }
  function escHtml(s) {
    const d = document.createElement('div');
    d.appendChild(document.createTextNode(String(s ?? '')));
    return d.innerHTML;
  }

  async function apiFetch(path) {
    const res = await fetch(base + path);
    const j   = await res.json();
    if (!j.success) throw new Error(j.message || 'API error');
    return j.data;
  }

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

  function kpiCard(label, value, color) {
    return `<div class="col-6 col-md-3">
      <div class="text-center p-3 rounded border">
        <div class="fs-3 fw-bold ${color ? 'text-' + color : ''}">${escHtml(value)}</div>
        <div class="text-muted small">${escHtml(label)}</div>
      </div>
    </div>`;
  }

  // ── Score ring ───────────────────────────────────────────────────────────
  function updateScoreRing(score) {
    const r    = 40;
    const circ = +(2 * Math.PI * r).toFixed(1);
    const dash = +((score / 100) * circ).toFixed(1);
    const col  = scoreColor(score);
    const arc  = qs('rpt-score-arc');
    const txt  = qs('rpt-score-text');
    if (arc) { arc.setAttribute('stroke', col); arc.setAttribute('stroke-dasharray', `${dash} ${circ}`); }
    if (txt) { txt.setAttribute('fill', col); txt.textContent = score; }
  }

  // ── Tiered action queue ──────────────────────────────────────────────────
  const ISSUE_FIX = {
    'Missing title':              'Add a unique <title> tag (50–60 chars) to every HTML page.',
    'Missing meta description':   'Write a unique meta description (120–158 chars) per page.',
    'Missing H1':                 'Add exactly one H1 heading per page.',
    'Client/Server errors':       'Fix or remove links to 4xx/5xx pages.',
    'Noindex pages':              'Audit noindex directives — check important pages are not blocked.',
    'Thin content (<300 words)':  'Expand thin pages — add value, FAQs, step-by-step guidance.',
    'Duplicate content':          'Consolidate duplicates with 301 redirects or canonical tags.',
    'Low readability (Flesch <50)': 'Rewrite at 7th–10th grade level. Shorter sentences, active voice.',
    'Images missing alt text':    'Add descriptive alt text (≤125 chars) to every image.',
  };

  function renderActionQueue(issues, containerId) {
    const tiers = {
      critical: { label: 'Fix This Week',   color: 'danger',    icon: 'bi-exclamation-triangle-fill', items: [] },
      high:     { label: 'Fix This Sprint', color: 'warning',   icon: 'bi-exclamation-circle-fill',   items: [] },
      medium:   { label: 'Next Sprint',     color: 'info',      icon: 'bi-info-circle-fill',           items: [] },
      low:      { label: 'Backlog',         color: 'secondary', icon: 'bi-circle-fill',               items: [] },
    };
    issues.forEach(iss => {
      const sev = (iss.severity || 'low').toLowerCase();
      if (tiers[sev]) tiers[sev].items.push(iss);
    });

    const container = qs(containerId);
    if (!container) return;

    const activeTiers = Object.values(tiers).filter(t => t.items.length > 0);
    if (!activeTiers.length) {
      container.innerHTML = '<p class="text-success mb-0"><i class="bi bi-check-circle me-1"></i>No issues found for this crawl.</p>';
      return;
    }

    container.innerHTML = activeTiers.map(tier => `
      <div class="mb-4">
        <div class="d-flex align-items-center gap-2 mb-2">
          <i class="bi ${tier.icon} text-${tier.color}"></i>
          <span class="fw-semibold text-${tier.color}">${tier.label}</span>
          <span class="badge bg-${tier.color}-subtle text-${tier.color} ms-auto">${tier.items.length}</span>
        </div>
        <div class="list-group list-group-flush border rounded">
          ${tier.items.map(iss => {
            const fix = ISSUE_FIX[iss.label] || '';
            return `<div class="list-group-item d-flex justify-content-between align-items-start py-2">
              <div>
                <div class="fw-medium small">${escHtml(iss.label)}</div>
                ${fix ? `<div class="text-muted" style="font-size:.75rem;">${escHtml(fix)}</div>` : ''}
              </div>
              <span class="badge bg-${tier.color}-subtle text-${tier.color} ms-2 flex-shrink-0">${iss.count}</span>
            </div>`;
          }).join('')}
        </div>
      </div>
    `).join('');
  }

  // ── Load runs list ───────────────────────────────────────────────────────
  async function loadRuns(projId) {
    const sel = qs('report-run-select');
    if (!sel || !projId) return;
    const runs = await apiFetch(`/api/projects/${projId}/crawl-runs`);
    sel.innerHTML = '<option value="">— Select Run —</option>' +
      runs.map(r => `<option value="${r.id}" ${(+r.id === currentRunId || (!currentRunId && r.status === 'completed')) ? 'selected' : ''}>${escHtml('#' + r.id + ' · ' + r.status + ' · ' + r.domain + ' · ' + (r.total_pages||0) + ' pages')}</option>`).join('');
    if (!currentRunId && runs.length) {
      const first = runs.find(r => r.status === 'completed') || runs[0];
      if (first) currentRunId = +first.id;
    }
  }

  // ── Load and render report ───────────────────────────────────────────────
  async function loadReport(projId, runId) {
    if (!projId || !runId) return;
    qs('rpt-loading').classList.remove('d-none');
    qs('rpt-error').classList.add('d-none');
    qs('rpt-queue-card').style.removeProperty('display');

    try {
      // Parallel fetches
      const [auditData, diffData, healthData] = await Promise.all([
        apiFetch(`/api/projects/${projId}/website-audit?crawl_run_id=${runId}&limit=1`),
        apiFetch(`/api/projects/${projId}/auto-diff`).catch(() => ({ available: false })),
        apiFetch(`/api/projects/${projId}/health-score?crawl_run_id=${runId}`).catch(() => null),
      ]);

      qs('rpt-loading').classList.add('d-none');
      qs('rpt-run-id').textContent = '#' + runId;

      // Health score
      const score = healthData?.score ?? 0;
      updateScoreRing(score);

      // Key metrics
      const issues    = auditData.issue_summary || [];
      const totalPgs  = auditData.crawl_total || 0;
      const errPgs    = issues.find(i => i.label === 'Client/Server errors')?.count || 0;
      const noindexPgs= issues.find(i => i.label === 'Noindex pages')?.count || 0;
      const slowPgs   = issues.find(i => i.label === 'Slow page (>3s response)')?.count || 0;

      qs('rpt-metrics-row').innerHTML = [
        kpiCard('Total Pages',   totalPgs,  ''),
        kpiCard('Health Score',  score,     score>=80?'success':score>=60?'warning':'danger'),
        kpiCard('Error Pages',   errPgs,    errPgs > 0 ? 'danger' : 'success'),
        kpiCard('Slow Pages',    slowPgs,   slowPgs > 0 ? 'warning' : ''),
        kpiCard('Noindex',       noindexPgs,''),
        kpiCard('Issues Found',  issues.length, issues.length > 0 ? 'warning' : 'success'),
        kpiCard('Report Date',   new Date().toLocaleDateString('en-IN',{day:'2-digit',month:'short',year:'numeric'}), ''),
        kpiCard('Score Label',   scoreLabel(score), score>=80?'success':score>=60?'warning':'danger'),
      ].join('');

      // Action queue
      renderActionQueue(issues, 'rpt-action-queue');

      // Diff section
      if (diffData?.available) {
        qs('rpt-diff-section').classList.remove('d-none');
        const delta = diffData.health_b - diffData.health_a;
        const arrow = delta >= 0 ? '↑' : '↓';
        const dcls  = delta >= 0 ? 'success' : 'danger';

        qs('rpt-diff-kpis').innerHTML = [
          kpiCard('Health Change',  `${arrow} ${Math.abs(delta)} pts`, dcls),
          kpiCard('Run Compared',   `#${diffData.run_old} → #${diffData.run_new}`, ''),
          kpiCard('Issues Worsened', diffData.new_issues?.length || 0, diffData.new_issues?.length > 0 ? 'danger' : 'success'),
          kpiCard('Issues Improved', diffData.fixed_issues?.length || 0, diffData.fixed_issues?.length > 0 ? 'success' : ''),
        ].join('');

        if (diffData.new_issues?.length) {
          qs('rpt-new-issues-col').innerHTML = `<div class="fw-semibold text-danger small mb-2">
            <i class="bi bi-arrow-up-circle me-1"></i>Issues Worsened
          </div>` + diffData.new_issues.map(i =>
            `<div class="d-flex justify-content-between small border-bottom py-1">
              <span>${escHtml(i.label)}</span>
              <span class="text-danger fw-semibold">${escHtml(i.change)}</span>
            </div>`
          ).join('');
        }
        if (diffData.fixed_issues?.length) {
          qs('rpt-fixed-issues-col').innerHTML = `<div class="fw-semibold text-success small mb-2">
            <i class="bi bi-arrow-down-circle me-1"></i>Issues Improved
          </div>` + diffData.fixed_issues.map(i =>
            `<div class="d-flex justify-content-between small border-bottom py-1">
              <span>${escHtml(i.label)}</span>
              <span class="text-success fw-semibold">${escHtml(i.change)}</span>
            </div>`
          ).join('');
        }
      } else {
        qs('rpt-diff-section').classList.add('d-none');
      }

      // Footer domain
      const domainEl = qs('rpt-footer-domain');
      if (domainEl) domainEl.textContent = auditData.crawl_domain || '';

    } catch (e) {
      qs('rpt-loading').classList.add('d-none');
      qs('rpt-error').textContent = 'Failed to load report: ' + e.message;
      qs('rpt-error').classList.remove('d-none');
    }
  }

  // ── Init ─────────────────────────────────────────────────────────────────
  async function init() {
    if (!initProjId) return;

    await loadRuns(initProjId);

    const sel = qs('report-run-select');
    if (sel && sel.value) currentRunId = +sel.value;

    if (currentRunId) await loadReport(initProjId, currentRunId);

    // Load button
    qs('load-report-btn')?.addEventListener('click', async () => {
      const sel = qs('report-run-select');
      if (sel && sel.value) {
        currentRunId = +sel.value;
        await loadReport(initProjId, currentRunId);
      }
    });

    // Back to audit link
    const backBtn = qs('back-audit-btn');
    if (backBtn) backBtn.href = base + '/?p=' + initProjId;
  }

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