/* global React, window */
/* ============================================================
   Answer panel + verdict chips (presentational).
   State is driven by the race controller in arena.jsx.
   ============================================================ */

// tiny inline icons (Lucide-style, 2px round)
function Glyph({ d, size = 14, color, fill = "none", sw = 2 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill}
      stroke={color} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"
      style={{ flex: "none" }}>
      {d}
    </svg>
  );
}
const IconCheck  = (p) => <Glyph {...p} d={<polyline points="20 6 9 17 4 12" />} />;
const IconX      = (p) => <Glyph {...p} d={<g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>} />;
const IconHalf   = (p) => <Glyph {...p} d={<g><circle cx="12" cy="12" r="9" /><path d="M12 3 a9 9 0 0 1 0 18 Z" fill={p.color} stroke="none" /></g>} />;
const IconAlert  = (p) => <Glyph {...p} d={<g><path d="M10.3 3.6 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.6a2 2 0 0 0-3.4 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></g>} />;
const IconEvidence = (p) => <Glyph {...p} d={<g><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></g>} />;
const IconChevron = (p) => <Glyph {...p} d={<polyline points="9 18 15 12 9 6" />} />;

const VERDICTS = {
  correct:    { label: "Correct",   icon: IconCheck, fg: "#15803D", bg: "#F0FDF4", bd: "#BBF7D0" },
  incorrect:  { label: "Incorrect", icon: IconX,     fg: "#B91C1C", bg: "#FEF2F2", bd: "#FECACA" },
  partial:    { label: "Partial",   icon: IconHalf,  fg: "#A16207", bg: "#FEFCE8", bd: "#FDE68A" },
  failed:     { label: "Failed",    icon: IconAlert, fg: "#B91C1C", bg: "#FEF2F2", bd: "#FECACA" },
  unverified: { label: "Answered",  icon: IconCheck, fg: "#525252", bg: "#F5F5F5", bd: "#E5E5E5" },
};

function VerdictChip({ verdict }) {
  const v = VERDICTS[verdict];
  if (!v) return null;
  const Ic = v.icon;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px 4px 8px",
      borderRadius: 999, background: v.bg, border: "1px solid " + v.bd, color: v.fg,
      font: "600 13px var(--font-sans)", whiteSpace: "nowrap",
    }}>
      <Ic size={14} color={v.fg} />{v.label}
    </span>
  );
}

function AnswerPanel({ model, label, version, accent, blind, st, onShowEvidence, evidenceOpen, anyEvidence, queryText }) {
  st = st || {};
  const streaming = st.running && !st.done;
  const showEvidenceBtn = model.ours && !blind && st.done && st.evidence;
  const showNoEvidence = !model.ours && !blind && st.done && anyEvidence;
  // link the SAME query into the vendor's own web app (illustrative)
  const guiUrl = model.gui
    ? (model.gui.slice(-1) === "=" ? model.gui + encodeURIComponent(queryText || "") : model.gui)
    : null;
  const showGui = !blind && guiUrl;

  return (
    <div style={{
      display: "flex", flexDirection: "column", minWidth: 0,
      background: "var(--surface)",
      border: (accent ? "1.5px" : "1px") + " solid " + (accent ? "var(--brand-orange)" : "var(--border)"),
      borderRadius: 14,
      boxShadow: accent ? "0 8px 24px -12px rgba(255,79,23,0.45), var(--shadow-sm)" : "var(--shadow-xs)",
      transform: accent ? "translateY(-4px)" : "none",
      transition: "transform .25s var(--ease, cubic-bezier(.2,0,0,1)), box-shadow .25s, border-color .25s",
      overflow: "hidden",
    }}>
      {/* header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between",
        padding: "11px 14px", borderBottom: "1px solid var(--border-subtle)",
        background: accent ? "linear-gradient(180deg,#FFF7F3,transparent)" : "transparent" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 9, minWidth: 0 }}>
          {accent && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--brand-orange)", flex: "none",
            marginTop: 5, boxShadow: "0 0 0 3px rgba(255,79,23,0.16)" }} />}
          <div style={{ minWidth: 0, display: "flex", flexDirection: "column", gap: 1 }}>
            <span style={{ font: "600 15px var(--font-sans)", color: "var(--fg-1)",
              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
            <span style={{ font: "500 11.5px var(--font-mono)", whiteSpace: "nowrap",
              color: accent ? "var(--brand-orange)" : "var(--fg-3)" }}>
              {blind ? "model hidden" : (version || "")}
            </span>
          </div>
        </div>
        {/* latency timer */}
        <span style={{ font: "500 13px var(--font-mono)", whiteSpace: "nowrap", marginTop: 1,
          color: streaming ? "var(--brand-orange)" : st.done ? "var(--fg-2)" : "var(--fg-4)" }}>
          {st.elapsed != null ? st.elapsed.toFixed(1) + "s" : "·"}
          {streaming && <span className="ev-cursor" style={{ marginLeft: 2 }}>●</span>}
        </span>
      </div>

      {/* body */}
      <div style={{ padding: "14px 16px", flex: 1, minHeight: 168, display: "flex", flexDirection: "column" }}>
        <div style={{ font: "400 14.5px/1.6 var(--font-sans)", color: "var(--fg-1)", flex: 1 }}>
          {st.text}
          {streaming && <span className="ev-caret">▍</span>}
          {st.failMsg && st.done && (
            <span style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 10,
              padding: "8px 10px", borderRadius: 8, background: "#FEF2F2", border: "1px solid #FECACA",
              color: "#B91C1C", font: "600 13px var(--font-sans)" }}>
              <IconAlert size={15} color="#B91C1C" />{st.failMsg}
            </span>
          )}
        </div>

        {/* footer: verdict + note */}
        {st.done && (
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <VerdictChip verdict={st.verdict} />
              {showEvidenceBtn && (
                <button onClick={onShowEvidence} style={{
                  display: "inline-flex", alignItems: "center", gap: 6, marginLeft: "auto",
                  padding: "6px 11px", borderRadius: 8, cursor: "pointer",
                  border: "1px solid var(--brand-orange)", background: evidenceOpen ? "var(--brand-orange)" : "#FFF7F3",
                  color: evidenceOpen ? "#fff" : "var(--brand-orange)", font: "600 13px var(--font-sans)",
                  transition: "all .15s" }}>
                  <IconEvidence size={14} color={evidenceOpen ? "#fff" : "var(--brand-orange)"} />
                  {evidenceOpen ? "Evidence shown" : "Show evidence"}
                  <span style={{ transform: evidenceOpen ? "rotate(90deg)" : "none", transition: "transform .2s", display: "inline-flex" }}>
                    <IconChevron size={13} color={evidenceOpen ? "#fff" : "var(--brand-orange)"} />
                  </span>
                </button>
              )}
            </div>
            {st.note && (
              <div style={{ font: "400 12.5px/1.5 var(--font-sans)", color: "var(--fg-2)" }}>
                <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)",
                  textTransform: "uppercase", letterSpacing: ".05em", marginRight: 6 }}>vs ground truth</span>
                {st.note}
              </div>
            )}
            {showNoEvidence && (
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 2,
                font: "400 12.5px var(--font-sans)", color: "var(--fg-4)" }}>
                <Glyph size={13} color="var(--fg-4)" d={<g><circle cx="12" cy="12" r="9" /><line x1="8" y1="12" x2="16" y2="12" /></g>} />
                No structured evidence available, answer is unverified text.
              </div>
            )}
            {showGui && (
              <a href={guiUrl} target="_blank" rel="noopener noreferrer" style={{
                display: "inline-flex", alignItems: "center", gap: 5, alignSelf: "flex-start", marginTop: 2,
                font: "500 12px var(--font-sans)", color: accent ? "var(--brand-orange)" : "var(--fg-3)",
                textDecoration: "none" }} className="ev-guilink">
                <Glyph size={12} color="currentColor" d={<g><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" /><polyline points="15 3 21 3 21 9" /><line x1="10" y1="14" x2="21" y2="3" /></g>} />
                Open this query in {model.name}
              </a>
            )}
          </div>
        )}
        {!st.done && !streaming && st.elapsed == null && (
          <div style={{ font: "400 13px var(--font-sans)", color: "var(--fg-4)", marginTop: "auto" }}>
            Waiting for question…
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AnswerPanel, VerdictChip });
