/* Page 4 — Backtest Lab */
const { Icon, fmt, sign } = window.UI;

const BacktestPage = () => {
  const [execMode, setExecMode] = React.useState("same-close");
  const [direction, setDirection] = React.useState("long");
  const [pyramiding, setPyramiding] = React.useState(false);
  const [reverse, setReverse] = React.useState(true);
  const [running, setRunning] = React.useState(false);

  /* Equity curve points */
  const equity = React.useMemo(() => {
    let v = 1_000_000;
    const out = [v];
    let s = 7;
    for (let i = 0; i < 120; i++) {
      s = (s * 9301 + 49297) % 233280;
      const r = (s / 233280 - 0.42) * 0.025;
      v *= (1 + r);
      out.push(v);
    }
    return out;
  }, []);
  const drawdown = React.useMemo(() => {
    let peak = equity[0];
    return equity.map(v => { peak = Math.max(peak, v); return (v - peak) / peak * 100; });
  }, [equity]);

  const trades = [
    { entry: "2025-10-14", exit: "2025-10-28", sym: "2330.TW", side: "Long", reason: "盤整突破", confirmed: "10-15 09:05", anchor: "10-14", ep: 845, xp: 892, pnl: 47, pct: 5.56, hd: 14 },
    { entry: "2025-11-04", exit: "2025-11-12", sym: "2330.TW", side: "Long", reason: "回後買上漲", confirmed: "11-05 09:05", anchor: "11-04", ep: 902, xp: 938, pnl: 36, pct: 3.99, hd: 8 },
    { entry: "2025-12-08", exit: "2025-12-16", sym: "2330.TW", side: "Long", reason: "高勝率紅 K", confirmed: "12-09 09:05", anchor: "12-08", ep: 945, xp: 922, pnl: -23, pct: -2.43, hd: 8 },
    { entry: "2026-01-15", exit: "2026-01-29", sym: "2330.TW", side: "Long", reason: "盤整突破", confirmed: "01-16 09:05", anchor: "01-15", ep: 928, xp: 974, pnl: 46, pct: 4.96, hd: 14 },
    { entry: "2026-02-19", exit: "2026-03-04", sym: "2330.TW", side: "Short", reason: "盤整跌破", confirmed: "02-20 09:05", anchor: "02-19", ep: 982, xp: 944, pnl: 38, pct: 3.87, hd: 13 },
    { entry: "2026-03-11", exit: "2026-03-18", sym: "2330.TW", side: "Long", reason: "回後買上漲", confirmed: "03-12 09:05", anchor: "03-11", ep: 952, xp: 968, pnl: 16, pct: 1.68, hd: 7 },
    { entry: "2026-04-08", exit: "2026-04-22", sym: "2330.TW", side: "Long", reason: "高勝率紅 K", confirmed: "04-09 09:05", anchor: "04-08", ep: 958, xp: 1005, pnl: 47, pct: 4.91, hd: 14 },
  ];

  const metrics = [
    { label: "總報酬", val: "+34.82%", tone: "up", sub: "對比買進持有 +18.4%" },
    { label: "年化報酬", val: "+27.1%", tone: "up", sub: "CAGR" },
    { label: "最大回撤", val: "-12.4%", tone: "warn", sub: "2025-12-09" },
    { label: "夏普值", val: "1.82", tone: "", sub: "無風險利率 1.5%" },
    { label: "勝率", val: "71.4%", tone: "up", sub: "5 勝 / 2 負" },
    { label: "獲利因子", val: "3.82", tone: "up", sub: "總獲利 / 總損失" },
    { label: "交易次數", val: "7", tone: "", sub: "多 6 · 空 1" },
    { label: "平均持有", val: "11 天", tone: "", sub: "中位數 12 天" },
  ];

  return (
    <div className="page backtest-page" data-color-mode="tw">
      {/* Strategy config */}
      <section className="surface bt-config">
        <header className="section-head">
          <div className="section-head-l">
            <h2 className="section-title">策略</h2>
            <input className="input" defaultValue="KC MA5 結構 v17 — 台股核心" style={{minWidth:280}}/>
          </div>
          <div className="section-head-r">
            <button className="btn ghost">儲存預設</button>
            <button className="btn primary" onClick={() => { setRunning(true); setTimeout(() => setRunning(false), 1200); }}>
              <Icon name="play" size={13}/> 執行回測
            </button>
          </div>
        </header>

        <div className="bt-config-grid">
          <div className="form-row col">
            <label className="form-label">股票</label>
            <div className="chip-row">
              <span className="pill accent">2330.TW</span>
              <span className="pill accent">2454.TW</span>
              <span className="pill accent">2603.TW</span>
              <button className="pill" style={{cursor:"pointer"}}><Icon name="plus" size={10}/></button>
            </div>
          </div>
          <div className="form-row col">
            <label className="form-label">時間週期</label>
            <div className="seg" style={{height:32}}><button className="active">1D</button><button>1W</button><button>1M</button></div>
          </div>
          <div className="form-row col">
            <label className="form-label">日期區間</label>
            <div style={{display:"flex", gap:6}}>
              <input className="input" defaultValue="2025-05-07" style={{flex:1}}/>
              <input className="input" defaultValue="2026-05-07" style={{flex:1}}/>
            </div>
          </div>
          <div className="form-row col">
            <label className="form-label">初始資金</label>
            <input className="input mono" defaultValue="1,000,000 TWD"/>
          </div>
          <div className="form-row col">
            <label className="form-label">部位大小</label>
            <select className="select"><option>固定金額 200,000</option><option>固定股數</option><option>權益 % (Kelly)</option></select>
          </div>
          <div className="form-row col">
            <label className="form-label">方向</label>
            <div className="seg" style={{height:32}}>
              <button className={direction === "long" ? "active" : ""} onClick={() => setDirection("long")}>只多</button>
              <button className={direction === "short" ? "active" : ""} onClick={() => setDirection("short")}>只空</button>
              <button className={direction === "ls" ? "active" : ""} onClick={() => setDirection("ls")}>多空</button>
            </div>
          </div>
          <div className="form-row col">
            <label className="form-label">
              執行模式
              {execMode === "same-close" && <span className="pill accent" style={{marginLeft:6}}>TradingView 視覺</span>}
            </label>
            <div className="seg" style={{height:32}}>
              <button className={execMode === "next-open" ? "active" : ""} onClick={() => setExecMode("next-open")}>次棒開盤</button>
              <button className={execMode === "same-close" ? "active" : ""} onClick={() => setExecMode("same-close")}>同棒收盤</button>
            </div>
          </div>
          <div className="form-row col">
            <label className="form-label">手續費 / 證交稅 / 滑點</label>
            <div style={{display:"flex", gap:6}}>
              <input className="input mono" defaultValue="0.1425%"/>
              <input className="input mono" defaultValue="0.30%"/>
              <input className="input mono" defaultValue="0.05%"/>
            </div>
          </div>
        </div>

        {/* Same bar close vs Next bar open compare */}
        <div className="exec-compare">
          <div className="sec-title" style={{marginBottom:6}}>執行模式對照</div>
          <div className="exec-grid">
            <div className={"exec-card " + (execMode === "same-close" ? "active" : "")}>
              <div className="exec-head">
                <span className="pill accent">同棒收盤</span>
                <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>TradingView 風格</span>
              </div>
              <div className="exec-vis">
                <ExecBars mode="same-close"/>
              </div>
              <div className="exec-stat">
                <div><span className="dim">進場點</span><span className="mono">訊號 K 棒 收盤</span></div>
                <div><span className="dim">滑點</span><span className="mono">0.05%</span></div>
                <div><span className="dim">總報酬</span><span className="up num">+34.82%</span></div>
              </div>
            </div>
            <div className={"exec-card " + (execMode === "next-open" ? "active" : "")}>
              <div className="exec-head">
                <span className="pill">次棒開盤</span>
                <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>貼近實際成交</span>
              </div>
              <div className="exec-vis">
                <ExecBars mode="next-open"/>
              </div>
              <div className="exec-stat">
                <div><span className="dim">進場點</span><span className="mono">次一棒 開盤</span></div>
                <div><span className="dim">滑點</span><span className="mono">0.18%</span></div>
                <div><span className="dim">總報酬</span><span className="num up">+28.15%</span></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Strategy conditions */}
      <section className="surface bt-conditions">
        <header className="section-head">
          <div className="section-head-l">
            <h2 className="section-title">策略條件</h2>
            <select className="select" defaultValue="KC v17"><option>KC MA5 結構 v17</option><option>自訂</option></select>
          </div>
          <div className="section-head-r" style={{gap:14}}>
            <label className="chk-inline"><div className={"switch " + (pyramiding ? "on" : "")} onClick={() => setPyramiding(!pyramiding)}/> 加碼</label>
            <label className="chk-inline"><div className={"switch " + (reverse ? "on" : "")} onClick={() => setReverse(!reverse)}/> 反向訊號轉向</label>
          </div>
        </header>
        <div className="cond-cols">
          <div>
            <div className="sec-title">進場</div>
            <div className="cond-list">
              <div className="cond-pill up">KC 多 · 盤整突破</div>
              <div className="cond-pill up">KC 多 · 回後買上漲</div>
              <div className="cond-pill up">KC 多 · 高勝率紅 K</div>
            </div>
          </div>
          <div>
            <div className="sec-title">出場</div>
            <div className="cond-list">
              <div className="cond-pill down">KC 多單出場 · 跌破 5MA</div>
              <div className="cond-pill down">KC 多單出場 · 跌破前低</div>
              <div className="cond-pill down">KC 多單出場 · 頭頭低</div>
            </div>
          </div>
          <div>
            <div className="sec-title">停損 / 停利</div>
            <div className="cond-list">
              <div className="cond-pill warn">停損 · -3% 或跌破 MA20</div>
              <div className="cond-pill success">停利 · KC 多單出場</div>
            </div>
          </div>
        </div>
      </section>

      {/* Metrics */}
      <section className="bt-metrics">
        {metrics.map((m, i) => (
          <div key={i} className="surface metric-card">
            <div className="dim sec-title">{m.label}</div>
            <div className={"metric-val num " + (m.tone || "")}>{m.val}</div>
            <div className="dim mono" style={{fontSize:"var(--fs-xs)"}}>{m.sub}</div>
          </div>
        ))}
      </section>

      {/* Charts row */}
      <section className="bt-charts">
        <div className="surface bt-chart">
          <header className="section-head"><h3 className="section-title">權益曲線</h3>
            <span className="pill success dot">+34.82%</span>
          </header>
          <EquityChart data={equity} height={200}/>
        </div>
        <div className="surface bt-chart">
          <header className="section-head"><h3 className="section-title">回撤</h3>
            <span className="pill warn">最大 -12.4%</span>
          </header>
          <DrawdownChart data={drawdown} height={200}/>
        </div>
      </section>

      {/* Trades */}
      <section className="surface bt-trades">
        <header className="section-head">
          <h3 className="section-title">交易明細</h3>
          <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>{trades.length} 筆 · 同棒收盤</span>
        </header>
        <div className="watchlist-scroll">
        <table>
          <thead>
            <tr>
              <th>進場日</th><th>出場日</th><th>代號</th><th>方向</th>
              <th>訊號原因</th><th>確認時間</th><th>圖上標記</th>
              <th style={{textAlign:"right"}}>進價</th><th style={{textAlign:"right"}}>出價</th>
              <th style={{textAlign:"right"}}>損益</th><th style={{textAlign:"right"}}>報酬率</th><th style={{textAlign:"right"}}>天數</th>
            </tr>
          </thead>
          <tbody>
            {trades.map((t, i) => (
              <tr key={i}>
                <td className="mono dim">{t.entry}</td>
                <td className="mono dim">{t.exit}</td>
                <td className="mono" style={{fontWeight:600}}>{t.sym}</td>
                <td>
                  <span className={"pill " + (t.side === "Long" ? "up" : "down")}>
                    <Icon name={t.side === "Long" ? "trending-up" : "trending-down"} size={11}/> {t.side === "Long" ? "多" : "空"}
                  </span>
                </td>
                <td>{t.reason}</td>
                <td className="mono dim" style={{fontSize:"var(--fs-xs)"}}>{t.confirmed}</td>
                <td className="mono dim" style={{fontSize:"var(--fs-xs)"}}>{t.anchor}</td>
                <td className="num num-r">{fmt(t.ep)}</td>
                <td className="num num-r">{fmt(t.xp)}</td>
                <td className={"num num-r " + (t.pnl >= 0 ? "up" : "down")}>{t.pnl >= 0 ? "+" : ""}{fmt(t.pnl)}</td>
                <td className={"num num-r " + (t.pct >= 0 ? "up" : "down")}>{t.pct >= 0 ? "+" : ""}{fmt(t.pct, 2)}%</td>
                <td className="num num-r dim">{t.hd}</td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </section>

      {running && (
        <div className="bt-running">
          <div className="surface running-card">
            <div className="spinner"/>
            <div>
              <div style={{fontWeight:600}}>回測中...</div>
              <div className="dim mono" style={{fontSize:"var(--fs-xs)"}}>3 檔股票 · 252 根 K 棒 · 同棒收盤</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const ExecBars = ({ mode }) => {
  const w = 240, h = 80;
  const bars = [
    { o: 30, c: 50, h: 18, l: 60, up: true },
    { o: 50, c: 65, h: 12, l: 70, up: true },
    { o: 65, c: 58, h: 50, l: 72, up: false, signal: true },
    { o: 58, c: 62, h: 50, l: 65, up: true },
    { o: 62, c: 70, h: 55, l: 70, up: true },
  ];
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`}>
      {bars.map((b, i) => {
        const x = 20 + i * 42;
        const isSig = b.signal;
        return (
          <g key={i}>
            <line x1={x+10} x2={x+10} y1={b.h} y2={b.l} stroke={b.up ? "var(--c-up)" : "var(--c-down)"} strokeWidth="1"/>
            <rect x={x+4} y={Math.min(b.o, b.c)} width="12" height={Math.abs(b.c - b.o)}
              fill={b.up ? "var(--c-up)" : "var(--c-down)"}
              stroke={isSig ? "var(--accent)" : "transparent"} strokeWidth="1.5"/>
            {isSig && <text x={x+10} y="14" fontSize="9" textAnchor="middle" fill="var(--accent)" fontWeight="600">訊號</text>}
            {isSig && mode === "same-close" && (
              <g>
                <circle cx={x+10} cy={b.c} r="3" fill="var(--accent)"/>
                <text x={x+10} y={h-3} fontSize="8" textAnchor="middle" fill="var(--accent)">進場</text>
              </g>
            )}
            {isSig && mode === "next-open" && (
              <g>
                <circle cx={x+42+10} cy={bars[i+1].o} r="3" fill="var(--accent)"/>
                <text x={x+42+10} y={h-3} fontSize="8" textAnchor="middle" fill="var(--accent)">進場</text>
              </g>
            )}
          </g>
        );
      })}
    </svg>
  );
};

const EquityChart = ({ data, height = 180 }) => {
  const wRef = React.useRef(null);
  const [w, setW] = React.useState(400);
  React.useEffect(() => {
    const ro = new ResizeObserver(() => setW(wRef.current.clientWidth));
    ro.observe(wRef.current); setW(wRef.current.clientWidth);
    return () => ro.disconnect();
  }, []);
  const min = Math.min(...data), max = Math.max(...data);
  const pts = data.map((v, i) => `${(i / (data.length-1) * (w - 20) + 10).toFixed(1)},${((1 - (v-min)/(max-min)) * (height - 30) + 15).toFixed(1)}`).join(" ");
  const fill = `M 10,${height-15} L ${pts.split(" ").join(" L ")} L ${(w-10).toFixed(1)},${height-15} Z`;
  return (
    <div ref={wRef} style={{width:"100%"}}>
      <svg width={w} height={height}>
        <path d={fill} fill="var(--accent-soft)"/>
        <polyline points={pts} fill="none" stroke="var(--accent)" strokeWidth="1.6"/>
        <line x1="10" x2={w-10} y1={height-15} y2={height-15} stroke="var(--border)" strokeDasharray="2 3"/>
      </svg>
    </div>
  );
};

const DrawdownChart = ({ data, height = 180 }) => {
  const wRef = React.useRef(null);
  const [w, setW] = React.useState(400);
  React.useEffect(() => {
    const ro = new ResizeObserver(() => setW(wRef.current.clientWidth));
    ro.observe(wRef.current); setW(wRef.current.clientWidth);
    return () => ro.disconnect();
  }, []);
  const min = Math.min(...data);
  const pts = data.map((v, i) => `${(i / (data.length-1) * (w - 20) + 10).toFixed(1)},${((v / min) * (height - 30) + 15).toFixed(1)}`).join(" ");
  const fill = `M 10,15 L ${pts.split(" ").join(" L ")} L ${(w-10).toFixed(1)},15 Z`;
  return (
    <div ref={wRef} style={{width:"100%"}}>
      <svg width={w} height={height}>
        <path d={fill} fill="rgba(248,113,113,0.15)"/>
        <polyline points={pts} fill="none" stroke="var(--danger)" strokeWidth="1.4"/>
        <line x1="10" x2={w-10} y1="15" y2="15" stroke="var(--border)" strokeDasharray="2 3"/>
      </svg>
    </div>
  );
};

window.BacktestPage = BacktestPage;
