// harness-demo.jsx — animated Excel wire list -> harness diagram (hero signature)
// Output panel shows the REAL Tractus output (assets/tr-1001-001-sheet2.png, from draw.io),
// revealed with a JS-driven plotter-style wipe.
// NOTE: no CSS transitions/animations on the reveal — this engine freezes them mid-flight.
// All motion is driven by requestAnimationFrame updating inline styles.
const { useState, useEffect, useRef, useCallback } = React;

const WIRE_ROWS = [
  { id: "W1001", from: "J1-3", to: "J2-3", ga: "24", sig: "CAN_H", hex: "#e8453c" },
  { id: "W1002", from: "J1-4", to: "J2-4", ga: "24", sig: "CAN_L", hex: "#e8453c" },
  { id: "W1003", from: "J1-1", to: "J2-1", ga: "20", sig: "PWR_28V", hex: "#2bb5a0" },
  { id: "W1004", from: "J1-2", to: "J2-2", ga: "20", sig: "GND", hex: "#2b3cf2" },
  { id: "W1005", from: "J1-8", to: "J2-5", ga: "22", sig: "5V", hex: "#f019d8" },
  { id: "W1006", from: "J1-9", to: "J2-7", ga: "22", sig: "RTN_A", hex: "#39e6e6" },
];

function HarnessDemo() {
  const [phase, setPhase] = useState("idle"); // idle | reading | generating | done
  const [readRow, setReadRow] = useState(-1);
  const [clock, setClock] = useState(0);
  const [progress, setProgress] = useState(0);
  const [draw, setDraw] = useState(0); // 0..1 wipe progress, rAF-driven
  const ref = useRef(null);
  const timers = useRef([]);
  const started = useRef(false);

  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const push = (fn, ms) => timers.current.push(setTimeout(fn, ms));

  const run = useCallback(() => {
    clearTimers();
    setPhase("reading"); setReadRow(-1); setProgress(0); setClock(0); setDraw(0);
    WIRE_ROWS.forEach((_, i) => push(() => setReadRow(i), 140 + i * 130));
    const genStart = 140 + WIRE_ROWS.length * 130 + 220;
    push(() => {
      setPhase("generating");
      let p = 0;
      const iv = setInterval(() => {
        p += 1;
        setProgress(Math.min(100, p * 4));
        setClock(Math.min(32, Math.round(p * 1.28)));
        if (p >= 25) clearInterval(iv);
      }, 46);
      timers.current.push(() => clearInterval(iv));
    }, genStart);
    push(() => { setProgress(100); setClock(32); setPhase("done"); }, genStart + 1280);
  }, []);

  useEffect(() => {
    if (started.current) return;
    started.current = true;
    const tmo = setTimeout(run, 650);
    return () => { clearTimeout(tmo); clearTimers(); };
  }, [run]);

  // plotter wipe: rAF advances `draw` 0→1 once generation completes
  useEffect(() => {
    if (phase !== "done") return;
    let raf = 0, start = null;
    const D = 2100;
    const step = (ts) => {
      if (start === null) start = ts;
      const p = Math.min(1, (ts - start) / D);
      setDraw(p);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    const safety = setTimeout(() => { cancelAnimationFrame(raf); setDraw(1); }, D + 600);
    return () => { cancelAnimationFrame(raf); clearTimeout(safety); };
  }, [phase]);

  const statusMap = {
    idle: ["STANDBY", "Awaiting wire list"],
    reading: ["READING", "Parsing wire_list.xlsx · 11 circuits"],
    generating: ["ROUTING", "Routing 11 circuits + DRC"],
    done: ["COMPLETE", "wire_list.drawio"],
  };
  const [st, stSub] = statusMap[phase];
  const mmss = `00:${String(clock).padStart(2, "0")}`;
  const wiping = phase === "done" && draw < 1;

  return (
    <div ref={ref} className="hd">
      <div className="hd-grid">
        {/* INPUT — Excel */}
        <div className="hd-panel hd-xls ticked">
          <div className="hd-bar">
            <span className="hd-xls-ico">X</span>
            <span className="hd-fname">wire_list.xlsx</span>
            <span className="hd-cellref">A{Math.max(1, readRow + 2)}</span>
          </div>
          <div className="hd-collabels">
            <span className="hd-rownum"></span>
            {["A", "B", "C", "D", "E"].map((c) => <span key={c}>{c}</span>)}
          </div>
          <div className="hd-row hd-head">
            <span className="hd-rownum">1</span>
            <span>WIRE</span><span>FROM</span><span>TO</span><span>GA</span><span>SIGNAL</span>
          </div>
          {WIRE_ROWS.map((r, i) => (
            <div key={r.id} className={"hd-row" + (i <= readRow ? " lit" : "") + (i === readRow && phase === "reading" ? " active" : "")}>
              <span className="hd-rownum">{i + 2}</span>
              <span className="hd-mono">{r.id}</span>
              <span className="hd-mono">{r.from}</span>
              <span className="hd-mono">{r.to}</span>
              <span className="hd-mono">{r.ga}</span>
              <span className="hd-color"><i style={{ background: r.hex }}></i>{r.sig}</span>
            </div>
          ))}
          <div className="hd-row hd-ellipsis"><span className="hd-rownum">…</span><span className="hd-mono" style={{ gridColumn: "2 / 7", color: "#8b8d95" }}>+ 5 more circuits</span></div>
        </div>

        {/* CENTER */}
        <div className="hd-center">
          <div className={"hd-pipe" + (phase !== "idle" ? " on" : "")}></div>
          <div className="hd-chip">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 8h9M8 4l5 4-5 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square" /></svg>
          </div>
        </div>

        {/* OUTPUT — the real drawing, plotter-wiped in */}
        <div className="hd-panel hd-out ticked">
          <div className="hd-bar hd-bar-out">
            <span className={"hd-led " + phase}></span>
            <span className="hd-status">{st}</span>
            <span className="hd-sub">{stSub}</span>
          </div>
          <div className="hd-sheetwrap">
            <img
              className="hd-sheet"
              src="assets/tr-1001-001-crop.png"
              alt="Tractus output: TR-1001-001 wiring diagram, J1–J3 circuits"
              style={{
                clipPath: `inset(0 ${(1 - draw) * 100}% 0 0)`,
                opacity: draw > 0 ? 1 : 0,
              }}
            />
            {wiping && <div className="hd-plothead" style={{ left: `${draw * 100}%` }}></div>}
            {phase !== "done" && (
              <div className="hd-sheet-empty">
                <span className="mono">TR-1001-001 · SHEET 2 OF 4</span>
              </div>
            )}
            {phase === "generating" && (
              <div className="hd-progress">
                <div className="hd-progress-track"><div className="hd-progress-fill" style={{ width: progress + "%" }}></div></div>
                <span className="hd-clock">{mmss}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="hd-footer">
        <span className="hd-tag">{phase === "done" ? "ACTUAL OUTPUT · EDITABLE DRAW.IO · 32 SECONDS" : "LIVE GENERATION"}</span>
        <button className="hd-replay" onClick={() => { started.current = true; run(); }} disabled={phase !== "done" && phase !== "idle"}>
          <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M13 8a5 5 0 1 1-1.5-3.5M13 2v3h-3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square" /></svg>
          Replay
        </button>
      </div>

      <style>{`
        .hd { width: 100%; }
        .hd-grid { display: grid; grid-template-columns: 1fr 56px 1.18fr; align-items: stretch; gap: 0; }
        .hd-panel { position: relative; border: 1px solid var(--navy-line); }
        .ticked::before { top:-1px; left:-1px; border-width: 1.5px 0 0 1.5px; }
        .ticked::after { bottom:-1px; right:-1px; border-width: 0 1.5px 1.5px 0; }

        /* Excel panel — pinned light in both themes (it's a spreadsheet) */
        .hd-xls { background: #fff; color: #1a1b20; box-shadow: var(--panel-shadow); z-index: 2; }
        .hd-bar { display: flex; align-items: center; gap: 9px; padding: 9px 12px; border-bottom: 1px solid #e2e3e7; background: #f3f4f6; }
        .hd-xls-ico { width: 18px; height: 18px; display: grid; place-items: center; background: #1d6f42; color: #fff; font-family: var(--mono); font-weight: 600; font-size: 11px; border-radius: 2px; }
        .hd-fname { font-family: var(--mono); font-size: 12px; font-weight: 500; color: #2a2b31; }
        .hd-cellref { margin-left: auto; font-family: var(--mono); font-size: 11px; color: #8b8d95; border: 1px solid #e2e3e7; padding: 1px 7px; }
        .hd-collabels, .hd-row { display: grid; grid-template-columns: 26px 1.05fr .85fr .85fr .55fr 1.15fr; }
        .hd-collabels { background: #f3f4f6; border-bottom: 1px solid #e2e3e7; }
        .hd-collabels span { font-family: var(--mono); font-size: 10px; color: #8b8d95; text-align: center; padding: 3px 0; border-right: 1px solid #e2e3e7; }
        .hd-collabels span:last-child { border-right: 0; }
        .hd-rownum { background: #f3f4f6; color: #8b8d95; font-family: var(--mono); font-size: 10px; display: grid; place-items: center; border-right: 1px solid #e2e3e7; }
        .hd-row { border-bottom: 1px solid #eef0f3; transition: background .2s ease; }
        .hd-row > span:not(.hd-rownum) { padding: 8px 9px; font-size: 12px; border-right: 1px solid #eef0f3; display: flex; align-items: center; }
        .hd-mono { font-family: var(--mono); }
        .hd-head > span:not(.hd-rownum) { font-family: var(--mono); font-weight: 600; font-size: 10.5px; letter-spacing: .06em; color: #5d5f66; background: #fafbfc; }
        .hd-row.lit { background: #fff4f3; }
        .hd-row.active { background: #ffe3e0; box-shadow: inset 3px 0 0 var(--accent); }
        .hd-color { gap: 7px; font-family: var(--mono); font-size: 11px; color: #2a2b31; }
        .hd-color i { width: 11px; height: 11px; border: 1px solid rgba(0,0,0,.18); flex: none; }
        .hd-ellipsis > span { padding: 7px 9px; white-space: nowrap; }
        .hd-ellipsis { border-bottom: 0; }

        /* center */
        .hd-center { position: relative; display: grid; place-items: center; }
        .hd-pipe { position: absolute; top: 50%; left: 0; right: 0; height: 2px; transform: translateY(-50%); background: var(--line-strong); }
        .hd-pipe::after { content: ""; position: absolute; inset: 0; background: var(--accent); transform: scaleX(0); transform-origin: left; transition: transform .5s ease; }
        .hd-pipe.on::after { transform: scaleX(1); }
        .hd-chip { position: relative; z-index: 2; width: 38px; height: 38px; display: grid; place-items: center; background: var(--navy-900); border: 1px solid var(--accent); color: var(--accent); }

        /* output panel — the real document, pinned light */
        .hd-out { background: #fff; color: #1a1b20; box-shadow: var(--panel-shadow); display: flex; flex-direction: column; }
        .hd-bar-out { background: #f3f4f6; border-bottom: 1px solid #e2e3e7; }
        .hd-status { font-family: var(--mono); color: #2a2b31; font-weight: 600; letter-spacing: .1em; font-size: 11px; }
        .hd-sub { font-family: var(--mono); font-size: 10.5px; color: #8b8d95; margin-left: auto; white-space: nowrap; }
        .hd-led { width: 8px; height: 8px; border-radius: 50%; background: #c2c4cb; flex: none; }
        .hd-led.reading { background: #2b6fd6; animation: hdpulse 1s infinite; }
        .hd-led.generating { background: var(--accent); animation: hdpulse .7s infinite; }
        .hd-led.done { background: #1d9e5f; }
        @keyframes hdpulse { 0%,100%{opacity:1} 50%{opacity:.3} }

        .hd-sheetwrap { position: relative; flex: 1; min-height: 0; padding: 0; overflow: hidden; }
        .hd-sheetwrap::before { content: ""; display: block; padding-top: 30.11%; }
        .hd-sheet { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; display: block; }
        .hd-plothead { position: absolute; top: 4%; bottom: 4%; width: 2px; background: var(--accent); box-shadow: 0 0 10px rgba(255,65,54,.5); }
        .hd-sheet-empty { position: absolute; inset: 10px; border: 1px dashed #d7d9de; display: grid; place-items: center; }
        .hd-sheet-empty span { font-size: 10px; letter-spacing: .14em; color: #b4b6bd; }
        .hd-progress { position: absolute; left: 24px; right: 24px; bottom: 22px; display: flex; align-items: center; gap: 12px; }
        .hd-progress-track { flex: 1; height: 4px; background: #e7e8ec; overflow: hidden; }
        .hd-progress-fill { height: 100%; background: var(--accent); transition: width .12s linear; }
        .hd-clock { font-family: var(--mono); font-size: 13px; font-weight: 600; color: var(--accent); }

        .hd-footer { display: flex; align-items: center; justify-content: space-between; margin-top: 14px; padding: 0 2px; }
        .hd-tag { font-family: var(--mono); font-size: 10.5px; letter-spacing: .14em; color: var(--accent); white-space: nowrap; }
        .hd-replay { display: inline-flex; align-items: center; gap: 7px; background: transparent; border: 1px solid var(--line-strong); color: var(--ink-mut); font-family: var(--mono); font-size: 11px; padding: 6px 12px; border-radius: 2px; transition: all .15s ease; }
        .hd-replay:hover:not(:disabled) { border-color: var(--accent); color: var(--ink); }
        .hd-replay:disabled { opacity: .4; cursor: default; }

        @media (max-width: 920px) {
          .hd-grid { grid-template-columns: 1fr; gap: 0; }
          .hd-center { height: 54px; transform: rotate(90deg); }
        }
      `}</style>
    </div>
  );
}

window.HarnessDemo = HarnessDemo;
