/* 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);

  /* 回測引擎尚未實作。等接上之後再填 equity / drawdown / trades / metrics */
  const equity = [];
  const drawdown = [];
  const trades = [];

  const metrics = [
    { label: "總報酬", val: "—", tone: "", sub: "對比買進持有" },
    { label: "年化報酬", val: "—", tone: "", sub: "CAGR" },
    { label: "最大回撤", val: "—", tone: "", sub: "" },
    { label: "夏普值", val: "—", tone: "", sub: "無風險利率 1.5%" },
    { label: "勝率", val: "—", tone: "", sub: "" },
    { label: "獲利因子", val: "—", tone: "", sub: "總獲利 / 總損失" },
    { label: "交易次數", val: "—", tone: "", sub: "" },
    { label: "平均持有", val: "—", tone: "", sub: "" },
  ];

  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={() => alert("回測引擎尚未實作，敬請期待。")}>
              <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">較低</span></div>
                <div><span className="dim">特性</span><span className="mono">回測樂觀</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">較高</span></div>
                <div><span className="dim">特性</span><span className="mono">真實可執行</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></header>
          {equity.length > 0
            ? <EquityChart data={equity} height={200}/>
            : <div className="bt-empty">尚未執行回測</div>}
        </div>
        <div className="surface bt-chart">
          <header className="section-head"><h3 className="section-title">回撤</h3></header>
          {drawdown.length > 0
            ? <DrawdownChart data={drawdown} height={200}/>
            : <div className="bt-empty">尚未執行回測</div>}
        </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>
        {trades.length > 0 ? (
          <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>
        ) : (
          <div className="bt-empty" style={{padding:"32px 16px"}}>尚未執行回測</div>
        )}
      </section>
    </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%" height="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="xMidYMid meet" style={{display:"block"}}>
      {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;
