/* global React, window, PidDiagram, KgSubgraph, SOURCES, UIcon */
/* ============================================================
   Evidence section (hero), scoreboard strip, upload modal.
   ============================================================ */
const { useState: useState2, useEffect: useEffect2 } = React;

function EvIcon(props) { return <UIcon {...props} />; }
const FileTxt = (p) => <EvIcon {...p} d={<g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="8" y1="13" x2="16" y2="13" /><line x1="8" y1="17" x2="13" y2="17" /></g>} />;

// ── Evidence section ─────────────────────────────────────────────
function EvidenceSection({ open, questionId, modelName }) {
  const sources = SOURCES[questionId] || SOURCES.default;
  return (
    <div style={{
      overflow: "hidden", transition: "max-height .4s cubic-bezier(.2,0,0,1), opacity .35s, margin .4s",
      maxHeight: open ? 920 : 0, opacity: open ? 1 : 0,
      margin: open ? "4px 22px 0" : "0 22px",
    }}>
      <div style={{ border: "1.5px solid var(--brand-orange)", borderRadius: 16, overflow: "hidden",
        background: "var(--surface)", boxShadow: "0 18px 50px -24px rgba(255,79,23,0.4)" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 20px",
          background: "linear-gradient(180deg,#FFF7F3,transparent)", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: "#FFF1EA",
            display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
            <EvIcon 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>} size={17} color="var(--brand-orange)" />
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ font: "600 16px var(--font-sans)", color: "var(--fg-1)" }}>Structured evidence · {modelName}</div>
            <div style={{ font: "400 12.5px var(--font-sans)", color: "var(--fg-2)" }}>
              Answer grounded in parsed symbols and a cited subgraph. Highlighted in orange.
            </div>
          </div>
        </div>

        {/* body grid */}
        <div style={{ display: "grid", gap: 0 }} className="ev-grid">
          {/* P&ID */}
          <div style={{ padding: "16px 20px", borderRight: "1px solid var(--border-subtle)" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".06em" }}>
                P&amp;ID · {sources[0]}
              </span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, font: "500 11.5px var(--font-sans)", color: "var(--brand-orange)" }}>
                <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--brand-orange)" }} className="ev-livedot" /> relevant symbols
              </span>
            </div>
            <div style={{ borderRadius: 12, border: "1px solid var(--border)", background: "#fff",
              padding: "8px 6px", overflow: "hidden" }}>
              {open && <PidDiagram questionId={questionId} />}
            </div>
          </div>

          {/* KG + sources */}
          <div style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
            <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".06em" }}>
              Knowledge graph
            </span>
            {open && <KgSubgraph questionId={questionId} />}
            <div>
              <div style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 7 }}>Sources</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {sources.map((s) => (
                  <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px",
                    borderRadius: 8, background: "var(--bg-subtle)", border: "1px solid var(--border)",
                    font: "500 12.5px var(--font-mono)", color: "var(--fg-1)" }}>
                    <FileTxt size={13} color="var(--fg-3)" /> {s}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Scoreboard ───────────────────────────────────────────────────
function Scoreboard({ models, tally, blind, revealed }) {
  // find leader by correct ratio then latency
  let leader = null, best = -1;
  models.forEach((m) => {
    const t = tally[m.key] || { correct: 0, total: 0 };
    const r = t.total ? t.correct / t.total : 0;
    if (r > best) { best = r; leader = m.key; }
  });
  return (
    <div style={{ padding: "16px 22px 8px", display: "flex", flexDirection: "column", gap: 10 }}>
      <span style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".07em" }}>
        Session scoreboard
      </span>
      <div style={{ display: "grid", gap: 12 }} className="ev-score" data-count={models.length}>
        {models.map((m, i) => {
          const t = tally[m.key] || { correct: 0, total: 0, latSum: 0, latN: 0 };
          const avg = t.latN ? (t.latSum / t.latN) : null;
          const showOurs = m.ours && (!blind || revealed);
          const isLeader = leader === m.key && t.total > 0 && (!blind || revealed);
          const label = (blind && !revealed) ? "Model " + String.fromCharCode(65 + i) : m.name;
          return (
            <div key={m.key} style={{ padding: "13px 15px", borderRadius: 12,
              border: "1px solid " + (showOurs ? "var(--brand-orange)" : "var(--border)"),
              background: showOurs ? "linear-gradient(180deg,#FFF7F3,var(--surface))" : "var(--surface)",
              boxShadow: showOurs ? "0 6px 18px -12px rgba(255,79,23,0.5)" : "var(--shadow-xs)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 9 }}>
                {showOurs && <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--brand-orange)" }} />}
                <span style={{ font: "600 13.5px var(--font-sans)", color: "var(--fg-1)",
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
                {isLeader && <span style={{ marginLeft: "auto", font: "600 10px var(--font-sans)", color: "var(--brand-orange)",
                  padding: "2px 7px", borderRadius: 999, background: "#FFF1EA", border: "1px solid #FFD8C7" }}>LEADING</span>}
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={{ font: "700 26px var(--font-sans)", letterSpacing: "-0.02em",
                  color: showOurs ? "var(--brand-orange)" : "var(--fg-1)" }}>{t.correct}</span>
                <span style={{ font: "500 15px var(--font-sans)", color: "var(--fg-3)" }}>/ {t.total}</span>
                <span style={{ font: "500 11px var(--font-sans)", color: "var(--fg-3)", marginLeft: 2 }}>correct</span>
              </div>
              <div style={{ font: "500 12px var(--font-mono)", color: "var(--fg-2)", marginTop: 4 }}>
                {avg != null ? "avg " + avg.toFixed(1) + "s" : "avg ·"}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Upload modal (parse pipeline) ────────────────────────────────
const PIPELINE = [
  { id: "upload",  label: "Upload",          sub: "Receiving drawing file" },
  { id: "symbol",  label: "Symbol detection", sub: "Vessels, valves, instruments" },
  { id: "tag",     label: "Tag extraction",   sub: "Equipment & loop tags" },
  { id: "connect", label: "Connectivity",     sub: "Lines & process flow" },
  { id: "graph",   label: "Knowledge graph",  sub: "Nodes & edges committed" },
];

const SAMPLE_FILES = [
  { name: "R279032044P04.pdf", size: "2.1 MB" },
  { name: "R279032044P05.pdf", size: "1.8 MB" },
  { name: "R279032044P06.pdf", size: "2.4 MB" },
];

function UploadModal({ open, onClose, onComplete }) {
  const [files, setFiles] = useState2(SAMPLE_FILES);
  const [step, setStep] = useState2(-1);   // -1 = idle, 0..n = parsing, n = done
  const [done, setDone] = useState2(false);
  const inputRef = React.useRef(null);

  useEffect2(() => {
    if (!open) { setFiles(SAMPLE_FILES); setStep(-1); setDone(false); }
  }, [open]);

  function startParse() {
    if (!files.length || step >= 0) return;
    let s = 0; setStep(0); setDone(false);
    const iv = setInterval(() => {
      s += 1;
      if (s >= PIPELINE.length) { clearInterval(iv); setStep(PIPELINE.length); setDone(true); }
      else setStep(s);
    }, 950);
  }

  function addFiles(list) {
    const extra = Array.from(list).map((f) => ({
      name: f.name, size: (f.size ? (f.size / 1048576).toFixed(1) + " MB" : "—"),
    }));
    if (extra.length) setFiles((prev) => [...prev, ...extra]);
  }

  if (!open) return null;
  const parsing = step >= 0 && !done;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 60,
      background: "rgba(10,10,10,0.5)", backdropFilter: "blur(3px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} className="ev-pop" style={{ width: "min(580px, 96vw)",
        maxHeight: "90vh", overflowY: "auto",
        background: "var(--surface)", borderRadius: 16, border: "1px solid var(--border)",
        boxShadow: "var(--shadow-xl)" }}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-subtle)",
          display: "flex", alignItems: "center", gap: 12, position: "sticky", top: 0, background: "var(--surface)", zIndex: 1 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: "#FFF1EA",
            display: "flex", alignItems: "center", justifyContent: "center" }}>
            <EvIcon 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>} size={17} color="var(--brand-orange)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ font: "600 16px var(--font-sans)", color: "var(--fg-1)" }}>Add your own P&amp;IDs</div>
            <div style={{ font: "400 12.5px var(--font-sans)", color: "var(--fg-2)" }}>
              Upload one or more drawings, parsed into the knowledge graph live
            </div>
          </div>
          <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", padding: 4 }}>
            <EvIcon d={<g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>} size={18} color="var(--fg-3)" />
          </button>
        </div>

        {/* drop zone */}
        <input ref={inputRef} type="file" multiple accept=".pdf,.dwg,.png,.jpg,.tiff" style={{ display: "none" }}
          onChange={(e) => addFiles(e.target.files)} />
        <div onClick={() => !parsing && inputRef.current && inputRef.current.click()}
          style={{ margin: "18px 22px 10px", padding: "20px", borderRadius: 12, textAlign: "center",
          border: "1.5px dashed var(--border-strong)", background: "var(--bg-subtle)", cursor: parsing ? "default" : "pointer",
          font: "500 13px var(--font-sans)", color: "var(--fg-3)" }}>
          <div style={{ font: "600 13.5px var(--font-sans)", color: "var(--fg-1)", marginBottom: 3 }}>
            Drop P&amp;IDs here or click to browse
          </div>
          PDF, DWG, or scanned image · multiple files supported
        </div>

        {/* file list */}
        <div style={{ padding: "0 22px", display: "flex", flexDirection: "column", gap: 8 }}>
          {files.map((f, i) => {
            const fileReady = done || (parsing && step > Math.floor(i * PIPELINE.length / Math.max(files.length, 1)));
            return (
              <div key={f.name + i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 12px",
                borderRadius: 10, border: "1px solid var(--border)", background: "var(--surface)" }}>
                <EvIcon d={<g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /></g>} size={17} color="var(--fg-3)" />
                <span style={{ flex: 1, font: "500 13.5px var(--font-mono)", color: "var(--fg-1)",
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name}</span>
                <span style={{ font: "400 12px var(--font-sans)", color: "var(--fg-3)" }}>{f.size}</span>
                {step >= 0 && (
                  <span style={{ font: "500 11px var(--font-mono)", width: 56, textAlign: "right",
                    color: fileReady ? "var(--success)" : "var(--brand-orange)" }}>
                    {fileReady ? "ready" : "parsing…"}
                  </span>
                )}
                {step < 0 && (
                  <button onClick={() => setFiles((p) => p.filter((_, j) => j !== i))}
                    style={{ border: "none", background: "transparent", cursor: "pointer", padding: 2, flex: "none" }}>
                    <EvIcon d={<g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>} size={15} color="var(--fg-4)" />
                  </button>
                )}
              </div>
            );
          })}
        </div>

        {/* pipeline (only while/after parsing) */}
        {step >= 0 && (
        <div style={{ padding: "14px 22px 4px", display: "flex", flexDirection: "column", gap: 2 }}>
          <div style={{ font: "600 11px var(--font-mono)", color: "var(--fg-3)", textTransform: "uppercase",
            letterSpacing: ".06em", marginBottom: 4 }}>Parse pipeline · {files.length} drawing{files.length > 1 ? "s" : ""}</div>
          {PIPELINE.map((p, i) => {
            const state = i < step ? "done" : i === step ? "active" : "pending";
            return (
              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 13, padding: "9px 4px" }}>
                <div style={{ width: 26, height: 26, borderRadius: 999, flex: "none",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  background: state === "done" ? "var(--success)" : state === "active" ? "#FFF1EA" : "var(--bg-muted)",
                  border: state === "active" ? "1.5px solid var(--brand-orange)" : "1px solid var(--border)" }}>
                  {state === "done"
                    ? <EvIcon d={<polyline points="20 6 9 17 4 12" />} size={14} color="#fff" />
                    : state === "active"
                      ? <span className="ev-spin" style={{ width: 13, height: 13, borderRadius: 999,
                          border: "2px solid #FFD8C7", borderTopColor: "var(--brand-orange)" }} />
                      : <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--fg-4)" }} />}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ font: "600 14px var(--font-sans)",
                    color: state === "pending" ? "var(--fg-4)" : "var(--fg-1)" }}>{p.label}</div>
                  <div style={{ font: "400 12px var(--font-sans)",
                    color: state === "pending" ? "var(--fg-4)" : "var(--fg-2)" }}>{p.sub}</div>
                </div>
                {state === "done" && <span style={{ font: "500 11px var(--font-mono)", color: "var(--success)" }}>ready</span>}
                {state === "active" && <span style={{ font: "500 11px var(--font-mono)", color: "var(--brand-orange)" }}>parsing…</span>}
              </div>
            );
          })}
        </div>
        )}

        {/* footer action */}
        <div style={{ padding: "14px 22px 22px" }}>
          {done ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
              <div style={{ flex: 1, minWidth: 200, padding: "12px 14px", borderRadius: 10, background: "#F0FDF4",
                border: "1px solid #BBF7D0", display: "flex", alignItems: "center", gap: 9,
                font: "600 13.5px var(--font-sans)", color: "#15803D" }}>
                <EvIcon d={<polyline points="20 6 9 17 4 12" />} size={16} color="#15803D" />
                {files.length} drawing{files.length > 1 ? "s" : ""} added · knowledge graph updated
              </div>
              <button onClick={() => { onComplete && onComplete(files.length); onClose(); }} style={{
                padding: "11px 20px", borderRadius: 10, border: "none", cursor: "pointer",
                background: "var(--brand-orange)", color: "#fff", font: "600 14px var(--font-sans)" }}>
                Done
              </button>
            </div>
          ) : (
            <button onClick={startParse} disabled={!files.length || parsing} style={{
              width: "100%", padding: "13px", borderRadius: 11, border: "none",
              cursor: (!files.length || parsing) ? "default" : "pointer",
              background: (!files.length || parsing) ? "var(--neutral-400)" : "var(--brand-orange)",
              color: "#fff", font: "600 14.5px var(--font-sans)" }}>
              {parsing ? "Parsing…" : "Parse " + files.length + " drawing" + (files.length > 1 ? "s" : "") + " into knowledge graph"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EvidenceSection, Scoreboard, UploadModal });
