/* eslint-disable */
// DriverModal — the per-driver "private war room" overlay.
// Now includes:
//   1. 強平倒數 livestrip row
//   2. Macro scrolling ribbon
//   3. 5 dashboard stats (REALIZED / UNREALIZED / AI CONFIDENCE / TRADES / STATUS)
//   4. Candlestick K-line chart with BB bands, MA line, axes, entry/exit markers
//   5. Trade-row trailing cyan icon

function WrDriverModal({ driver, liveDelta = 0, onClose }) {
  React.useEffect(() => {
    if (!driver) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [driver, onClose]);

  if (!driver) return null;
  const d = driver;
  const textOnBg = (d.color === "#FF6B9D" || d.color === "#5B8FFF" || d.color === "#B388FF") ? "#fff" : "#000";

  // Summary numbers derived from trade list
  const closed = d.trades.filter(t => t[4] === "win" || t[4] === "lose");
  const wins = closed.filter(t => t[4] === "win").length;
  const winRate = closed.length ? Math.round(wins / closed.length * 100) : 0;
  const inCount = d.trades.filter(t => t[4] === "open" || t[4] === "closed").length;
  const outCount = closed.length;
  const sumPnl = closed.reduce((s, t) => s + (parseInt(t[3], 10) || 0), 0);
  const totalTrades = d.trades.length;

  // Status pill at the right of the livestrip — driven by `side`.
  const stateInfo = {
    long:  { label: "多單持倉", cls: "wr-m-livestrip__state--green" },
    short: { label: "空單持倉", cls: "wr-m-livestrip__state--red"   },
    pit:   { label: "進站換胎", cls: ""                              },
    flat:  { label: "待命",     cls: ""                              },
  }[d.side];

  return (
    <div className="wr-modal" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="wr-modal__shell">

        {/* TOP */}
        <div className="wr-m-top">
          <div className="wr-m-top__info">
            <span className="wr-m-top__id" style={{ background: d.color, color: textOnBg }}>{d.code}</span>
            <div>
              <div className="wr-m-top__nm">{d.name}</div>
              <div className="wr-m-top__sub">▎ Driver № 0{d.no} · {d.strat} · est. {d.est} · 5m bar · TXFEAH7</div>
            </div>
          </div>
          <button className="wr-m-top__close" onClick={onClose}>CLOSE [ ESC ]</button>
        </div>

        {/* ROW 1 — date / latest / LIVE / bar count */}
        <div className="wr-m-row1">
          <input type="date" className="wr-m-date" defaultValue="2026-05-17"/>
          <button className="wr-m-latest">▸ 最新戰況</button>
          <span className="wr-m-live"><span className="dot"></span>LIVE</span>
          <span className="wr-m-bars">✓ <b>167</b> 根 K 線</span>
        </div>

        {/* SUMMARY */}
        <div className="wr-m-summary">
          <span className="wr-m-summary__l">本交易日 <b>{d.code}</b>：</span>
          <span className="wr-m-summary__it">進場 <b>{inCount}</b> 次</span>
          <span className="wr-m-summary__it">出場 <b>{outCount}</b> 次</span>
          <span className="wr-m-summary__it">損益 <b className={sumPnl >= 0 ? "g" : "r"}>{(sumPnl >= 0 ? "+" : "") + sumPnl} 點</b></span>
          <span className="wr-m-summary__it">勝率 <b>{winRate}%</b></span>
          <span style={{ fontSize: 10, color: "var(--nx-muted)", letterSpacing: ".14em", fontFamily: "var(--nx-font-mono)" }}>·est</span>
        </div>

        {/* LIVE BANNER — synced with the tile's amber row */}
        <LiveBanner driver={d} liveDelta={liveDelta}/>

        {/* LIVE STRIP — 即時參考價 / 淨部位 / 強平倒數 / state */}
        <div className="wr-m-livestrip">
          <span className="wr-m-livestrip__it">即時參考價: <b>{d.entry === "—" ? "—" : d.entry}</b></span>
          <span className="wr-m-livestrip__it">淨部位: <b>{d.side === "long" ? "net:+1" : d.side === "short" ? "net:−1" : "net:0"}</b></span>
          <span className="wr-m-livestrip__it">
            強平倒數: <b className="wr-m-livestrip__cd">08:05:21</b>
            <em>NIGHT_SESSION</em>
          </span>
          <span className={"wr-m-livestrip__state " + stateInfo.cls}>{stateInfo.label}</span>
        </div>

        {/* MACRO RIBBON */}
        <MacroRibbon/>

        {/* STATS — 5 dashboard cells */}
        <div className="wr-m-stats">
          <div className="wr-m-stats__c">
            <div className="l">REALIZED TODAY</div>
            <div className={"v " + (d.realized.startsWith("+") && d.realized !== "+0" ? "g" : "r")}>
              {d.realized === "+0" ? "BETA" : d.realized}
            </div>
          </div>
          <div className="wr-m-stats__c">
            <div className="l">UNREALIZED</div>
            <div className={"v " + (d.unreal === "—" ? "" : (d.unreal.startsWith("+") ? "g" : "r"))}>{d.unreal}</div>
          </div>
          <div className="wr-m-stats__c">
            <div className="l">AI CONFIDENCE</div>
            <div className={"v " + (d.conf > 60 ? "g" : d.conf > 40 ? "a" : "r")}>{d.conf}%</div>
          </div>
          <div className="wr-m-stats__c">
            <div className="l">TRADES TODAY</div>
            <div className="v">{totalTrades}</div>
          </div>
          <div className="wr-m-stats__c">
            <div className="l">STATUS</div>
            <div className={"v " + (d.side === "long" ? "g" : d.side === "short" ? "r" : d.side === "pit" ? "" : "")}>
              {stateInfo.label}
            </div>
          </div>
        </div>

        {/* GRID — chart | trades */}
        <div className="wr-m-grid">
          <div className="wr-m-col">
            <div className="wr-panel__head" style={{ padding: "11px 18px" }}>
              <span className="wr-panel__t" style={{ fontSize: 17 }}>5-min <em>K-line</em> · this driver's prints</span>
              <span className="wr-panel__meta">▸ MARKERS = ENTRIES / EXITS</span>
            </div>
            <div className="wr-chart-panel"><CandleChart driver={d}/></div>

            <div className="wr-m-ind-row">
              {[
                ["RSI · 14", "71.4", "r", 71, "Overbought · pullback bias"],
                ["ADX · 14", "18.2", "n", 36, "Range market · MR favored"],
                ["BB %B",    "0.87", "a", 87, "Near upper band"],
                ["ATR · 14", "38.4", "n", 54, "Normal vol envelope"],
              ].map(([lab, v, cls, w, note], i) => (
                <div className="wr-m-ind" key={i}>
                  <div className="l"><span>▎ {lab}</span><span>?</span></div>
                  <div className={"v " + cls}>{v}</div>
                  <div className="bar"><i style={{ width: w + "%" }}/></div>
                  <div className="note">▸ {note}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="wr-m-col">
            <div className="wr-panel__head" style={{ padding: "11px 18px" }}>
              <span className="wr-panel__t" style={{ fontSize: 17 }}><em>Today's</em> trades</span>
              <span className="wr-panel__meta">▸ REALIZED POINTS ONLY</span>
            </div>
            <div className="wr-trades-wrap" style={{ maxHeight: 900 }}>
              {d.trades.map((t, i) => <TradeRow key={i} d={d} t={t}/>)}
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}

/* ─── LIVE BANNER ───────────────────────────────────────────────── */

function LiveBanner({ driver, liveDelta }) {
  const d = driver;
  const base = window.basePnl(d);
  const live = base + liveDelta;
  const isBeta = d.realized === "+0" && d.unreal === "—";
  const cls = isBeta ? "b" : (live >= 0 ? "" : "r");
  const sign = live >= 0 ? "+" : "";
  const realCls = d.realized.startsWith("+") && d.realized !== "+0" ? "g" : (d.realized === "+0" ? "" : "r");
  const unrealCls = d.unreal === "—" ? "" : (d.unreal.startsWith("+") ? "g" : "r");
  return (
    <div className="wr-m-livebanner">
      <div className="wr-m-livebanner__l">
        <span className="wr-m-livebanner__lbl">▎ 即時損益 · {d.code} live PnL · syncs with paddock</span>
        <span className="wr-m-livebanner__sub">
          realized <b className={realCls}>{d.realized === "+0" ? "BETA" : d.realized + " pt"}</b>
          · unrealized <b className={unrealCls}>{d.unreal === "—" ? "—" : d.unreal + " pt"}</b>
          · jitter <b>{(liveDelta >= 0 ? "+" : "") + liveDelta.toFixed(1)} pt</b>
        </span>
      </div>
      <div className={"wr-m-livebanner__v " + cls}>
        {isBeta ? "BETA" : sign + Math.round(live)}{!isBeta && <sup>pt</sup>}
      </div>
    </div>
  );
}

/* ─── MACRO RIBBON ─────────────────────────────────────────────── */

function MacroRibbon() {
  const items = [
    { lab: "銅",      v: "$4.22",   chg: "+0.20%", dir: "g" },
    { lab: "USDTWD",  v: "31.83",   chg: "−0.17%", dir: "r" },
    { lab: "BTC",     v: "$68,382", chg: "−1.16%", dir: "r" },
    { lab: "SPX",     v: "5,835",   chg: "+0.27%", dir: "g" },
    { lab: "VIX",     v: "14.84",   chg: "+1.26%", dir: "g" },
    { lab: "WTI 油",  v: "$78.2",   chg: "−0.91%", dir: "r" },
    { lab: "金",      v: "$2,643",  chg: "+0.25%", dir: "g" },
    { lab: "10Y UST", v: "4.28%",   chg: "−0.04%", dir: "r" },
    { lab: "DXY",     v: "106.34",  chg: "−0.18%", dir: "r" },
    { lab: "NDX",     v: "21,645",  chg: "+0.42%", dir: "g" },
  ];
  const seq = [...items, ...items];
  return (
    <div className="wr-m-macro">
      <span className="wr-m-macro__pin">MACRO</span>
      <div className="wr-m-macro__scroll">
        <div className="wr-m-macro__track">
          {seq.map((it, i) => (
            <span className="wr-m-macro__it" key={i}>
              <span className="lab">{it.lab}</span>
              <span className="v">{it.v}</span>
              <span className={"chg " + it.dir}>{it.dir === "g" ? "▲" : "▼"} {it.chg}</span>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ─── CANDLESTICK CHART ─────────────────────────────────────────── */

function CandleChart({ driver }) {
  // Synthetic OHLC series spanning ~50 5m bars. Deterministic per driver.
  const N = 50;
  const candles = React.useMemo(() => generateOHLC(driver.code, N), [driver.code]);
  const W = 780, H = 360;
  const padL = 0, padR = 56, padT = 20, padB = 26;
  const plotW = W - padL - padR;
  const plotH = H - padT - padB;

  // Y range from min low / max high w/ small breathing.
  const lows  = candles.map(c => c.l);
  const highs = candles.map(c => c.h);
  const yMin = Math.min(...lows) - 10;
  const yMax = Math.max(...highs) + 10;
  const yScale = (p) => padT + (1 - (p - yMin) / (yMax - yMin)) * plotH;
  const xStep = plotW / N;
  const cw = Math.max(3, xStep * 0.62);

  // Bollinger bands (20-period, 2σ) and SMA(20) on closes.
  const closes = candles.map(c => c.c);
  const sma20 = movingAvg(closes, 20);
  const bbU = closes.map((_, i) => {
    if (i < 19) return null;
    const slice = closes.slice(i - 19, i + 1);
    const mean = slice.reduce((s, v) => s + v) / 20;
    const sd = Math.sqrt(slice.reduce((s, v) => s + (v - mean) ** 2, 0) / 20);
    return mean + 2 * sd;
  });
  const bbL = closes.map((_, i) => {
    if (i < 19) return null;
    const slice = closes.slice(i - 19, i + 1);
    const mean = slice.reduce((s, v) => s + v) / 20;
    const sd = Math.sqrt(slice.reduce((s, v) => s + (v - mean) ** 2, 0) / 20);
    return mean - 2 * sd;
  });

  // Y-axis grid ticks
  const ticks = 4;
  const tickVals = Array.from({ length: ticks + 1 }, (_, i) => yMin + ((yMax - yMin) * (ticks - i) / ticks));

  // X-axis time labels at fixed bar indices
  const xLabels = [
    { i: 0,  label: "08:45" },
    { i: 12, label: "10:00" },
    { i: 22, label: "11:15" },
    { i: 32, label: "12:30" },
    { i: 42, label: "13:45" },
    { i: 49, label: "NIGHT" },
  ];

  // Trade markers — pull entry / exit prices from the driver's trade list.
  // Take the first few "win"/"lose"/"open" rows from the chronological tail.
  const markers = pickMarkers(driver.trades, candles, N);

  const polyPath = (arr) => {
    let s = "";
    arr.forEach((v, i) => {
      if (v == null) return;
      const x = padL + i * xStep + xStep / 2;
      const y = yScale(v);
      s += (s ? " L" : "M") + x.toFixed(1) + "," + y.toFixed(1);
    });
    return s;
  };

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {/* grid */}
      <g className="grid">
        {tickVals.map((v, i) => {
          const y = yScale(v);
          return <line key={i} x1={padL} y1={y} x2={padL + plotW} y2={y}/>;
        })}
      </g>

      {/* BB bands */}
      <path className="bb" d={polyPath(bbU)}/>
      <path className="bb" d={polyPath(bbL)}/>

      {/* MA */}
      <path className="ma" d={polyPath(sma20)} stroke={driver.color === "#A8E063" ? "#A8E063" : "var(--nx-green-soft)"}/>

      {/* candles */}
      {candles.map((c, i) => {
        const x = padL + i * xStep + xStep / 2;
        const isUp = c.c >= c.o;
        const fill = isUp ? "var(--nx-green)" : "var(--nx-red)";
        const yHi = yScale(c.h), yLo = yScale(c.l);
        const yOp = yScale(c.o), yCl = yScale(c.c);
        const yT = Math.min(yOp, yCl), yB = Math.max(yOp, yCl);
        return (
          <g key={i}>
            <line x1={x} y1={yHi} x2={x} y2={yLo} stroke={fill} strokeWidth="1"/>
            <rect x={x - cw / 2} y={yT} width={cw} height={Math.max(1, yB - yT)} fill={fill}/>
          </g>
        );
      })}

      {/* markers — dashed vertical line + price box label */}
      {markers.map((m, i) => {
        const x = padL + m.barIdx * xStep + xStep / 2;
        const y = yScale(m.price);
        const cls = m.kind === "win" ? "g" : m.kind === "lose" ? "r" : m.kind === "open" ? "c" : "";
        const stroke = m.kind === "win" ? "var(--nx-green)" : m.kind === "lose" ? "var(--nx-red)" : "var(--nx-cyan)";
        return (
          <g key={i}>
            <line className={"marker-line " + cls} x1={x} y1={padT} x2={x} y2={padT + plotH}/>
            <g className="marker-lbl">
              <rect className="bg" x={x + 6} y={y - 14} width={m.label.length * 7 + 14} height={20} fill="var(--nx-bg)"/>
              <rect className="box" x={x + 6} y={y - 14} width={m.label.length * 7 + 14} height={20} stroke={stroke}/>
              <text x={x + 13} y={y + 1} fill={stroke}>{m.label}</text>
            </g>
          </g>
        );
      })}

      {/* y-axis labels (right side) */}
      <g className="axis">
        {tickVals.map((v, i) => (
          <text key={i} x={padL + plotW + 6} y={yScale(v) + 4} textAnchor="start">{Math.round(v).toLocaleString()}</text>
        ))}
      </g>

      {/* x-axis labels (bottom) */}
      <g className="axis">
        {xLabels.map((xl, i) => {
          const x = padL + xl.i * xStep + xStep / 2;
          return <text key={i} x={x} y={padT + plotH + 18} textAnchor="middle">{xl.label}</text>;
        })}
      </g>
    </svg>
  );
}

// --- helpers --------------------------------------------------------

function hashSeed(s) {
  let h = 2166136261;
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = (h * 16777619) >>> 0; }
  return () => { h = (h * 16807) % 2147483647; return h / 2147483647; };
}

function generateOHLC(seedStr, N) {
  const rand = hashSeed(seedStr);
  const out = [];
  let price = 22300;
  for (let i = 0; i < N; i++) {
    const drift = (rand() - 0.48) * 18;
    const o = price;
    const c = price + drift;
    const wickH = Math.abs(rand() * 12);
    const wickL = Math.abs(rand() * 12);
    const h = Math.max(o, c) + wickH;
    const l = Math.min(o, c) - wickL;
    out.push({ o, h, l, c });
    price = c;
  }
  return out;
}

function movingAvg(arr, w) {
  const out = arr.map((_, i) => {
    if (i < w - 1) return null;
    const slice = arr.slice(i - w + 1, i + 1);
    return slice.reduce((s, v) => s + v, 0) / w;
  });
  return out;
}

// Pick a handful of trade rows that have prices and translate them into
// chart markers. We don't try to align to real time — just spread them
// across recent bars so the chart looks busy.
function pickMarkers(trades, candles, N) {
  const candidates = trades.filter(t => /\d/.test(String(t[2])));
  const sliced = candidates.slice(0, 4);
  return sliced.map((t, i) => {
    const barIdx = Math.round(N * 0.25 + i * (N * 0.6 / Math.max(1, sliced.length - 1)));
    const kind = t[4]; // open / win / lose / closed / watch
    const verb = t[1];
    const label =
      kind === "open"  ? (verb.includes("空") ? "SHORT" : "LONG") + " +1" :
      kind === "win"   ? "EXIT " + t[3] :
      kind === "lose"  ? "STOP " + t[3] :
                         "▸ HOLD";
    const last = candles[barIdx] || candles[candles.length - 1];
    return { barIdx, price: last.c, kind, label };
  });
}

window.WrDriverModal = WrDriverModal;
