/* Admin: verification panel for one lead — re-scan the action plan against
   the live site, generate the fix-ready files, read the history. */

function VerifyPanel({ slug, token, report, onExpired, onReportChanged }) {
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState('');
  const [last, setLast] = React.useState(null);
  const actions = ((report.full || {}).actions) || [];
  const counts = { verified: 0, regressed: 0, open: 0, manual: 0, conflicts: 0 };
  actions.forEach((a) => { const s = verifyStatusOf(a); counts[s] = (counts[s] || 0) + 1; if (a.manual_conflict) counts.conflicts += 1; });
  const call = async (action, extra) => {
    setBusy(action); setFlash('');
    try {
      const d = await apiCall('/api/verify', { method: 'POST', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, slug, ...(extra || {}) }) });
      if (d.status === 401) { onExpired(); return null; }
      if (!d.ok) { setFlash(d.message || d.detail || `${action} failed (HTTP ${d.status}).`); setBusy(''); return null; }
      setBusy('');
      return d;
    } catch (e) { setFlash('Could not reach the server.'); setBusy(''); return null; }
  };
  const rescan = async () => {
    const d = await call('rescan');
    if (d) { setLast(d); onReportChanged(); }
  };
  const deliverables = async () => {
    const d = await call('deliverables');
    if (d) { setFlash(`Built ${Object.keys(d.summary).length} files: ` + Object.values(d.summary).map((x) => x.title + (x.placeholders ? ` (${x.placeholders} to fill)` : '')).join('; ')); onReportChanged(); }
  };
  if (!actions.length) {
    return <Panel title="Verification"><div style={{ fontSize: 13.5, color: 'var(--fg-muted)' }}>No action plan yet. Write the full report first; its items carry machine checks.</div></Panel>;
  }
  const deliv = (report.full || {}).deliverables;
  return (
    <Panel title={`Verification · ${counts.verified} verified · ${counts.open} open · ${counts.regressed} regressed · ${counts.manual} manual${counts.conflicts ? ` · ${counts.conflicts} conflict` : ''}`}
      tone={counts.regressed || counts.conflicts ? 'crit' : counts.verified ? 'good' : undefined}>
      <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 10 }}>
        {report.last_rescan_at ? `Last re-scan ${String(report.last_rescan_at).slice(0, 16).replace('T', ' ')}.` : 'Not re-scanned yet.'}
        {' '}A re-scan fetches the live site the way a crawler does and checks every item that has a machine check; ticks by hand are never undone, a disagreement is flagged.
        {deliv ? ` Files built ${String(deliv.generated_at || '').slice(0, 16).replace('T', ' ')}.` : ' No fix-ready files built yet.'}
      </div>
      {flash && <div style={{ marginBottom: 10, fontSize: 13.5, color: 'var(--warn)' }}>{flash}</div>}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <button style={smallBtn('accent')} disabled={!!busy} onClick={rescan}>{busy === 'rescan' ? 'Checking the site…' : 'Re-scan the action plan'}</button>
        <button style={smallBtn()} disabled={!!busy} onClick={deliverables}>{busy === 'deliverables' ? 'Building…' : (deliv ? 'Rebuild the fix-ready files' : 'Build the fix-ready files')}</button>
      </div>
      {last &&
      <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 4 }}>
        {last.results.filter((r) => r.status !== 'manual').map((r) =>
        <div key={r.id} style={{ fontSize: 13, color: 'var(--fg-muted)', display: 'flex', gap: 8, alignItems: 'baseline', flexWrap: 'wrap' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{r.id}</span>
          <TonePill tone={VERIFY_STATUS[r.status].tone}>{r.status}</TonePill>
          {r.manual_conflict && <TonePill tone="crit">conflict</TonePill>}
          <span>{r.detail}</span>
        </div>)}
      </div>}
      {(report.rescans || []).length > 0 &&
      <div style={{ marginTop: 12 }}><VerifyTimeline verify={{ enabled: true, history: report.rescans }} /></div>}
    </Panel>);
}
