const { Badge, CodeBlock, InlineHint, DecisionBar, EntityRow, Banner } =
  window.EquestrianismDesignSystem_6b57f9;

const PENDING = [
  {
    id: 'ap-311', title: 'Send email', session: 'Email the plumber', tool: 'email.send',
    expires: 'expires in 6h 12m',
    args: '{\n  "to": "plumber@example.co.uk",\n  "subject": "Boiler service — availability",\n  "body": "Good morning — could you let us know your availability for an annual boiler service in the week of 24 August? Mornings suit best."\n}',
    plan: 'Send one email. No follow-up without a fresh approval.',
    policy: 'Outbound email always gates. Expiry is a lapse, not a denial — the agent will re-ask.',
  },
  {
    id: 'ap-312', title: 'Submit cancellation form', session: 'Cancel subscription', tool: 'browser.submit_form',
    expires: 'expires in 2h 03m',
    args: '{\n  "url": "https://account.example.com/cancel",\n  "fields": { "reason": "No longer needed", "confirm": true }\n}',
    plan: 'Submit the form, capture the confirmation page as an artifact, stop.',
    policy: 'Form submissions on account pages always gate.',
  },
];

function Approvals({ go }) {
  const [items, setItems] = React.useState(PENDING);
  const [decided, setDecided] = React.useState([]);
  const [open, setOpen] = React.useState(PENDING[0].id);
  const decide = (id, verdict, reason) => {
    const it = items.find((x) => x.id === id);
    setItems(items.filter((x) => x.id !== id));
    setDecided([{ ...it, verdict, reason }, ...decided]);
    const rest = items.filter((x) => x.id !== id);
    setOpen(rest.length ? rest[0].id : null);
  };
  return (
    <div className="stack">
      <window.PageHead title="Approvals"
        sub="Everything an agent wants to do that counts. Nothing here happens without you." />
      {items.length === 0 && (
        <Banner state="running" action={<a href="#board" onClick={(e) => { e.preventDefault(); go('board'); }}>Board</a>}>
          Inbox clear — both sessions have resumed.
        </Banner>
      )}
      {items.map((it) => (
        <div className="panel" key={it.id} style={{ padding: 0 }}>
          <button type="button" className="sess-card" style={{ border: 0, background: 'transparent', padding: 'var(--app-pad)' }}
            onClick={() => setOpen(open === it.id ? null : it.id)} aria-expanded={open === it.id}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <b style={{ fontSize: 'var(--text-body)' }}>{it.title}</b>
              <Badge decision="pending">Pending</Badge>
              <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-caption)', color: 'var(--text-muted)' }}>{it.expires}</span>
            </span>
            <span className="m">{it.session} · <code style={{ fontFamily: 'var(--font-mono)' }}>{it.tool}</code></span>
          </button>
          {open === it.id && (
            <div style={{ padding: '0 var(--app-pad) var(--app-pad)', display: 'flex', flexDirection: 'column', gap: 12 }}>
              <CodeBlock label={`tool call · ${it.tool}`} prompt="" copyable={false} code={it.args} />
              <div>
                <p className="panel-lbl" style={{ marginBottom: 4 }}>Plan</p>
                <p style={{ margin: 0, fontFamily: 'var(--font-sans)', fontSize: 'var(--text-body-sm)', lineHeight: 'var(--lh-ui)', color: 'var(--text-primary)' }}>{it.plan}</p>
              </div>
              <InlineHint>Policy: {it.policy}</InlineHint>
              <DecisionBar onApprove={(r) => decide(it.id, 'approved', r)} onDeny={(r) => decide(it.id, 'denied', r)} />
            </div>
          )}
        </div>
      ))}
      {decided.length > 0 && (
        <div>
          <p className="panel-lbl">Decided</p>
          <div className="stack" style={{ gap: 8 }}>
            {decided.map((d) => (
              <EntityRow key={d.id} title={d.title}
                meta={`${d.session}${d.reason ? ` · "${d.reason}"` : ''}`}
                end={<Badge decision={d.verdict}>{d.verdict}</Badge>} />
            ))}
            <EntityRow title="Book dentist appointments" meta="School admin · nobody decided in time"
              end={<Badge decision="expired">Expired</Badge>} />
          </div>
        </div>
      )}
    </div>
  );
}
window.Approvals = Approvals;
