/* The self-verifying action plan: status and evidence on each item, the
   fix-ready deliverables inside the item, and the re-scan timeline.

   Shared by the client page and admin. A status here is what the last
   re-scan found on the live site; "manual" means only a person can tell.
   A person's tick is never undone by a re-scan — a disagreement shows as
   a conflict instead. */

const VERIFY_STATUS = {
  verified: { tone: 'good', label: 'verified on the site' },
  regressed: { tone: 'crit', label: 'regressed' },
  open: { tone: 'warn', label: 'not yet on the site' },
  manual: { tone: 'fg-subtle', label: 'checked by a person' },
};

function verifyStatusOf(a) {
  if (a.status && VERIFY_STATUS[a.status]) return a.status;
  return (a.verify && a.verify.type && a.verify.type !== 'manual') ? 'open' : 'manual';
}

function VerifyLine({ a }) {
  const s = verifyStatusOf(a);
  const ev = a.evidence || {};
  const meta = VERIFY_STATUS[s];
  const checked = ev.checked_at ? String(ev.checked_at).slice(0, 16).replace('T', ' ') : '';
  return (
    <div style={{ marginTop: 8, fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
      <TonePill tone={meta.tone}>{meta.label}</TonePill>
      {a.manual_conflict && <span style={{ marginLeft: 6 }}><TonePill tone="crit">ticked, but the check fails</TonePill></span>}
      {a.manual_done && !a.manual_conflict && s !== 'verified' && <span style={{ marginLeft: 6 }}><TonePill tone="good">ticked done</TonePill></span>}
      {ev.check && <div style={{ marginTop: 4 }}><span className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', letterSpacing: '0.06em' }}>CHECK · </span>{ev.check}</div>}
      {ev.detail && <div><span className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', letterSpacing: '0.06em' }}>FOUND · </span>{ev.detail}{checked ? ` (checked ${checked})` : ''}</div>}
      {!ev.check && a.verify && a.verify.type && a.verify.type !== 'manual' &&
      <div style={{ color: 'var(--fg-subtle)' }}>Will be checked on the next re-scan.</div>}
    </div>);
}

/* Deliverable text with the placeholders marked: what only the business can fill in. */
function PlaceholderText({ text }) {
  const parts = String(text || '').split(/(\{\{[A-Z0-9_]+(?::[^}]*)?\}\})/g);
  return (
    <pre className="mono" style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: 12, lineHeight: 1.6, color: 'var(--fg)' }}>
      {parts.map((p, i) => /^\{\{/.test(p)
        ? <mark key={i} style={{ background: 'color-mix(in oklab, var(--warn) 30%, transparent)', color: 'var(--fg)', borderRadius: 3, padding: '0 3px', fontWeight: 600 }}>{p}</mark>
        : <React.Fragment key={i}>{p}</React.Fragment>)}
    </pre>);
}

function DeliverableCard({ d }) {
  const [open, setOpen] = React.useState(false);
  const n = (d.placeholders || []).length;
  return (
    <div style={{ borderRadius: 'var(--r-md)', background: 'var(--navy)', border: '1px solid var(--line)', padding: '10px 12px' }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{ fontSize: 13.5, fontWeight: 600, flex: '1 1 200px' }}>{d.title}</span>
        {d.validated === true && <TonePill tone="good">validates</TonePill>}
        {d.validated === false && <TonePill tone="crit">does not validate</TonePill>}
        {n > 0 ? <TonePill tone="warn">{n} to fill in</TonePill> : <TonePill tone="good">ready as is</TonePill>}
        <CopyText text={d.content} label="Copy" />
        <button onClick={() => downloadText(d.filename, d.content, d.mime + ';charset=utf-8')} style={textButton()}>Download {d.filename}</button>
        <button onClick={() => setOpen(!open)} style={textButton()}>{open ? 'Hide' : 'Show'}</button>
      </div>
      {d.note && <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6, lineHeight: 1.55 }}>{d.note}</div>}
      {open && <div style={{ marginTop: 8, maxHeight: 420, overflow: 'auto', padding: '10px 12px', borderRadius: 'var(--r-sm, 6px)', background: 'var(--navy-2)', border: '1px solid var(--line)' }}>
        <PlaceholderText text={d.content} />
      </div>}
    </div>);
}

function deliverablesFor(full, actionId) {
  const d = (full && full.deliverables) || null;
  if (!d || !d.items) return [];
  return ((d.by_action || {})[actionId] || []).map((k) => d.items[k]).filter(Boolean);
}

function GeneralDeliverables({ full }) {
  const d = (full && full.deliverables) || null;
  if (!d || !d.items) return null;
  const items = (d.general || []).map((k) => d.items[k]).filter(Boolean);
  if (!items.length) return null;
  return (
    <div style={{ marginTop: 22 }}>
      <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginBottom: 8 }}>
        Ready-to-use files · built {String(d.generated_at || '').slice(0, 10)}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{items.map((x) => <DeliverableCard key={x.kind} d={x} />)}</div>
    </div>);
}

function VerifyTimeline({ verify }) {
  if (!verify || !verify.enabled) return null;
  const h = verify.history || [];
  if (!h.length) {
    return <div style={{ fontSize: 13, color: 'var(--fg-subtle)', marginBottom: 14 }}>Not re-scanned yet. Each re-scan checks every item against the live site and keeps the date.</div>;
  }
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 14, fontSize: 12.5, color: 'var(--fg-muted)' }}>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', letterSpacing: '0.08em' }}>RE-SCANS · </span>
      {h.slice(-6).map((r, i) =>
      <span key={i} className="mono" style={{ fontSize: 11.5, padding: '3px 8px', borderRadius: 'var(--r-pill)', border: '1px solid var(--line)' }}>
        {String(r.at).slice(0, 10)} · {r.verified}/{r.total - (r.manual || 0)} verified{r.regressed ? ` · ${r.regressed} regressed` : ''}{r.conflicts ? ` · ${r.conflicts} conflict` : ''}
      </span>)}
    </div>);
}
