// Interactive Demo section — strategy picker + stats + equity curve + monthly bars + positions

const DEMO_STRATEGIES = [
  { id: "all",          name: "All Strategies", color: "262 83% 67%",
    stats: { realized: 60543.03, unrealized: 11580.30, winRate: 61.8, sharpe: 1.86, maxDD: -3.20, trades: 784 },
    curve: { start: 224000, end: 296123, seed: 4711 },
    monthly: [ 1820, 2640, -1240, 3280, 4120, -680, 2940, 5210, 3820, -1480, 4640, 3120 ],
    positions: [
      { sym: "NVDA",  qty: 120, avg: 802.40,  mkt: 884.10 },
      { sym: "AVGO",  qty: 38,  avg: 1342.20, mkt: 1418.50 },
      { sym: "TQQQ",  qty: 240, avg: 64.18,   mkt: 71.20 },
      { sym: "SHOP",  qty: 180, avg: 96.40,   mkt: 102.10 },
      { sym: "PLTR",  qty: 320, avg: 22.40,   mkt: 21.18 },
    ],
  },
  { id: "momo-nasdaq",  name: "Momentum_Tech", color: "262 83% 67%",
    stats: { realized: 18420.10, unrealized: 3120.40, winRate: 64.2, sharpe: 2.04, maxDD: -2.80, trades: 184 },
    curve: { start: 64000, end: 85540, seed: 1003 },
    monthly: [ 620, 1140, -340, 980, 1620, -220, 1240, 2310, 1620, -480, 1840, 1320 ],
    positions: [
      { sym: "NVDA",  qty: 120, avg: 802.40,  mkt: 884.10 },
      { sym: "AVGO",  qty: 38,  avg: 1342.20, mkt: 1418.50 },
      { sym: "META",  qty: 22,  avg: 482.10,  mkt: 514.30 },
      { sym: "AMD",   qty: 80,  avg: 142.50,  mkt: 158.40 },
      { sym: "MSFT",  qty: 30,  avg: 410.10,  mkt: 422.80 },
    ],
  },
  { id: "wtt-sp500",    name: "Trend_SP500", color: "145 60% 50%",
    stats: { realized: 11240.40, unrealized: -240.10, winRate: 61.4, sharpe: 1.93, maxDD: -2.10, trades: 96 },
    curve: { start: 48000, end: 59000, seed: 2104 },
    monthly: [ 420, 880, -180, 760, 1020, -120, 940, 1410, 1120, -380, 1640, 920 ],
    positions: [
      { sym: "PLTR",  qty: 320, avg: 22.40,   mkt: 21.18 },
      { sym: "DIS",   qty: 60,  avg: 102.40,  mkt: 108.20 },
      { sym: "BAC",   qty: 200, avg: 36.20,   mkt: 38.10 },
      { sym: "WMT",   qty: 40,  avg: 168.10,  mkt: 172.40 },
      { sym: "XOM",   qty: 90,  avg: 114.20,  mkt: 109.40 },
    ],
  },
  { id: "rotation-etf",      name: "Rotation_ETF", color: "262 50% 78%",
    stats: { realized: 5210.80, unrealized: 2240.10, winRate: 65.2, sharpe: 2.20, maxDD: -1.90, trades: 46 },
    curve: { start: 28000, end: 35450, seed: 3402 },
    monthly: [ 280, 410, -90, 480, 620, -40, 540, 720, 540, -180, 680, 460 ],
    positions: [
      { sym: "VTI",   qty: 120, avg: 245.30,  mkt: 252.80 },
      { sym: "VXUS",  qty: 200, avg: 58.20,   mkt: 60.40 },
      { sym: "BND",   qty: 90,  avg: 72.10,   mkt: 72.80 },
      { sym: "VNQ",   qty: 60,  avg: 86.20,   mkt: 88.60 },
    ],
  },
  { id: "adaptive-growth",         name: "Adaptive_Growth", color: "0 75% 62%",
    stats: { realized: 3640.40, unrealized: 1860.50, winRate: 62.5, sharpe: 1.66, maxDD: -4.20, trades: 32 },
    curve: { start: 18000, end: 23500, seed: 7211 },
    monthly: [ 180, 320, -240, 410, 680, -180, 480, 920, 540, -380, 720, 410 ],
    positions: [
      { sym: "TQQQ",  qty: 240, avg: 64.18,   mkt: 71.20 },
    ],
  },
];

function DemoStat({ label, value, tone = "neutral", suffix = "", prefix = "", changing }) {
  const color = tone === "positive" ? "text-positive" : tone === "negative" ? "text-negative" : "text-fg";
  return (
    <div className="card2 p-3">
      <div className="text-[10px] font-semibold uppercase tracking-wider text-subtlefg">{label}</div>
      <div className={`mt-1 font-mono text-lg md:text-xl font-bold tabular-nums ${color} transition-opacity ${changing ? "opacity-50" : "opacity-100"}`}>
        {prefix}{value}{suffix}
      </div>
    </div>
  );
}

function InteractiveDemo() {
  const [active, setActive] = React.useState("all");
  const [transitioning, setTransitioning] = React.useState(false);
  const strat = DEMO_STRATEGIES.find(s => s.id === active);
  const curveData = React.useMemo(
    () => genCurve(strat.curve.start, strat.curve.end, 30, strat.curve.seed),
    [strat.id]
  );
  React.useEffect(() => {
    setTransitioning(true);
    const t = setTimeout(() => setTransitioning(false), 200);
    return () => clearTimeout(t);
  }, [active]);

  const monthlyData = strat.monthly.map((v, i) => ({ m: ["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"][i], v }));

  return (
    <Section
      id="demo"
      eyebrow="Live · interactive"
      title="Try it now, no signup needed."
      sub="Pick a strategy. Watch the dashboard pivot in real time. Same UI you'll see in production, same numbers, same density."
    >
      {/* Strategy pill row */}
      <div className="flex flex-wrap gap-2 mb-6">
        {DEMO_STRATEGIES.map(s => (
          <Pill key={s.id} active={active === s.id} onClick={() => setActive(s.id)}>
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full" style={{background: `hsl(${s.color})`}} />
              {s.name}
            </span>
          </Pill>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
        {/* Left stats column */}
        <div className="lg:col-span-4 space-y-3">
          <DemoStat
            label="Realized P&L"
            value={(strat.stats.realized >= 0 ? "+" : "-") + "$" + fmtNum(Math.abs(strat.stats.realized))}
            tone={strat.stats.realized >= 0 ? "positive" : "negative"}
            changing={transitioning}
          />
          <DemoStat
            label="Unrealized P&L"
            value={(strat.stats.unrealized >= 0 ? "+" : "-") + "$" + fmtNum(Math.abs(strat.stats.unrealized))}
            tone={strat.stats.unrealized >= 0 ? "positive" : "negative"}
            changing={transitioning}
          />
          <DemoStat label="Win Rate"      value={`${strat.stats.winRate.toFixed(1)}%`} changing={transitioning} />
          <DemoStat label="Sharpe"        value={strat.stats.sharpe.toFixed(2)}        changing={transitioning} />
          <DemoStat label="Max Drawdown"  value={`${strat.stats.maxDD.toFixed(2)}%`}   tone="negative" changing={transitioning} />
          <DemoStat label="Round-trips"   value={strat.stats.trades.toString()}        changing={transitioning} />
        </div>

        {/* Right chart column */}
        <div className="lg:col-span-8 space-y-4">
          <div className="card1 p-4">
            <div className="flex items-center justify-between mb-2">
              <div>
                <div className="text-[10px] font-semibold uppercase tracking-wider text-subtlefg">Equity curve · 30 days</div>
                <div className="font-mono text-2xl font-bold mt-0.5">${Math.round(strat.curve.end).toLocaleString()}</div>
              </div>
              <div className="text-right">
                <div className="text-[10px] font-semibold uppercase tracking-wider text-subtlefg">Period change</div>
                <Signed value={strat.curve.end - strat.curve.start} className="text-base font-bold" />
              </div>
            </div>
            <div className={`transition-opacity duration-200 ${transitioning ? "opacity-60" : "opacity-100"}`}>
              <EquityChart data={curveData} width={760} height={200} stroke={`hsl(${strat.color})`} />
            </div>
          </div>
          <div className="card1 p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="text-[10px] font-semibold uppercase tracking-wider text-subtlefg">Monthly P&L · trailing 12 months</div>
              <div className="text-[10px] text-subtlefg">Σ <span className="text-positive font-mono">+${strat.monthly.reduce((a,v)=>a+v,0).toLocaleString()}</span></div>
            </div>
            <div className={`transition-opacity duration-200 ${transitioning ? "opacity-60" : "opacity-100"}`}>
              <BarsChart data={monthlyData} width={600} height={130} />
            </div>
          </div>
        </div>
      </div>

      {/* Open positions for selected strategy */}
      <div className="card1 mt-4 overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-border1">
          <div className="flex items-center gap-2">
            <span className="text-[11px] font-semibold uppercase tracking-wider text-subtlefg">Open positions</span>
            <Badge tone="ghost" className="!normal-case !tracking-normal !text-[10px]">{strat.positions.length} live</Badge>
            <span className="text-[11px] text-subtlefg">· {strat.name}</span>
          </div>
          <span className="text-[10px] text-subtlefg inline-flex items-center gap-1.5"><span className="live-dot" />EODHD marks · last 4 min</span>
        </div>
        <table className="df w-full text-[12px]">
          <thead>
            <tr>
              <th>Symbol</th>
              <th className="text-right">Qty</th>
              <th className="text-right">Avg Cost</th>
              <th className="text-right">Market</th>
              <th className="text-right">Unrealized</th>
              <th className="text-right">%</th>
            </tr>
          </thead>
          <tbody className={`transition-opacity duration-200 ${transitioning ? "opacity-60" : "opacity-100"}`}>
            {strat.positions.map(p => {
              const pnl = (p.mkt - p.avg) * p.qty;
              const pct = ((p.mkt - p.avg) / p.avg) * 100;
              return (
                <tr key={p.sym}>
                  <td className="font-mono font-semibold">{p.sym}</td>
                  <td className="text-right font-mono tabular-nums">{p.qty}</td>
                  <td className="text-right font-mono tabular-nums text-mutedfg">${p.avg.toFixed(2)}</td>
                  <td className="text-right font-mono tabular-nums">${p.mkt.toFixed(2)}</td>
                  <td className="text-right"><Signed value={pnl} /></td>
                  <td className={`text-right font-mono tabular-nums ${pct >= 0 ? "text-positive" : "text-negative"}`}>{pct >= 0 ? "+" : ""}{pct.toFixed(2)}%</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Section>
  );
}

Object.assign(window, { InteractiveDemo, DEMO_STRATEGIES });
