/* Diagnostic — triage list, failed gates first, score gauge at top. */
const { TOKENS: T_DIAG, useViewport: useViewportDiag } = window.IE_UI;
const { useState: useStateDiag } = React;

function ScoreGauge({ score, banner, msg }) {
  const { isMobile } = useViewportDiag();
  const colors = {
    green:  { fg: T_DIAG.green,  ring: "rgba(107,212,155,.3)", glow: "rgba(107,212,155,.08)" },
    yellow: { fg: T_DIAG.warn,   ring: "rgba(255,200,87,.3)",  glow: "rgba(255,200,87,.08)" },
    red:    { fg: T_DIAG.danger, ring: "rgba(255,118,118,.3)", glow: "rgba(255,118,118,.08)" },
  };
  const c = colors[banner];
  const radius = 38;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (score / 5) * circumference;
  return (
    <div style={{
      display: "flex", flexDirection: isMobile ? "column" : "row",
      alignItems: isMobile ? "flex-start" : "center", gap: isMobile ? 14 : 22,
      padding: isMobile ? "16px 18px" : "20px 24px", borderRadius: 10,
      background: c.glow, border: `1px solid ${c.ring}`,
    }}>
      <svg width="100" height="100" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r={radius} stroke={T_DIAG.borderSoft} strokeWidth="6" fill="none" />
        <circle cx="50" cy="50" r={radius} stroke={c.fg} strokeWidth="6" fill="none"
          strokeDasharray={circumference} strokeDashoffset={offset}
          strokeLinecap="round" transform="rotate(-90 50 50)"
          style={{ transition: "stroke-dashoffset .6s cubic-bezier(.2,.8,.2,1)" }} />
        <text x="50" y="50" textAnchor="middle" dominantBaseline="central"
          fill={c.fg} fontFamily={T_DIAG.mono} fontSize="22" fontWeight="700">{score}</text>
        <text x="50" y="68" textAnchor="middle" dominantBaseline="central"
          fill={T_DIAG.muted} fontFamily={T_DIAG.mono} fontSize="9" letterSpacing=".1em">/5</text>
      </svg>
      <div>
        <div style={{
          fontFamily: T_DIAG.mono, fontSize: 10.5, color: c.fg, fontWeight: 700,
          letterSpacing: ".12em", textTransform: "uppercase", marginBottom: 4,
        }}>
          {banner === "green" ? "Cleared" : banner === "yellow" ? "Caution" : "At material risk"}
        </div>
        <div style={{ font: `600 17px/1.3 ${T_DIAG.serif}`, color: T_DIAG.text, marginBottom: 6, letterSpacing: "-0.01em", maxWidth: 480 }}>{msg}</div>
        <div style={{ fontSize: 11.5, color: T_DIAG.muted }}>
          Advisory by default <span style={{ fontFamily: T_DIAG.mono, color: T_DIAG.mutedDeep }}>(ADR-015)</span>. Partner override allowed.
        </div>
      </div>
    </div>
  );
}

function GateCard({ gate, idx, defaultOpen }) {
  const [open, setOpen] = useStateDiag(defaultOpen);
  const failed = !gate.yes;
  const accent = failed ? T_DIAG.danger : T_DIAG.green;
  const bg = failed ? "rgba(255,118,118,.04)" : "transparent";
  return (
    <div style={{
      borderRadius: 6, border: `1px solid ${failed ? "rgba(255,118,118,.3)" : T_DIAG.borderSoft}`,
      background: bg, marginBottom: 10, overflow: "hidden",
    }}>
      <button onClick={() => setOpen(!open)} style={{
        width: "100%", textAlign: "left", padding: "14px 16px",
        background: "transparent", border: "none", cursor: "pointer",
        display: "flex", alignItems: "flex-start", gap: 14,
        font: `inherit`, color: "inherit",
      }}>
        <div style={{
          flexShrink: 0, padding: "3px 9px", borderRadius: 3,
          background: failed ? "rgba(255,118,118,.16)" : "rgba(107,212,155,.14)",
          color: accent, fontFamily: T_DIAG.mono, fontSize: 10, fontWeight: 700,
          letterSpacing: ".08em", marginTop: 2,
        }}>{failed ? "FAIL" : "PASS"}</div>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: T_DIAG.mono, fontSize: 10, color: T_DIAG.muted,
            letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 3,
          }}>Gate {idx + 1} · {gate.short}</div>
          <div style={{ font: `500 14px/1.4 ${T_DIAG.sans}`, color: T_DIAG.text }}>{gate.q}</div>
          {!open && failed && (
            <div style={{ fontSize: 12, color: T_DIAG.textDim, marginTop: 6, lineHeight: 1.5 }}>{gate.reason}</div>
          )}
        </div>
        <div style={{ color: T_DIAG.muted, fontFamily: T_DIAG.mono, fontSize: 11, marginTop: 4 }}>{open ? "▾" : "▸"}</div>
      </button>
      {open && (
        <div style={{ padding: "0 16px 14px 56px" }}>
          <div style={{ fontSize: 12.5, color: T_DIAG.textDim, lineHeight: 1.55, marginBottom: failed && gate.intervention ? 10 : 0 }}>
            {gate.reason}
          </div>
          {failed && gate.intervention && (
            <div style={{
              padding: "10px 12px", borderLeft: `2px solid ${T_DIAG.warn}`,
              background: "rgba(255,200,87,.06)", borderRadius: "0 4px 4px 0",
            }}>
              <div style={{
                fontFamily: T_DIAG.mono, fontSize: 10, color: T_DIAG.warn,
                letterSpacing: ".1em", textTransform: "uppercase", fontWeight: 700, marginBottom: 4,
              }}>Pre-kickoff intervention</div>
              <div style={{ fontSize: 12.5, color: T_DIAG.text, lineHeight: 1.5 }}>{gate.intervention}</div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function Diagnostic({ diag }) {
  if (!diag) return null;
  const failed = diag.gates.map((g, i) => ({ g, i })).filter((x) => !x.g.yes);
  const passed = diag.gates.map((g, i) => ({ g, i })).filter((x) => x.g.yes);

  return (
    <div>
      <ScoreGauge score={diag.score} banner={diag.banner} msg={diag.msg} />

      {failed.length > 0 && (
        <div style={{ marginTop: 24 }}>
          <div style={{
            display: "flex", alignItems: "baseline", justifyContent: "space-between",
            marginBottom: 10, paddingBottom: 8, borderBottom: `1px solid ${T_DIAG.borderSoft}`,
          }}>
            <div>
              <div style={{
                fontFamily: T_DIAG.mono, fontSize: 10.5, color: T_DIAG.danger, fontWeight: 700,
                letterSpacing: ".12em", textTransform: "uppercase", marginBottom: 2,
              }}>Triage · {failed.length} failed</div>
              <div style={{ font: `600 16px/1.2 ${T_DIAG.serif}`, color: T_DIAG.text, letterSpacing: "-0.01em" }}>
                What's broken — fix before kickoff.
              </div>
            </div>
          </div>
          {failed.map(({ g, i }) => <GateCard key={i} gate={g} idx={i} defaultOpen={true} />)}
        </div>
      )}

      <div style={{ marginTop: 24 }}>
        <div style={{
          display: "flex", alignItems: "baseline", justifyContent: "space-between",
          marginBottom: 10, paddingBottom: 8, borderBottom: `1px solid ${T_DIAG.borderSoft}`,
        }}>
          <div>
            <div style={{
              fontFamily: T_DIAG.mono, fontSize: 10.5, color: T_DIAG.green, fontWeight: 700,
              letterSpacing: ".12em", textTransform: "uppercase", marginBottom: 2,
            }}>Cleared · {passed.length} of 5</div>
            <div style={{ font: `600 16px/1.2 ${T_DIAG.serif}`, color: T_DIAG.text, letterSpacing: "-0.01em" }}>
              Validated. Click to expand evidence.
            </div>
          </div>
        </div>
        {passed.map(({ g, i }) => <GateCard key={i} gate={g} idx={i} defaultOpen={false} />)}
      </div>
    </div>
  );
}

window.IE_DIAGNOSTIC = { Diagnostic };
