// Gauntlet "Method Deep-Dive + Decision Inspector" — the hero analysis view.
// Two modes:
//   "single" — pick any finalist (default winner) and analyze HOW it produced its result:
//              robustness (train vs OOS), parameter sensitivity, equity+drawdown, monthly
//              returns, PnL attribution, per-trade decision rationale.
//   "all"    — every finalist's buy/sell decisions in ONE table (strategy column + filters);
//              click any row -> the same decision drawer.
// Read-only; all data comes from the already-loaded gauntlet artifact.
// Helpers are defined INSIDE the component (function scope) to avoid redeclaring the
// top-level gz* names from gauntlet-tab.jsx (no build step -> top-level redeclare = SyntaxError).

function GauntletAnalysis({ data, isMobile }) {
  const { useState, useMemo } = React;
  const {
    ResponsiveContainer, ComposedChart, AreaChart, Area, BarChart, Bar, Line, Scatter,
    XAxis, YAxis, Tooltip, ReferenceLine, CartesianGrid, Cell,
  } = Recharts;

  if (!data || !Array.isArray(data.bakeoff) || !data.bakeoff.length) return null;

  // ---- pure helpers (function-scoped, conflict-free) ----
  const PAL = ["#f59e0b", "#22c55e", "#627eea", "#9945ff", "#ef4444", "#22d3ee", "#e879f9", "#84cc16", "#fb923c", "#94a3b8"];
  function color(i) { return PAL[i % PAL.length]; }
  function num(n, d) { if (n == null || isNaN(n)) return "—"; return (+n).toFixed(d == null ? 2 : d); }
  function DS(arr, n) { if (!Array.isArray(arr) || arr.length <= n) return arr || []; var st = Math.ceil(arr.length / n); var o = []; for (var i = 0; i < arr.length; i += st) o.push(arr[i]); if (o[o.length - 1] !== arr[arr.length - 1]) o.push(arr[arr.length - 1]); return o; }
  function ddSeries(curve) { var peak = -Infinity; return (curve || []).map(function (p) { if (p.value > peak) peak = p.value; var dd = peak > 0 ? (p.value - peak) / peak * 100 : 0; return { date: p.date, dd: +dd.toFixed(2) }; }); }
  function tradeStats(trades) {
    var sells = (trades || []).filter(function (t) { return t.side === "sell"; });
    var wins = sells.filter(function (t) { return (t.pnl || 0) > 0; });
    var losses = sells.filter(function (t) { return (t.pnl || 0) < 0; });
    var sum = function (a) { return a.reduce(function (s, t) { return s + (t.pnl || 0); }, 0); };
    var grossW = sum(wins), grossL = Math.abs(sum(losses));
    var best = sells.reduce(function (mx, t) { return (t.pnl || 0) > (mx ? mx.pnl : -Infinity) ? t : mx; }, null);
    var worst = sells.reduce(function (mn, t) { return (t.pnl || 0) < (mn ? mn.pnl : Infinity) ? t : mn; }, null);
    return { closes: sells.length, winRate: sells.length ? wins.length / sells.length * 100 : 0, avgWin: wins.length ? grossW / wins.length : 0, avgLoss: losses.length ? -grossL / losses.length : 0, best: best, worst: worst, pnls: sells.map(function (t) { return t.pnl || 0; }) };
  }
  function histogram(vals, bins) {
    if (!vals || !vals.length) return [];
    var lo = Math.min.apply(null, vals), hi = Math.max.apply(null, vals);
    if (lo === hi) return [{ label: num(lo, 0), count: vals.length, mid: lo }];
    var w = (hi - lo) / bins, b = [];
    for (var i = 0; i < bins; i++) { var a = lo + i * w; b.push({ mid: a + w / 2, count: 0 }); }
    vals.forEach(function (v) { var idx = Math.min(bins - 1, Math.floor((v - lo) / w)); b[idx].count++; });
    return b.map(function (x) { return { label: num(x.mid, 0), mid: x.mid, count: x.count }; });
  }
  function monthly(curve) {
    var bm = {}; (curve || []).forEach(function (p) { var k = (p.date || "").slice(0, 7); if (!k) return; if (!bm[k]) bm[k] = { first: p.value, last: p.value }; bm[k].last = p.value; });
    var years = {}; Object.keys(bm).sort().forEach(function (k) { var y = k.slice(0, 4), mo = parseInt(k.slice(5, 7), 10) - 1; var o = bm[k]; if (!years[y]) years[y] = {}; years[y][mo] = o.first > 0 ? (o.last - o.first) / o.first * 100 : 0; });
    return years;
  }
  function heat(v) { if (v == null) return "rgba(255,255,255,0.03)"; var t = Math.max(-1, Math.min(1, v / 20)); return t >= 0 ? "rgba(34,197,94," + (0.15 + t * 0.7).toFixed(2) + ")" : "rgba(239,68,68," + (0.15 + (-t) * 0.7).toFixed(2) + ")"; }
  function comboIndexOf(runId) { var p = String(runId || "").split("#"); return p.length > 1 ? parseInt(p[1], 10) : null; }
  function optResultFor(fin) {
    var s = (data.optimizationSummaries || []).find(function (x) { return x.strategyId === fin.strategyId; });
    if (!s) return { summary: null, result: null };
    var ci = comboIndexOf(fin.runId);
    return { summary: s, result: (ci != null ? (s.results || []).find(function (x) { return x.comboIndex === ci; }) : null) || (s.results || [])[0] || null };
  }
  function decisionOf(trade) {
    var mt = trade.meta || {};
    var rich = Array.isArray(mt.buyReasons) || Array.isArray(mt.sellReasons) || mt.regime;
    if (rich) return { kind: "rich", reason: mt.reason || trade.reason, reasons: trade.side === "sell" ? (mt.sellReasons || []) : (mt.buyReasons || []), blocked: trade.side === "sell" ? (mt.sellBlockedReasons || []) : (mt.buyBlockedReasons || []), regime: mt.regime, buyScore: mt.buyScore, sellScore: mt.sellScore, buyThreshold: mt.buyThreshold, sellThreshold: mt.sellThreshold, riskSell: mt.riskSellTriggered, holdingBars: mt.holdingBars, pnlPct: mt.pnlPct };
    var ind = {}; Object.keys(mt).forEach(function (k) { if (typeof mt[k] === "number") ind[k] = mt[k]; });
    return { kind: "simple", reason: trade.reason, indicators: ind, dmaState: mt.dmaState || null };
  }

  // ---- state ----
  var savedWinnerId = data.winner ? (data.winner.runId || data.winner.strategyId) : null;
  const [mode, setMode] = useState("single");          // single | all
  const [sel, setSel] = useState(savedWinnerId || (data.bakeoff[0].runId || data.bakeoff[0].strategyId));
  const [selTrade, setSelTrade] = useState(null);       // selected trade object (any strategy)
  const [tradeFilter, setTradeFilter] = useState("all"); // all | buy | sell
  const [allStrat, setAllStrat] = useState("all");      // strategy filter in 'all' mode

  const finalist = useMemo(function () { return data.bakeoff.find(function (b) { return (b.runId || b.strategyId) === sel; }) || data.bakeoff[0]; }, [data, sel]);
  const opt = useMemo(function () { return optResultFor(finalist); }, [data, sel]);
  const m = finalist.metrics || {};
  const trades = finalist.trades || [];
  const stats = useMemo(function () { return tradeStats(trades); }, [sel]);
  const equity = useMemo(function () { return DS(finalist.equityCurve || [], 500); }, [sel]);
  const dd = useMemo(function () { return DS(ddSeries(finalist.equityCurve || []), 500); }, [sel]);
  const pnlHist = useMemo(function () { return histogram(stats.pnls, 12); }, [sel]);
  const months = useMemo(function () { return monthly(finalist.equityCurve || []); }, [sel]);
  const equityMarked = useMemo(function () {
    var rows = equity.map(function (p) { return { date: p.date, value: p.value, buy: null, sell: null }; });
    var idxByDate = {}; rows.forEach(function (r, i) { idxByDate[r.date] = i; });
    var dates = rows.map(function (r) { return r.date; });
    trades.forEach(function (t) { if (!t.date) return; var d = t.date.slice(0, 10); var di = idxByDate[d]; if (di == null) { var hit = dates.find(function (x) { return x.slice(0, 10) >= d; }); di = hit != null ? idxByDate[hit] : rows.length - 1; } if (di == null || !rows[di]) return; if (t.side === "buy") rows[di].buy = rows[di].value; else rows[di].sell = rows[di].value; });
    return rows;
  }, [sel]);
  var splitDate = (opt.summary && opt.summary.split) ? opt.summary.split.oosStartDate : null;
  var refDate = splitDate ? (equity.find(function (p) { return p.date >= splitDate; }) || {}).date : null;

  // combined ledger across ALL finalists (for 'all' mode)
  const allTrades = useMemo(function () {
    var out = []; data.bakeoff.forEach(function (b) { (b.trades || []).forEach(function (t) { out.push(Object.assign({}, t, { _strat: b.runId || b.strategyId })); }); });
    out.sort(function (a, c) { return (a.date || "").localeCompare(c.date || ""); });
    return out;
  }, [data]);

  const peers = useMemo(function () {
    if (!selTrade || !selTrade.date) return [];
    var d = selTrade.date.slice(0, 10);
    return data.bakeoff.map(function (b) { return { id: b.runId || b.strategyId, actions: (b.trades || []).filter(function (t) { return (t.date || "").slice(0, 10) === d; }) }; });
  }, [selTrade, data]);

  // ---- styles ----
  var mono = "var(--m)", head = "var(--h)";
  var panel = { background: "#0d1117", border: "1px solid rgba(255,255,255,0.06)", borderRadius: 8, padding: 14, marginBottom: 14 };
  var h2 = { fontFamily: head, fontWeight: 700, fontSize: 13, color: "#f8fafc", marginBottom: 10 };
  var th = { textAlign: "right", padding: "5px 7px", fontSize: 9, color: "#6b7280", fontFamily: head, fontWeight: 700, borderBottom: "1px solid rgba(255,255,255,0.08)", whiteSpace: "nowrap" };
  var td = { textAlign: "right", padding: "5px 7px", fontSize: 11, fontFamily: mono, color: "#cbd5e1", whiteSpace: "nowrap" };
  var GZMI = (typeof window !== "undefined" && window.GZ_METRIC_INFO) || {};
  function gzTip(info) { return info ? info.t + " — " + info.d : undefined; }
  function stat(label, val, c, infoKey) {
    var info = infoKey ? GZMI[infoKey] : null;
    return <div title={gzTip(info)} style={{ background: "#0f172a", borderRadius: 6, padding: "7px 10px", minWidth: 84, cursor: info ? "help" : "default" }}><div style={{ fontSize: 9, color: "#6b7280", fontFamily: head, fontWeight: 700 }}>{label}{info && <span style={{ color: "#475569" }}> ⓘ</span>}</div><div style={{ fontSize: 14, color: c || "#f8fafc", fontFamily: mono, fontWeight: 700 }}>{val}</div></div>;
  }
  function modeBtn(k, label) { return <button onClick={function () { setMode(k); setSelTrade(null); }} style={{ fontSize: 11, fontFamily: mono, padding: "5px 12px", borderRadius: 6, cursor: "pointer", border: "1px solid " + (mode === k ? "#f59e0b" : "rgba(255,255,255,0.12)"), background: mode === k ? "rgba(245,158,11,0.14)" : "none", color: mode === k ? "#f59e0b" : "#94a3b8", fontWeight: mode === k ? 700 : 400 }}>{label}</button>; }
  function filterBtns() { return <div style={{ display: "flex", gap: 4 }}>{[["all", "Hepsi"], ["buy", "Al"], ["sell", "Sat"]].map(function (o) { return <button key={o[0]} onClick={function () { setTradeFilter(o[0]); }} style={{ fontSize: 9, fontFamily: mono, padding: "3px 8px", borderRadius: 5, cursor: "pointer", border: "1px solid " + (tradeFilter === o[0] ? "#f59e0b" : "rgba(255,255,255,0.12)"), background: tradeFilter === o[0] ? "rgba(245,158,11,0.12)" : "none", color: tradeFilter === o[0] ? "#f59e0b" : "#94a3b8" }}>{o[1]}</button>; })}</div>; }

  var filteredTrades = (tradeFilter === "all" ? trades : trades.filter(function (t) { return t.side === tradeFilter; }));
  var allFiltered = allTrades.filter(function (t) { return (allStrat === "all" || t._strat === allStrat) && (tradeFilter === "all" || t.side === tradeFilter); });
  var oosM = opt.result && opt.result.oosMetrics ? opt.result.oosMetrics : null;
  var trM = opt.result && opt.result.metrics ? opt.result.metrics : null;
  var allOosScores = opt.summary ? (opt.summary.results || []).map(function (r) { return { x: +r.trainScore || 0, y: +r.oosScore || 0, sel: r.comboIndex === comboIndexOf(finalist.runId) }; }) : [];

  // ---- shared decision drawer ----
  function decisionDrawer() {
    if (!selTrade) return <div style={{ fontSize: 11, color: "#6b7280", fontFamily: mono }}>Bir trade sec → karar gerekcesi burada.</div>;
    var dv = decisionOf(selTrade);
    return (
      <div>
        {selTrade._strat && <div style={{ fontSize: 9, color: "#f59e0b", fontFamily: mono, marginBottom: 2 }}>{selTrade._strat}</div>}
        <div style={{ fontSize: 12, fontFamily: head, fontWeight: 700, color: selTrade.side === "buy" ? "#22c55e" : "#ef4444", marginBottom: 4 }}>{(selTrade.date || "").slice(0, 10)} · <span style={{ color: "#f8fafc" }}>{selTrade.symbol}</span> · {String(selTrade.side).toUpperCase()} {num(selTrade.qty, 4)} @ ${num(selTrade.price)}{selTrade.side === "sell" ? " · pnl " + num(selTrade.pnl) : ""}</div>
        <div style={{ fontSize: 11, color: "#e2e8f0", fontFamily: mono, marginBottom: 8 }}>{dv.reason}</div>
        {dv.kind === "rich" ? (
          <div style={{ fontSize: 10, fontFamily: mono, color: "#cbd5e1", display: "flex", flexDirection: "column", gap: 5 }}>
            {dv.regime && <div>regime: <b style={{ color: "#a5b4fc" }}>{dv.regime.type}</b> · ADX {num(dv.regime.adx, 1)}</div>}
            <div>skor: buy <b style={{ color: "#22c55e" }}>{num(dv.buyScore, 1)}</b> / sell <b style={{ color: "#ef4444" }}>{num(dv.sellScore, 1)}</b> · esik buy {num(dv.buyThreshold, 1)} sell {num(dv.sellThreshold, 1)}</div>
            {!!(dv.reasons && dv.reasons.length) && <div>nedenler: {dv.reasons.map(function (r, i) { return <span key={i} style={{ background: "rgba(34,197,94,0.12)", color: "#22c55e", borderRadius: 3, padding: "1px 5px", marginRight: 3 }}>{r}</span>; })}</div>}
            {!!(dv.blocked && dv.blocked.length) && <div>engeller: {dv.blocked.map(function (r, i) { return <span key={i} style={{ background: "rgba(239,68,68,0.12)", color: "#ef4444", borderRadius: 3, padding: "1px 5px", marginRight: 3 }}>{r}</span>; })}</div>}
            {dv.riskSell && <div style={{ color: "#f59e0b" }}>risk/exit: {dv.riskSell}</div>}
            {dv.holdingBars != null && <div>hold: {dv.holdingBars} bar{dv.pnlPct != null ? " · pnl " + num(dv.pnlPct * 100) + "%" : ""}</div>}
          </div>
        ) : (
          <div style={{ fontSize: 10, fontFamily: mono, color: "#cbd5e1", display: "flex", flexDirection: "column", gap: 5 }}>
            {Object.keys(dv.indicators).length > 0 && <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>{Object.keys(dv.indicators).map(function (k) { return <span key={k} style={{ background: "#0a0e17", borderRadius: 3, padding: "2px 6px" }}>{k}: <b style={{ color: "#f8fafc" }}>{num(dv.indicators[k], 2)}</b></span>; })}</div>}
            {dv.dmaState && <div>dmaState: {JSON.stringify(dv.dmaState)}</div>}
          </div>
        )}
        <div style={{ marginTop: 10, borderTop: "1px solid rgba(255,255,255,0.08)", paddingTop: 8 }}>
          <div style={{ fontSize: 9, color: "#6b7280", fontFamily: head, fontWeight: 700, marginBottom: 4 }}>AYNI GUN · diger yontemler</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {peers.map(function (p) { var acts = p.actions.map(function (a) { return a.side; }); var label = acts.length ? acts.join(",") : "hold"; var c = acts.indexOf("buy") >= 0 ? "#22c55e" : acts.indexOf("sell") >= 0 ? "#ef4444" : "#6b7280"; return <div key={p.id} style={{ display: "flex", justifyContent: "space-between", fontSize: 9, fontFamily: mono }}><span style={{ color: "#94a3b8" }}>{p.id}</span><span style={{ color: c }}>{label}</span></div>; })}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={panel}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8, marginBottom: 10 }}>
        <div style={{ ...h2, marginBottom: 0 }}>🔬 Yontem Analizi + Karar Mufettisi</div>
        <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
          {modeBtn("single", "Tek Yontem")}
          {modeBtn("all", "Tum Yontemler")}
          {mode === "single" && <select className="gz-finalist-select" value={sel} onChange={function (e) { setSel(e.target.value); setSelTrade(null); }}
            style={{ background: "#0f172a", color: "#f8fafc", border: "1px solid rgba(255,255,255,0.12)", borderRadius: 6, padding: "6px 10px", fontFamily: mono, fontSize: 11 }}>
            {data.bakeoff.map(function (b) { var id = b.runId || b.strategyId; return <option key={id} value={id}>{id === savedWinnerId ? "🏆 " : ""}{id} · {num(b.metrics && b.metrics.totalReturnPct)}%</option>; })}
          </select>}
        </div>
      </div>

      {mode === "single" && (
        <div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            {stat("RETURN", num(m.totalReturnPct) + "%", m.totalReturnPct >= 0 ? "#22c55e" : "#ef4444", "ret")}
            {stat("ALPHA", num(m.alphaPct) + "%", m.alphaPct >= 0 ? "#22c55e" : "#ef4444", "alpha")}
            {stat("MAX DD", num(m.maxDrawdownPct) + "%", "#f59e0b", "maxDD")}
            {stat("SHARPE", num(m.sharpe), "#a5b4fc", "sharpe")}
            {stat("WIN RATE", num(stats.winRate, 1) + "%", "#22d3ee", "winRate")}
            {stat("PF", num(m.profitFactor), "#cbd5e1", "pf")}
            {stat("TRADES", m.totalTrades, "#cbd5e1", "trades")}
          </div>
          <div style={{ fontSize: 10, color: "#64748b", fontFamily: mono, marginBottom: 6 }}>params: {JSON.stringify(finalist.params || {})}</div>

          {opt.result && (
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10, marginBottom: 12 }}>
              <div style={{ background: "#0f172a", borderRadius: 6, padding: 10 }}>
                <div title={(typeof window !== "undefined" && window.GZ_OVERFIT_INFO) || ""} style={{ fontSize: 10, color: "#6b7280", fontFamily: head, fontWeight: 700, marginBottom: 6, cursor: "help" }}>SAGLAMLIK · train vs OOS <span style={{ color: "#475569" }}>ⓘ</span>
                  <span title={((typeof window !== "undefined" && window.GZ_STATUS_INFO) || {})[opt.result.status] ? window.GZ_STATUS_INFO[opt.result.status].t + " — " + window.GZ_STATUS_INFO[opt.result.status].d : undefined} style={{ marginLeft: 8, color: opt.result.status === "OK" ? "#22c55e" : opt.result.status === "OVERFIT_RISK" ? "#f59e0b" : "#ef4444", fontWeight: 700, cursor: "help" }}>{opt.result.status}{(opt.result.riskFlags || []).length ? " · " + opt.result.riskFlags.join("|") : ""}</span>
                </div>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead><tr><th style={{ ...th, textAlign: "left" }}>metrik</th><th style={th}>train</th><th style={th}>OOS</th></tr></thead>
                  <tbody>
                    {[["return%", trM && trM.totalReturnPct, oosM && oosM.totalReturnPct], ["maxDD%", trM && trM.maxDrawdownPct, oosM && oosM.maxDrawdownPct], ["sharpe", trM && trM.sharpe, oosM && oosM.sharpe], ["trades", trM && trM.totalTrades, oosM && oosM.totalTrades], ["score", opt.result.trainScore, opt.result.oosScore]].map(function (row) {
                      return <tr key={row[0]}><td style={{ ...td, textAlign: "left", color: "#94a3b8" }}>{row[0]}</td><td style={td}>{num(row[1])}</td><td style={{ ...td, color: "#f8fafc", fontWeight: 700 }}>{num(row[2])}</td></tr>;
                    })}
                  </tbody>
                </table>
              </div>
              <div style={{ background: "#0f172a", borderRadius: 6, padding: 10 }}>
                <div style={{ fontSize: 10, color: "#6b7280", fontFamily: head, fontWeight: 700, marginBottom: 6 }}>PARAMETRE DUYARLILIGI <span style={{ fontWeight: 400 }}>(train vs OOS skor · ◆ = secili)</span></div>
                {allOosScores.length > 1 ? (
                  <ResponsiveContainer width="100%" height={150}>
                    <ComposedChart margin={{ top: 6, right: 10, left: -10, bottom: 0 }}>
                      <CartesianGrid stroke="rgba(255,255,255,0.05)" />
                      <XAxis type="number" dataKey="x" name="train" tick={{ fontSize: 8, fill: "#6b7280" }} />
                      <YAxis type="number" dataKey="y" name="oos" tick={{ fontSize: 8, fill: "#6b7280" }} />
                      <ReferenceLine y={0} stroke="rgba(255,255,255,0.15)" />
                      <Tooltip contentStyle={{ background: "#0f172a", border: "1px solid rgba(255,255,255,0.1)", fontSize: 10, fontFamily: mono }} />
                      <Scatter data={allOosScores.filter(function (p) { return !p.sel; })} fill="#475569" />
                      <Scatter data={allOosScores.filter(function (p) { return p.sel; })} fill="#f59e0b" shape="diamond" />
                    </ComposedChart>
                  </ResponsiveContainer>
                ) : <div style={{ fontSize: 10, color: "#6b7280", fontFamily: mono, padding: 20 }}>Tek kombinasyon (parametresiz) — duyarlilik yok.</div>}
                <div style={{ fontSize: 9, color: "#6b7280", fontFamily: mono, marginTop: 2 }}>Sag-ust kume = saglam plato · yalniz secili nokta yuksekse = kirilgan tepe (overfit)</div>
              </div>
            </div>
          )}

          <div style={{ ...h2, fontSize: 11 }}>Equity + Al/Sat Marker'lari {refDate && <span style={{ fontWeight: 400, color: "#ef4444", fontSize: 9 }}>(kirmizi cizgi = OOS)</span>} <span style={{ fontWeight: 400, color: "#6b7280", fontSize: 9 }}>· fare tekerleği = yakınlaş/uzaklaş · sürükle = kaydır</span></div>
          <ZoomChart dataKey="date" dataLength={equityMarked.length}>
            <ResponsiveContainer width="100%" height={isMobile ? 200 : 250}>
              <ComposedChart data={equityMarked} margin={{ top: 6, right: 10, left: 0, bottom: 0 }}>
                <CartesianGrid stroke="rgba(255,255,255,0.05)" />
                <XAxis dataKey="date" tick={{ fontSize: 8, fill: "#6b7280" }} minTickGap={40} />
                <YAxis tick={{ fontSize: 8, fill: "#6b7280" }} width={52} tickFormatter={function (v) { return "$" + fK(v); }} domain={["auto", "auto"]} />
                <Tooltip contentStyle={{ background: "#0f172a", border: "1px solid rgba(255,255,255,0.1)", fontSize: 10, fontFamily: mono }} formatter={function (v) { return "$" + fmt(v); }} />
                {refDate && <ReferenceLine x={refDate} stroke="#ef4444" strokeDasharray="4 3" />}
                <Line type="monotone" dataKey="value" stroke={color(0)} dot={false} strokeWidth={2} isAnimationActive={false} />
                <Scatter dataKey="buy" fill="#22c55e" isAnimationActive={false} />
                <Scatter dataKey="sell" fill="#ef4444" isAnimationActive={false} />
              </ComposedChart>
            </ResponsiveContainer>
            <ResponsiveContainer width="100%" height={110}>
              <AreaChart data={dd} margin={{ top: 4, right: 10, left: 0, bottom: 0 }}>
                <XAxis dataKey="date" hide />
                <YAxis tick={{ fontSize: 8, fill: "#6b7280" }} width={52} tickFormatter={function (v) { return v + "%"; }} />
                <Tooltip contentStyle={{ background: "#0f172a", border: "1px solid rgba(255,255,255,0.1)", fontSize: 10, fontFamily: mono }} formatter={function (v) { return num(v) + "%"; }} />
                <Area type="monotone" dataKey="dd" stroke="#ef4444" fill="rgba(239,68,68,0.25)" isAnimationActive={false} />
              </AreaChart>
            </ResponsiveContainer>
          </ZoomChart>

          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10, margin: "12px 0" }}>
            <div style={{ background: "#0f172a", borderRadius: 6, padding: 10 }}>
              <div style={{ fontSize: 10, color: "#6b7280", fontFamily: head, fontWeight: 700, marginBottom: 6 }}>KAZANC DAGILIMI (realized PnL/trade)</div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 6, fontSize: 11, fontFamily: mono }}>
                <span style={{ color: "#22c55e" }}>avg win ${num(stats.avgWin)}</span>
                <span style={{ color: "#ef4444" }}>avg loss ${num(stats.avgLoss)}</span>
                <span style={{ color: "#22c55e" }}>best ${num(stats.best && stats.best.pnl)}</span>
                <span style={{ color: "#ef4444" }}>worst ${num(stats.worst && stats.worst.pnl)}</span>
              </div>
              <ResponsiveContainer width="100%" height={130}>
                <BarChart data={pnlHist} margin={{ top: 4, right: 6, left: -16, bottom: 0 }}>
                  <XAxis dataKey="label" tick={{ fontSize: 7, fill: "#6b7280" }} interval={1} />
                  <YAxis tick={{ fontSize: 8, fill: "#6b7280" }} allowDecimals={false} />
                  <Tooltip contentStyle={{ background: "#0f172a", border: "1px solid rgba(255,255,255,0.1)", fontSize: 10, fontFamily: mono }} />
                  <Bar dataKey="count" isAnimationActive={false}>{pnlHist.map(function (b, i) { return <Cell key={i} fill={b.mid >= 0 ? "#22c55e" : "#ef4444"} />; })}</Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
            <div style={{ background: "#0f172a", borderRadius: 6, padding: 10, overflowX: "auto" }}>
              <div style={{ fontSize: 10, color: "#6b7280", fontFamily: head, fontWeight: 700, marginBottom: 6 }}>AYLIK GETIRI (%)</div>
              <table style={{ borderCollapse: "collapse", fontFamily: mono }}>
                <thead><tr><th style={{ ...th, textAlign: "left" }}></th>{["O", "S", "M", "N", "M", "H", "T", "A", "E", "E", "K", "A"].map(function (mm, i) { return <th key={i} style={{ ...th, padding: "3px 5px" }}>{mm}</th>; })}</tr></thead>
                <tbody>
                  {Object.keys(months).sort().map(function (y) {
                    return <tr key={y}><td style={{ ...td, textAlign: "left", color: "#94a3b8" }}>{y}</td>{Array.from({ length: 12 }).map(function (_, i) { var v = months[y][i]; return <td key={i} title={v != null ? num(v) + "%" : ""} style={{ padding: 0 }}><div style={{ width: 22, height: 18, background: heat(v), borderRadius: 2, fontSize: 7, color: "#0a0e17", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>{v != null ? Math.round(v) : ""}</div></td>; })}</tr>;
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TRADE LEDGER (single OR all) + DECISION DRAWER */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 6 }}>
        <div style={{ ...h2, fontSize: 11, marginBottom: 4 }}>{mode === "all" ? "Tum Yontemler — Al/Sat Kararlari" : "Karar Defteri"} <span style={{ fontWeight: 400, color: "#6b7280", fontSize: 9 }}>(satira tikla → neden)</span></div>
        <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
          {mode === "all" && <select value={allStrat} onChange={function (e) { setAllStrat(e.target.value); }} style={{ background: "#0f172a", color: "#f8fafc", border: "1px solid rgba(255,255,255,0.12)", borderRadius: 5, padding: "4px 8px", fontFamily: mono, fontSize: 10 }}>
            <option value="all">tum stratejiler</option>
            {data.bakeoff.map(function (b) { var id = b.runId || b.strategyId; return <option key={id} value={id}>{id}</option>; })}
          </select>}
          {filterBtns()}
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.3fr 1fr", gap: 10 }}>
        <div style={{ overflowX: "auto", maxHeight: 380, overflowY: "auto", border: "1px solid rgba(255,255,255,0.06)", borderRadius: 6 }}>
          {mode === "all" ? (
            <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 480 }}>
              <thead><tr>{["strateji", "sembol", "tarih", "side", "fiyat", "pnl", "neden"].map(function (c, i) { return <th key={c} style={{ ...th, textAlign: i >= 4 && i <= 5 ? "right" : "left", position: "sticky", top: 0, background: "#0d1117" }}>{c}</th>; })}</tr></thead>
              <tbody>
                {allFiltered.slice(0, 600).map(function (t, i) {
                  var on = selTrade === t;
                  return (
                    <tr key={i} className="gz-trade-row" onClick={function () { setSelTrade(t); }} style={{ cursor: "pointer", background: on ? "rgba(245,158,11,0.12)" : "transparent", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                      <td style={{ ...td, textAlign: "left", fontSize: 9, color: "#a5b4fc" }}>{t._strat}</td>
                      <td style={{ ...td, textAlign: "left", fontWeight: 700, color: "#f8fafc" }}>{t.symbol}</td>
                      <td style={{ ...td, textAlign: "left", fontSize: 9 }}>{(t.date || "").slice(0, 10)}</td>
                      <td style={{ ...td, textAlign: "left", color: t.side === "buy" ? "#22c55e" : "#ef4444", fontWeight: 700 }}>{t.side}</td>
                      <td style={td}>${num(t.price)}</td>
                      <td style={{ ...td, color: (t.pnl || 0) > 0 ? "#22c55e" : (t.pnl || 0) < 0 ? "#ef4444" : "#6b7280" }}>{t.side === "sell" ? num(t.pnl) : "—"}</td>
                      <td style={{ ...td, textAlign: "left", fontSize: 9, color: "#94a3b8", maxWidth: 150, overflow: "hidden", textOverflow: "ellipsis" }}>{t.reason}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          ) : (
            <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 420 }}>
              <thead><tr>{["sembol", "tarih", "side", "fiyat", "pnl", "neden"].map(function (c, i) { return <th key={c} style={{ ...th, textAlign: i < 3 || i === 5 ? "left" : "right", position: "sticky", top: 0, background: "#0d1117" }}>{c}</th>; })}</tr></thead>
              <tbody>
                {filteredTrades.slice(0, 300).map(function (t, i) {
                  var on = selTrade === t;
                  return (
                    <tr key={i} className="gz-trade-row" onClick={function () { setSelTrade(t); }} style={{ cursor: "pointer", background: on ? "rgba(245,158,11,0.12)" : "transparent", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                      <td style={{ ...td, textAlign: "left", fontWeight: 700, color: "#f8fafc" }}>{t.symbol}</td>
                      <td style={{ ...td, textAlign: "left", fontSize: 9 }}>{(t.date || "").slice(0, 10)}</td>
                      <td style={{ ...td, textAlign: "left", color: t.side === "buy" ? "#22c55e" : "#ef4444", fontWeight: 700 }}>{t.side}{t.type && t.type !== "signal" ? "·" + t.type : ""}</td>
                      <td style={td}>${num(t.price)}</td>
                      <td style={{ ...td, color: (t.pnl || 0) > 0 ? "#22c55e" : (t.pnl || 0) < 0 ? "#ef4444" : "#6b7280" }}>{t.side === "sell" ? num(t.pnl) : "—"}</td>
                      <td style={{ ...td, textAlign: "left", fontSize: 9, color: "#94a3b8", maxWidth: 180, overflow: "hidden", textOverflow: "ellipsis" }}>{t.reason}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
        <div style={{ background: "#0f172a", borderRadius: 6, padding: 12, minHeight: 120 }}>{decisionDrawer()}</div>
      </div>
      {mode === "all" && <div style={{ fontSize: 9, color: "#6b7280", fontFamily: mono, marginTop: 4 }}>{allFiltered.length} karar{allFiltered.length > 600 ? " (ilk 600 gosteriliyor — strateji/side filtresiyle daralt)" : ""} · {data.bakeoff.length} yontem</div>}
    </div>
  );
}

window.GauntletAnalysis = GauntletAnalysis;
