// aria-why.jsx — ARIA transparency showcase
// Section + the tabbed modal (Audit · Frameworks · EU AI Act Art. 13).

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────────────────────
// Modal: AriaWhyModal
// ─────────────────────────────────────────────────────────────────────────────

function AriaWhyModal({ open, onClose, trajectory }) {
  const [tab, setTab] = useState("audit");

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;
  const t = trajectory;

  return (
    <div className="modal-overlay" onClick={onClose} role="dialog" aria-modal="true">
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={{ padding: "24px 32px 0", display: "flex", flexDirection: "column", gap: 22 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="eyebrow">ARIA · Why?</span>
                <span className="chip" style={{ fontSize: 10 }}>{t.id}</span>
              </div>
              <div className="display" style={{ fontSize: 32 }}>
                Why we routed <em>Sarah M.</em> to a same-day urgent slot.
              </div>
            </div>
            <button onClick={onClose} aria-label="Close" style={{
              background: "transparent", border: "1px solid var(--rule)",
              borderRadius: 999, width: 36, height: 36, cursor: "pointer",
              color: "var(--ink-soft)", fontSize: 16, flexShrink: 0,
            }}>✕</button>
          </div>

          {/* Decision summary strip */}
          <div className="modal-summary" style={{
            display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1,
            background: "var(--rule)", border: "1px solid var(--rule)",
            borderRadius: 14, overflow: "hidden",
          }}>
            <SummaryCell label="Decision" value={t.decision} />
            <SummaryCell label="Confidence" value={
              <div style={{ display: "flex", flexDirection: "column", gap: 6, paddingTop: 2 }}>
                <div style={{ fontVariantNumeric: "tabular-nums", fontSize: 14, color: "var(--ink)" }}>
                  {(t.confidence * 100).toFixed(1)}%
                </div>
                <div className="conf-bar"><div style={{ width: `${t.confidence * 100}%` }} /></div>
              </div>
            } />
            <SummaryCell label="Human review" value={
              <span style={{ color: t.humanReview ? "var(--warn)" : "var(--ok)" }}>
                {t.humanReview ? "Required" : "Not required"}
              </span>
            } />
            <SummaryCell label="Duration" value={t.duration} />
          </div>

          {/* Tabs */}
          <div style={{ display: "flex", gap: 6, borderBottom: "1px solid var(--rule)", paddingBottom: 0 }}>
            <button className="tab-pill" data-active={tab === "audit"}      onClick={() => setTab("audit")}>Audit trail</button>
            <button className="tab-pill" data-active={tab === "frameworks"} onClick={() => setTab("frameworks")}>Framework chain</button>
            <button className="tab-pill" data-active={tab === "art13"}      onClick={() => setTab("art13")}>EU AI Act · Art. 13</button>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 32px 28px", overflowY: "auto", flex: 1 }}>
          {tab === "audit"      && <AuditTab trajectory={t} />}
          {tab === "frameworks" && <FrameworksTab trajectory={t} />}
          {tab === "art13"      && <Art13Tab trajectory={t} />}
        </div>

        {/* Footer */}
        <div style={{
          padding: "14px 32px", borderTop: "1px solid var(--rule)",
          background: "var(--bg)", display: "flex",
          justifyContent: "space-between", alignItems: "center", gap: 16,
          fontSize: 12, color: "var(--ink-mute)",
        }}>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <span className="chip" style={{ background: "transparent", border: "1px solid var(--rule)" }}>
              {t.modelHash}
            </span>
            <span>Patient identifiers redacted in this view.</span>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <span>Press <span className="kbd">Esc</span> to close</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function SummaryCell({ label, value }) {
  return (
    <div style={{ background: "var(--bg-elev)", padding: "14px 16px", display: "flex", flexDirection: "column", gap: 4 }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>{value}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Tab: Audit trail
// ─────────────────────────────────────────────────────────────────────────────

function AuditTab({ trajectory }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16 }}>
        <p style={{ margin: 0, color: "var(--ink-soft)", maxWidth: 560 }}>
          Every step of the triage decision, captured immutably and exposed in plain language.
          Auto steps are deterministic; <em className="serif-it">model</em> steps invoked the
          routing model; human steps logged a clinician's action or override.
        </p>
        <div style={{ display: "flex", gap: 10, fontSize: 11, color: "var(--ink-mute)" }}>
          <LegendDot color="var(--sage)" label="auto" />
          <LegendDot color="var(--brand)" label="model" />
          <LegendDot color="var(--accent)" label="human" />
        </div>
      </div>

      <div className="trail">
        {trajectory.audit.map((step, i) => (
          <div key={i} className="trail-step" data-state={step.state}>
            <div style={{ display: "flex", gap: 14, alignItems: "baseline" }}>
              <span className="chip" style={{ fontFamily: "var(--font-mono)", minWidth: 110, justifyContent: "center" }}>
                {step.t}
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, color: "var(--ink)", fontWeight: 500 }}>
                  {step.label}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 2 }}>
                  {step.detail}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function LegendDot({ color, label }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: color }} />
      {label}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Tab: Framework chain
// ─────────────────────────────────────────────────────────────────────────────

function FrameworksTab({ trajectory }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <p style={{ margin: 0, color: "var(--ink-soft)", maxWidth: 620 }}>
        Five frameworks invoked in sequence. Each is independently versioned, clinically reviewed,
        and exposes its own input → output contract. Click any to see the model card.
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {trajectory.frameworks.map((f, i) => (
          <React.Fragment key={f.name}>
            <div className="fw-item">
              <div style={{
                width: 32, height: 32, borderRadius: 999, background: "var(--brand-soft)",
                color: "var(--brand-deep)", display: "flex", alignItems: "center",
                justifyContent: "center", fontSize: 12, fontFamily: "var(--font-mono)",
                fontWeight: 500, flexShrink: 0,
              }}>{i + 1}</div>
              <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
                <div style={{ display: "flex", gap: 10, alignItems: "baseline", flexWrap: "wrap" }}>
                  <span style={{ fontSize: 14, fontWeight: 500, color: "var(--ink)" }}>{f.name}</span>
                  <span className="chip">v{f.v}</span>
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{f.note}</div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4, flexShrink: 0 }}>
                <span className="eyebrow" style={{ fontSize: 9 }}>output</span>
                <span className="chip chip-brand" style={{ fontSize: 11 }}>{f.out}</span>
              </div>
            </div>
            {i < trajectory.frameworks.length - 1 && (
              <div className="fw-arrow">↓</div>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Tab: EU AI Act Article 13
// ─────────────────────────────────────────────────────────────────────────────

function Art13Tab({ trajectory }) {
  const statusColor = {
    documented: "var(--sage)",
    live: "var(--brand)",
    mitigated: "var(--accent)",
    available: "var(--sage)",
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{
        background: "var(--bg)", border: "1px solid var(--rule)",
        borderRadius: 14, padding: "18px 20px",
        display: "flex", gap: 18, alignItems: "flex-start",
      }}>
        <div style={{
          width: 42, height: 42, borderRadius: 12, background: "var(--brand-soft)",
          color: "var(--brand-deep)", display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "var(--font-display)", fontSize: 22, flexShrink: 0,
        }}>§</div>
        <div>
          <div className="eyebrow" style={{ fontSize: 10 }}>EU AI Act · Article 13</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1.15, marginTop: 4 }}>
            Transparency &amp; provision of information to deployers
          </div>
          <p style={{ margin: "8px 0 0", fontSize: 13, color: "var(--ink-soft)", maxWidth: 580 }}>
            High-risk AI systems must be designed so deployers can interpret outputs.
            Below is what ARIA documents for this routing class — refreshed on every model release.
          </p>
        </div>
      </div>

      <div className="art13-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        {trajectory.art13.map((row) => (
          <div key={row.req} style={{
            background: "var(--bg-elev)", border: "1px solid var(--rule)",
            borderRadius: 12, padding: "14px 16px", display: "flex", flexDirection: "column", gap: 8,
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{row.req}</span>
              <span style={{
                fontSize: 10, padding: "3px 8px", borderRadius: 999,
                background: "var(--bg-deep)", color: statusColor[row.status],
                fontFamily: "var(--font-mono)", letterSpacing: ".04em",
              }}>{row.status}</span>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--ink-soft)", lineHeight: 1.5 }}>{row.detail}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Section: AriaWhySection (lives on the page)
// ─────────────────────────────────────────────────────────────────────────────

function AriaWhySection({ trajectory, variant = "split", onOpen }) {
  return (
    <section id="aria-why" data-screen-label="ARIA Why" style={{ padding: "120px 0 100px", position: "relative" }}>
      <div className="container">
        <div className="section-mark"><span className="eyebrow">ARIA Why · Showcase</span></div>

        <div className="aria-grid" style={{ display: "grid", gridTemplateColumns: variant === "split" ? "1.05fr 1fr" : "1fr", gap: 64, alignItems: "start" }}>
          {/* Left: pitch */}
          <div>
            <h2 className="display" style={{ fontSize: "clamp(44px, 5vw, 72px)", margin: 0 }}>
              Every booking decision,<br />
              <em>explained.</em>
            </h2>
            <p style={{ fontSize: 18, color: "var(--ink-soft)", maxWidth: 520, marginTop: 22, lineHeight: 1.6 }}>
              Every patient interaction routed through ARIA — our triage assistant — exposes
              a full audit trail, the five-framework chain it ran, and a live mapping to EU AI
              Act Article 13. Click <span className="serif-it" style={{ color: "var(--brand)" }}>Why?</span> on
              any decision, anywhere on this site, and the receipts open.
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 28, maxWidth: 540 }}>
              <FeatureRow
                num="01"
                title="Audit trail · every step, timestamped"
                detail="Auto · model · human steps separated, immutable, exportable as PDF for clinical leads."
              />
              <FeatureRow
                num="02"
                title="Framework chain · five frameworks per decision"
                detail="Versioned, clinician-reviewed, each with its own input → output contract and model card."
              />
              <FeatureRow
                num="03"
                title="EU AI Act Article 13 · live mapping"
                detail="Intended purpose, limitations, foreseeable risks, oversight — refreshed on every release."
              />
            </div>

            <div style={{ display: "flex", gap: 10, marginTop: 32 }}>
              <button className="btn btn-primary" onClick={onOpen}>
                See a sample Why? <span style={{ opacity: .7 }}>→</span>
              </button>
              <a className="btn btn-ghost" href="#trust">Read our model card</a>
            </div>
          </div>

          {/* Right: live decision card */}
          <DecisionCard trajectory={trajectory} onOpen={onOpen} />
        </div>
      </div>
    </section>
  );
}

function FeatureRow({ num, title, detail }) {
  return (
    <div style={{ display: "flex", gap: 16, paddingTop: 14, borderTop: "1px solid var(--rule)" }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-mute)",
        paddingTop: 2, letterSpacing: ".05em",
      }}>{num}</div>
      <div>
        <div style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)" }}>{title}</div>
        <div style={{ fontSize: 14, color: "var(--ink-soft)", marginTop: 4, maxWidth: 480 }}>{detail}</div>
      </div>
    </div>
  );
}

// The live decision card — shows the inbound SMS, the AI reply, and a Why? button.
function DecisionCard({ trajectory, onOpen }) {
  return (
    <div style={{
      background: "var(--bg-elev)", border: "1px solid var(--rule)",
      borderRadius: 22, padding: 24, display: "flex", flexDirection: "column", gap: 18,
      boxShadow: "0 24px 60px -28px rgba(43, 27, 34, 0.18)",
    }}>
      {/* Convo header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingBottom: 14, borderBottom: "1px solid var(--rule)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 999,
            background: "var(--brand-soft)", color: "var(--brand-deep)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--font-display)", fontSize: 16,
          }}>SM</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Sarah M.</div>
            <div style={{ fontSize: 11, color: "var(--ink-mute)", fontFamily: "var(--font-mono)" }}>SMS · 14:32 · +1 (204) ••• 0192</div>
          </div>
        </div>
        <span className="chip chip-amber">urgent · 7/10</span>
      </div>

      {/* Inbound */}
      <div style={{ display: "flex" }}>
        <div style={{
          maxWidth: "82%", padding: "12px 16px", borderRadius: "16px 16px 16px 4px",
          background: "var(--bg-deep)", fontSize: 14, lineHeight: 1.5, color: "var(--ink)",
        }}>
          Hi — I chipped a front tooth last night and it's throbbing this morning. I'm not a patient yet. Any chance you can fit me in tomorrow?
        </div>
      </div>

      {/* ARIA reply */}
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <div style={{
          maxWidth: "86%", padding: "12px 16px", borderRadius: "16px 16px 4px 16px",
          background: "var(--brand)", color: "#FFF8F0", fontSize: 14, lineHeight: 1.5,
        }}>
          So sorry you're in pain, Sarah. We've held an urgent slot for you tomorrow at <strong>10:30 AM with Dr. Chen</strong> at our Tuxedo clinic. Reply <strong>YES</strong> to confirm — we'll text the intake form right after.
        </div>
      </div>

      {/* Decision footer */}
      <div style={{
        marginTop: 4, padding: 16, background: "var(--bg)",
        border: "1px solid var(--rule)", borderRadius: 14,
        display: "flex", flexDirection: "column", gap: 12,
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <div className="eyebrow" style={{ fontSize: 10 }}>ARIA decision</div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Book · urgent · Tuxedo / Dr. Chen / 10:30</div>
          </div>
          <span style={{ fontSize: 12, color: "var(--ink-mute)", fontFamily: "var(--font-mono)" }}>{trajectory.id}</span>
        </div>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <span className="chip chip-sage">conf · 0.94</span>
          <span className="chip">5 frameworks</span>
          <span className="chip">9 audit steps</span>
          <span className="chip chip-brand">Art. 13 · documented</span>
        </div>

        <button onClick={onOpen} className="btn btn-primary" style={{ alignSelf: "flex-start", marginTop: 4 }}>
          Why? <span style={{ opacity: .7, fontFamily: "var(--font-display)", fontStyle: "italic" }}>see the receipts</span>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AriaWhySection, AriaWhyModal, DecisionCard });
