/* global React, window, PidDiagram, KgSubgraph, SOURCES */
/* ============================================================
   Arena UI chrome, header, controls, drawers, scoreboard,
   evidence section, upload modal. Presentational + light state.
   ============================================================ */
const { useState, useEffect, useRef } = React;

function UIcon({ d, size = 16, color = "currentColor", sw = 2, fill = "none" }) {
  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 Plus    = (p) => <UIcon {...p} d={<g><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></g>} />;
const BankIco = (p) => <UIcon {...p} d={<g><rect x="3" y="4" width="18" height="5" rx="1" /><rect x="3" y="11" width="18" height="5" rx="1" /><line x1="3" y1="20" x2="21" y2="20" /></g>} />;
const Check   = (p) => <UIcon {...p} d={<polyline points="20 6 9 17 4 12" />} />;
const Eye     = (p) => <UIcon {...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 EyeOff  = (p) => <UIcon {...p} d={<g><path d="M9.9 4.2A9.1 9.1 0 0 1 12 4c7 0 10 8 10 8a17 17 0 0 1-2.2 3.2M6.6 6.6A17 17 0 0 0 2 12s3 8 10 8a9 9 0 0 0 4-1M3 3l18 18" /></g>} />;
const Graph   = (p) => <UIcon {...p} d={<g><circle cx="5" cy="6" r="2.5" /><circle cx="19" cy="6" r="2.5" /><circle cx="12" cy="18" r="2.5" /><line x1="7" y1="7" x2="10.5" y2="16" /><line x1="17" y1="7" x2="13.5" y2="16" /><line x1="7.4" y1="6" x2="16.6" y2="6" /></g>} />;
const Close   = (p) => <UIcon {...p} d={<g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>} />;
const Upload  = (p) => <UIcon {...p} d={<g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></g>} />;
const Cmd     = (p) => <UIcon {...p} d={<path d="M6 6a2 2 0 1 1 2 2H6V6m0 0v4m0 4a2 2 0 1 0 2-2H6v2m12-8a2 2 0 1 0-2 2h2V6m0 0v4m0 4a2 2 0 1 1-2-2h2v2" />} />;

const CAT_COLORS = {
  Valves: "#2563EB", Tags: "#A855F7", Connectivity: "#0EA5A4", Safety: "#DC2626",
};

// ── Header ───────────────────────────────────────────────────────
function Header({ corpus, setCorpus, corpora, blind, setBlind, revealed, onReveal, onUpload, running, uploadedCount }) {
  return (
    <header style={{ display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap",
      padding: "14px 22px", borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
      {/* brand */}
      <div style={{ display: "flex", alignItems: "center", gap: 11, flex: "none" }}>
        <img src="assets/logo-mark-orange.svg" alt="" style={{ width: 26, height: 26 }} />
        <span style={{ font: "600 18px var(--font-sans)", letterSpacing: "-0.02em", color: "var(--fg-1)" }}>
          P&amp;ID Arena
        </span>
      </div>

      {/* corpus selector */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginLeft: 8 }}>
        <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)",
          textTransform: "uppercase", letterSpacing: ".07em" }}>Corpus</span>
        <div style={{ display: "flex", gap: 0, padding: 3, borderRadius: 11,
          background: "var(--bg-muted)", border: "1px solid var(--border)" }}>
          {corpora.map((c) => {
            const on = c.id === corpus;
            return (
              <button key={c.id} onClick={() => setCorpus(c.id)} disabled={running} style={{
                display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 1,
                padding: "6px 14px", borderRadius: 8, border: "none", cursor: running ? "default" : "pointer",
                background: on ? "var(--surface)" : "transparent",
                boxShadow: on ? "var(--shadow-xs)" : "none",
                opacity: running && !on ? 0.5 : 1, transition: "all .15s" }}>
                <span style={{ font: "600 14px var(--font-sans)", color: on ? "var(--fg-1)" : "var(--fg-2)", whiteSpace: "nowrap" }}>{c.label}</span>
                <span style={{ font: "500 10px var(--font-sans)", color: on ? "var(--brand-orange)" : "var(--fg-4)", whiteSpace: "nowrap" }}>{c.sub}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{ flex: 1 }} />

      {/* status chip */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 12px",
        borderRadius: 999, background: "var(--bg-subtle)", border: "1px solid var(--border)" }}>
        <span className="ev-livedot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--success)", flex: "none" }} />
        <span style={{ font: "500 12.5px var(--font-sans)", color: "var(--fg-2)", whiteSpace: "nowrap" }}>
          {uploadedCount > 0
            ? "Corpus + " + uploadedCount + " of your drawing" + (uploadedCount > 1 ? "s" : "") + " · in Knowledge Graph"
            : "Corpus loaded · parsed into Knowledge Graph"}
        </span>
      </div>

      {/* blind toggle / reveal */}
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <button onClick={() => setBlind(!blind)} style={{
          display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 9,
          cursor: "pointer", font: "600 13px var(--font-sans)",
          border: "1px solid " + (blind ? "var(--fg-1)" : "var(--border)"),
          background: blind ? "var(--fg-1)" : "var(--surface)", color: blind ? "var(--surface)" : "var(--fg-2)",
          transition: "all .15s" }}>
          {blind ? <EyeOff size={15} color="currentColor" /> : <Eye size={15} color="currentColor" />}
          Blind mode
        </button>
        {blind && !revealed && (
          <button onClick={onReveal} style={{
            display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 13px", borderRadius: 9,
            cursor: "pointer", font: "600 13px var(--font-sans)", border: "1px solid var(--brand-orange)",
            background: "var(--brand-orange)", color: "#fff" }}>
            Reveal
          </button>
        )}
      </div>

      {/* upload */}
      <button onClick={onUpload} style={{
        display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 9,
        cursor: "pointer", font: "600 13px var(--font-sans)", border: "1px solid var(--border)",
        background: "var(--surface)", color: "var(--fg-1)" }}>
        <Plus size={15} color="currentColor" /> Add your own P&amp;ID
      </button>
    </header>
  );
}

// ── Question bar ─────────────────────────────────────────────────
function QuestionBar({ value, setValue, onRun, onToggleBank, bankOpen, running, corpusDetail,
  competitors, selected, onToggleCompetitor }) {
  const ref = useRef(null);
  useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); onRun(); }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onRun]);

  return (
    <div style={{ padding: "18px 22px", display: "flex", flexDirection: "column", gap: 8 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <button onClick={onToggleBank} style={{
          display: "inline-flex", alignItems: "center", gap: 8, padding: "0 16px", height: 52, borderRadius: 12,
          cursor: "pointer", font: "600 14px var(--font-sans)", flex: "none",
          border: "1px solid " + (bankOpen ? "var(--fg-1)" : "var(--border)"),
          background: bankOpen ? "var(--fg-1)" : "var(--surface)", color: bankOpen ? "var(--surface)" : "var(--fg-1)",
          transition: "all .15s" }}>
          <BankIco size={17} color="currentColor" /> Question bank
        </button>

        <div style={{ position: "relative", flex: 1 }}>
          <input ref={ref} value={value} onChange={(e) => setValue(e.target.value)}
            placeholder="Ask all models…" disabled={running}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.metaKey && !e.ctrlKey) onRun(); }}
            style={{ width: "100%", height: 52, padding: "0 18px", borderRadius: 12,
              border: "1px solid var(--border)", background: "var(--surface)", outline: "none",
              font: "400 16px var(--font-sans)", color: "var(--fg-1)", boxShadow: "var(--shadow-xs)" }} />
        </div>

        <button onClick={onRun} disabled={running} style={{
          display: "inline-flex", alignItems: "center", gap: 9, padding: "0 22px", height: 52, borderRadius: 12,
          cursor: running ? "default" : "pointer", flex: "none", font: "600 15px var(--font-sans)",
          border: "none", background: running ? "var(--neutral-400)" : "var(--brand-orange)", color: "#fff",
          boxShadow: running ? "none" : "0 6px 18px -8px rgba(255,79,23,0.6)", transition: "all .15s" }}>
          {running ? "Running…" : (<><span style={{ display: "inline-flex", gap: 1, alignItems: "center",
            padding: "3px 6px", borderRadius: 6, background: "rgba(255,255,255,0.22)", font: "600 12px var(--font-mono)" }}>
            <Cmd size={13} color="#fff" />↵</span> Run</>)}
        </button>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14, paddingLeft: 2, flexWrap: "wrap" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <Graph size={13} color="var(--fg-4)" />
          <span style={{ font: "500 12px var(--font-sans)", color: "var(--fg-3)" }}>{corpusDetail}</span>
        </span>
        {competitors && competitors.length > 0 && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, marginLeft: "auto", flexWrap: "wrap" }}>
            <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)",
              textTransform: "uppercase", letterSpacing: ".06em" }}>Compare against</span>
            {(() => {
              const allOn = competitors.every((c) => selected[c.key]);
              return (
                <button onClick={() => onToggleCompetitor("__all", !allOn)} disabled={running} style={{
                  display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 10px", borderRadius: 999,
                  cursor: running ? "default" : "pointer", font: "600 12px var(--font-sans)",
                  border: "1px solid " + (allOn ? "var(--fg-1)" : "var(--border)"),
                  background: allOn ? "var(--fg-1)" : "var(--surface)", color: allOn ? "var(--surface)" : "var(--fg-2)",
                  opacity: running ? 0.6 : 1, transition: "all .15s" }}>All</button>
              );
            })()}
            {competitors.map((c) => {
              const on = !!selected[c.key];
              return (
                <button key={c.key} onClick={() => onToggleCompetitor(c.key, !on)} disabled={running} style={{
                  display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 11px", borderRadius: 999,
                  cursor: running ? "default" : "pointer", font: "600 12px var(--font-sans)",
                  border: "1px solid " + (on ? "var(--border-strong)" : "var(--border)"),
                  background: on ? "var(--bg-subtle)" : "var(--surface)", color: on ? "var(--fg-1)" : "var(--fg-4)",
                  opacity: running ? 0.6 : 1, transition: "all .15s" }}>
                  <span style={{ width: 13, height: 13, borderRadius: 4, flex: "none",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    border: "1.5px solid " + (on ? "var(--fg-1)" : "var(--border-strong)"),
                    background: on ? "var(--fg-1)" : "transparent" }}>
                    {on && <Check size={9} color="var(--surface)" />}
                  </span>
                  {c.name}
                </button>
              );
            })}
          </span>
        )}
      </div>
    </div>
  );
}

// ── Question bank drawer ─────────────────────────────────────────
function QuestionBank({ open, questions, onPick, onClose }) {
  if (!open) return null;
  return (
    <div style={{ padding: "0 22px 14px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <span style={{ font: "600 12px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".07em" }}>
          Suggested questions
        </span>
        <button onClick={onClose} style={{ display: "inline-flex", alignItems: "center", gap: 5,
          border: "none", background: "transparent", cursor: "pointer", font: "500 12px var(--font-sans)", color: "var(--fg-3)" }}>
          <Close size={13} color="currentColor" /> Close
        </button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
        {questions.map((q) => {
          const cat = CAT_COLORS[q.category] || "var(--fg-3)";
          return (
            <button key={q.id} onClick={() => onPick(q)} className="ev-card" style={{
              textAlign: "left", padding: 14, borderRadius: 12, cursor: "pointer",
              border: "1px solid var(--border)", background: "var(--surface)", display: "flex",
              flexDirection: "column", gap: 10, boxShadow: "var(--shadow-xs)" }}>
              <span style={{ font: "500 14.5px/1.45 var(--font-sans)", color: "var(--fg-1)" }}>{q.text}</span>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 9px", borderRadius: 999,
                  font: "600 11px var(--font-sans)", color: cat, background: cat + "14", border: "1px solid " + cat + "33" }}>
                  {q.category}
                </span>
                {q.verified && (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4, marginLeft: "auto",
                    font: "600 11px var(--font-sans)", color: "var(--success)" }}>
                    <Check size={13} color="var(--success)" /> verified answer
                  </span>
                )}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Header, QuestionBar, QuestionBank, UIcon, CAT_COLORS });
