/* global React, window */
/* ============================================================
   Evidence diagram, the hero moment.
   A clean schematic P&ID fragment of a debutanizer plus a
   knowledge-graph subgraph. Answer-relevant symbols pulse in
   the Intuigence orange. Pure inline SVG, no images.
   ============================================================ */
const ORANGE = "#FF4F17";
const INK = "#262626";
const LINE = "#737373";
const MUTE = "#A3A3A3";

// Which symbols light up for each question.
const HIGHLIGHTS = {
  pic1108: ["PIC1108"],
  valves:  ["FV1102", "PV1108"],
  relief:  ["PSV1140"],
  connect: ["P-110A", "E-114"],
  default: ["PIC1108"],
};

// Knowledge-graph focus node label per question.
const KG_TAG = {
  pic1108: "PIC1108",
  valves:  "FV1102 · PV1108",
  relief:  "PSV1140",
  connect: "P-110A",
  default: "PIC1108",
};

const SOURCES = {
  pic1108: ["Sheet R279032044P01", "Note 1"],
  valves:  ["Sheet R279032044P01", "Overhead line"],
  relief:  ["Sheet R279032044P03", "Flare header"],
  connect: ["Sheet R279032044P02", "Reboiler loop"],
  default: ["Sheet R279032044P01", "Note 1"],
};

function isHot(active, id) { return active.indexOf(id) !== -1; }

// ── Symbol primitives ───────────────────────────────────────────
function Vessel({ x, y, w, h, label }) {
  const r = w / 2;
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={r} fill="#fff" stroke={INK} strokeWidth="1.6" />
      <text x={x + w / 2} y={y - 9} textAnchor="middle" fontSize="12"
        fontWeight="600" fill={INK} fontFamily="var(--font-sans)">{label}</text>
    </g>
  );
}

function HVessel({ x, y, w, h, label }) {
  const r = h / 2;
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={r} fill="#fff" stroke={INK} strokeWidth="1.6" />
      <text x={x + w / 2} y={y - 8} textAnchor="middle" fontSize="12"
        fontWeight="600" fill={INK} fontFamily="var(--font-sans)">{label}</text>
    </g>
  );
}

function Exchanger({ cx, cy, label }) {
  return (
    <g>
      <circle cx={cx} cy={cy} r="20" fill="#fff" stroke={INK} strokeWidth="1.6" />
      <path d={`M ${cx - 20} ${cy} h 40`} stroke={INK} strokeWidth="1.2" />
      <path d={`M ${cx - 12} ${cy - 7} l 24 14 M ${cx - 12} ${cy + 7} l 24 -14`} stroke={INK} strokeWidth="1.2" fill="none" />
      <text x={cx} y={cy + 36} textAnchor="middle" fontSize="11.5"
        fontWeight="600" fill={INK} fontFamily="var(--font-sans)">{label}</text>
    </g>
  );
}

function Pump({ cx, cy, label }) {
  return (
    <g>
      <circle cx={cx} cy={cy} r="16" fill="#fff" stroke={INK} strokeWidth="1.6" />
      <path d={`M ${cx - 9} ${cy - 9} L ${cx + 13} ${cy} L ${cx - 9} ${cy + 9} Z`} fill={INK} opacity="0.85" />
      <text x={cx} y={cy + 32} textAnchor="middle" fontSize="11.5"
        fontWeight="600" fill={INK} fontFamily="var(--font-sans)">{label}</text>
    </g>
  );
}

// Control valve: bowtie + actuator. Highlightable.
function ControlValve({ cx, cy, id, hot }) {
  const stroke = hot ? ORANGE : INK;
  return (
    <g className={hot ? "ev-pulse" : ""}>
      {hot && <circle cx={cx} cy={cy} r="26" fill={ORANGE} opacity="0.10" className="ev-halo" />}
      <path d={`M ${cx - 11} ${cy - 9} L ${cx + 11} ${cy + 9} L ${cx + 11} ${cy - 9} L ${cx - 11} ${cy + 9} Z`}
        fill="#fff" stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} strokeLinejoin="round" />
      {/* actuator */}
      <path d={`M ${cx} ${cy - 9} V ${cy - 18}`} stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} />
      <path d={`M ${cx - 8} ${cy - 18} Q ${cx} ${cy - 27} ${cx + 8} ${cy - 18} Z`}
        fill={hot ? ORANGE : "#fff"} stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} />
      <text x={cx} y={cy + 26} textAnchor="middle" fontSize="11"
        fontWeight={hot ? 700 : 600} fill={hot ? ORANGE : INK}
        fontFamily="var(--font-mono)">{id}</text>
    </g>
  );
}

// Relief valve: angle body venting up.
function ReliefValve({ cx, cy, id, hot }) {
  const stroke = hot ? ORANGE : INK;
  return (
    <g className={hot ? "ev-pulse" : ""}>
      {hot && <circle cx={cx} cy={cy} r="24" fill={ORANGE} opacity="0.10" className="ev-halo" />}
      <path d={`M ${cx - 10} ${cy + 9} L ${cx + 10} ${cy + 9} L ${cx} ${cy - 6} Z`}
        fill="#fff" stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} strokeLinejoin="round" />
      <path d={`M ${cx} ${cy - 6} V ${cy - 20}`} stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} />
      <path d={`M ${cx - 6} ${cy - 16} L ${cx} ${cy - 24} L ${cx + 6} ${cy - 16}`}
        fill="none" stroke={stroke} strokeWidth={hot ? 2.2 : 1.6} strokeLinejoin="round" />
      <text x={cx + 4} y={cy + 24} textAnchor="middle" fontSize="11"
        fontWeight={hot ? 700 : 600} fill={hot ? ORANGE : INK}
        fontFamily="var(--font-mono)">{id}</text>
    </g>
  );
}

// Instrument bubble with dashed connector to its tap point.
function Instrument({ cx, cy, tapX, tapY, top, bottom, hot }) {
  const stroke = hot ? ORANGE : LINE;
  return (
    <g className={hot ? "ev-pulse" : ""}>
      <path d={`M ${cx} ${cy + 16} L ${tapX} ${tapY}`} stroke={stroke} strokeWidth="1.2" strokeDasharray="3 3" />
      {hot && <circle cx={cx} cy={cy} r="24" fill={ORANGE} opacity="0.10" className="ev-halo" />}
      <circle cx={cx} cy={cy} r="16" fill="#fff" stroke={hot ? ORANGE : INK} strokeWidth={hot ? 2.2 : 1.6} />
      <line x1={cx - 16} y1={cy} x2={cx + 16} y2={cy} stroke={hot ? ORANGE : INK} strokeWidth="0.9" opacity="0.5" />
      <text x={cx} y={cy - 2} textAnchor="middle" fontSize="9" fontWeight="700"
        fill={hot ? ORANGE : INK} fontFamily="var(--font-mono)">{top}</text>
      <text x={cx} y={cy + 9} textAnchor="middle" fontSize="9" fontWeight="600"
        fill={hot ? ORANGE : INK} fontFamily="var(--font-mono)">{bottom}</text>
    </g>
  );
}

// ── The P&ID ────────────────────────────────────────────────────
function PidDiagram({ questionId }) {
  const active = HIGHLIGHTS[questionId] || HIGHLIGHTS.default;
  const pipe = { stroke: LINE, strokeWidth: 1.6, fill: "none" };
  const hotPipe = { stroke: ORANGE, strokeWidth: 2.4, fill: "none" };
  // overhead line hot when a valve/instrument on it is active
  const ohHot = active.some((a) => ["PIC1108", "PV1108", "FV1102"].indexOf(a) !== -1);
  const reliefHot = isHot(active, "PSV1140");
  const bottomsHot = active.some((a) => ["P-110A", "E-114"].indexOf(a) !== -1);

  return (
    <svg viewBox="0 0 824 470" width="100%" style={{ display: "block" }}>
      <rect x="0" y="0" width="824" height="470" fill="none" />

      {/* ── piping ── */}
      {/* overhead: top of column up and across to condenser */}
      <path d="M 142 110 V 76 H 410" {...(ohHot ? hotPipe : pipe)} />
      {/* condenser to drum top */}
      <path d="M 450 76 H 520 V 120" {...pipe} />
      {/* drum to reflux/distillate down */}
      <path d="M 560 168 V 300 H 250 V 246" {...pipe} />
      {/* reflux back to column */}
      <path d="M 250 220 V 150 H 142" {...pipe} />
      {/* relief: drum top to flare */}
      <path d="M 612 120 V 96" {...(reliefHot ? hotPipe : pipe)} />
      <path d="M 612 76 V 36 H 706" {...(reliefHot ? hotPipe : pipe)} />
      {/* bottoms: column bottom to pump to reboiler and return */}
      <path d="M 142 372 V 410 H 226" {...(bottomsHot ? hotPipe : pipe)} />
      <path d="M 266 410 H 360" {...(bottomsHot ? hotPipe : pipe)} />
      <path d="M 408 392 V 352 H 175" {...(bottomsHot ? hotPipe : pipe)} />

      {/* flare arrow + label */}
      <path d="M 706 36 l -7 -4 v 8 Z" fill={reliefHot ? ORANGE : LINE} />
      <text x="712" y="40" fontSize="11" fontWeight="600" fill={reliefHot ? ORANGE : LINE}
        fontFamily="var(--font-sans)">To flare</text>

      {/* ── equipment ── */}
      <Vessel x={110} y={110} w={64} h={262} label="T-101 Debutanizer" />
      <Exchanger cx={430} cy={76} label="E-101 Condenser" />
      <HVessel x={500} y={120} w={120} h={48} label="V-102 OH Drum" />
      <Pump cx={246} cy={410} label="P-110A" />
      <rect x={360} y={392} width={48} height={36} rx={4} fill="#fff" stroke={bottomsHot ? ORANGE : INK} strokeWidth={bottomsHot ? 2.2 : 1.6} />
      <text x={384} y={444} textAnchor="middle" fontSize="11.5" fontWeight="600"
        fill={bottomsHot ? ORANGE : INK} fontFamily="var(--font-sans)">E-114 Reboiler</text>

      {/* ── valves & instruments ── */}
      <ControlValve cx={250} cy={76} id="PV1108" hot={isHot(active, "PV1108")} />
      <Instrument cx={336} cy={34} tapX={336} tapY={76} top="PIC" bottom="1108" hot={isHot(active, "PIC1108")} />
      <ControlValve cx={400} cy={300} id="FV1102" hot={isHot(active, "FV1102")} />
      <ReliefValve cx={612} cy={108} id="PSV1140" hot={reliefHot} />

      {/* pump hot ring */}
      {bottomsHot && <circle cx={246} cy={410} r="24" fill={ORANGE} opacity="0.10" className="ev-halo" />}
    </svg>
  );
}

// ── Knowledge-graph subgraph ─────────────────────────────────────
function KgSubgraph({ questionId }) {
  const tag = KG_TAG[questionId] || KG_TAG.default;
  const src = SOURCES[questionId] || SOURCES.default;
  // node layout
  const nodes = [
    { id: "site",  x: 24,  y: 20,  label: "NGL Plant", type: "Site", dim: true },
    { id: "sheet", x: 150, y: 96,  label: src[0], type: "Document", hot: true },
    { id: "note",  x: 22,  y: 150, label: src[1], type: "Note", hot: true },
    { id: "tag",   x: 168, y: 196, label: tag, type: "Tag", hot: true, focus: true },
  ];
  function node(n) {
    const border = n.hot ? ORANGE : "var(--border)";
    return (
      <div key={n.id} style={{
        position: "absolute", left: n.x, top: n.y, opacity: n.dim ? 0.55 : 1,
        background: n.focus ? "#FFF7F3" : "#fff",
        border: (n.hot ? "1.5px" : "1px") + " solid " + border,
        borderRadius: 9, padding: "7px 10px", display: "flex", flexDirection: "column",
        boxShadow: "var(--shadow-xs)", minWidth: 96, maxWidth: 150,
      }}>
        <span style={{ font: "600 12px var(--font-sans)", color: n.hot ? "#9A2D0B" : "var(--fg-1)",
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{n.label}</span>
        <span style={{ font: "500 9px var(--font-mono)", color: n.hot ? ORANGE : "var(--fg-3)",
          textTransform: "uppercase", letterSpacing: ".06em" }}>{n.type}</span>
      </div>
    );
  }
  return (
    <div style={{ position: "relative", height: 250,
      background: "radial-gradient(circle, #D4D4D4 1px, transparent 1.2px) 0 0/18px 18px, #FAFAFA",
      borderRadius: 12, border: "1px solid var(--border)", overflow: "hidden" }}>
      <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}>
        {/* site -> sheet (dim) */}
        <line x1="92" y1="46" x2="180" y2="96" stroke={MUTE} strokeWidth="1.2" strokeDasharray="4 4" />
        {/* sheet -> note (hot) */}
        <line x1="150" y1="118" x2="92" y2="158" stroke={ORANGE} strokeWidth="2" className="ev-edge" />
        {/* note -> tag (hot) */}
        <line x1="78" y1="178" x2="180" y2="200" stroke={ORANGE} strokeWidth="2" className="ev-edge" />
        {/* sheet -> tag (hot) */}
        <line x1="196" y1="124" x2="208" y2="196" stroke={ORANGE} strokeWidth="2" className="ev-edge" />
      </svg>
      {nodes.map(node)}
      <div style={{ position: "absolute", right: 12, bottom: 10,
        font: "500 10px var(--font-mono)", color: "var(--fg-3)",
        textTransform: "uppercase", letterSpacing: ".06em" }}>Highlighted subgraph</div>
    </div>
  );
}

Object.assign(window, { PidDiagram, KgSubgraph, SOURCES });
