// Faux equity-curve SVG — plots a normalised series of points as a polyline
function EquityCurve({ points, width = 600, height = 160 }) {
  const min = Math.min(...points);
  const max = Math.max(...points);
  const pad = { t: 12, r: 8, b: 8, l: 8 };
  const w = width - pad.l - pad.r;
  const h = height - pad.t - pad.b;
  const xs = points.map((_, i) => pad.l + (i / (points.length - 1)) * w);
  const ys = points.map(v => pad.t + h - ((v - min) / (max - min || 1)) * h);
  const poly = xs.map((x, i) => `${x},${ys[i]}`).join(' ');
  const areaPts = `${xs[0]},${pad.t + h} ${poly} ${xs[xs.length-1]},${pad.t + h}`;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: height, display: 'block' }} preserveAspectRatio="none">
      <polygon points={areaPts} fill={TH.accent} opacity="0.07"/>
      <polyline points={poly} fill="none" stroke={TH.accent} strokeWidth="1.5"/>
      {/* start / end dots */}
      <circle cx={xs[0]} cy={ys[0]} r="3" fill={TH.accent}/>
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r="3" fill={TH.accent}/>
    </svg>
  );
}

function BacktestEntry({ entry, go, wide }) {
  const [expanded, setExpanded] = React.useState(false);
  return (
    <div style={{ background: TH.panel, border: `1px solid ${TH.rule}`, marginBottom: 20 }}>
      {/* Entry header */}
      <div style={{ padding: wide ? '22px 28px 18px' : '16px 18px 14px', borderBottom: `1px solid ${TH.rule}` }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap', marginBottom: 8 }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.green, letterSpacing: 1.5, padding: '2px 7px', border: `1px solid ${TH.green}` }}>{entry.tag}</span>
            <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1 }}>{entry.category}</span>
          </div>
          <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1 }}>{entry.date}</span>
        </div>
        <div style={{ fontFamily: TH.serif, fontSize: wide ? 24 : 20, letterSpacing: -0.4, lineHeight: 1.2, marginBottom: 6 }}>{entry.title}</div>
        <div style={{ fontFamily: TH.serif, fontSize: 14, color: TH.inkSoft, lineHeight: 1.55 }}>{entry.summary}</div>
      </div>

      {/* Metrics strip */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${wide ? entry.metrics.length : Math.min(entry.metrics.length, 3)}, 1fr)`, borderBottom: `1px solid ${TH.rule}` }}>
        {entry.metrics.map((m, i) => (
          <div key={i} style={{ padding: '14px 16px', borderRight: i < entry.metrics.length - 1 ? `1px solid ${TH.rule}` : 'none' }}>
            <div style={{ fontFamily: TH.mono, fontSize: 9, color: TH.muted, letterSpacing: 1.5, marginBottom: 4 }}>{m.label}</div>
            <div style={{ fontFamily: TH.mono, fontSize: wide ? 18 : 15, color: m.color || TH.ink }}>{m.value}</div>
          </div>
        ))}
      </div>

      {/* Equity curve */}
      <div style={{ padding: wide ? '20px 28px' : '14px 18px', borderBottom: `1px solid ${TH.rule}` }}>
        <div style={{ fontFamily: TH.mono, fontSize: 9, color: TH.muted, letterSpacing: 1.5, marginBottom: 8 }}>OUT-OF-SAMPLE EQUITY CURVE (normalised to 100)</div>
        <div style={{ background: TH.bg, border: `1px solid ${TH.rule}`, padding: '8px 0' }}>
          <EquityCurve points={entry.curve}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: TH.mono, fontSize: 9, color: TH.muted, letterSpacing: 1, marginTop: 4 }}>
          <span>{entry.period.split('→')[0].trim()}</span>
          <span>{entry.period.split('→')[1].trim()}</span>
        </div>
      </div>

      {/* Expandable detail */}
      <div style={{ padding: wide ? '16px 28px' : '12px 18px' }}>
        <div onClick={() => setExpanded(v => !v)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer', userSelect: 'none' }}>
          <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.accent, letterSpacing: 1.5 }}>
            {expanded ? '▲ HIDE DETAIL' : '▼ PARAMETERS & ANALYSIS'}
          </span>
          <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1 }}>WALK-FORWARD VALIDATED</span>
        </div>

        {expanded && (
          <div style={{ marginTop: 18 }}>
            {/* Parameters */}
            <div style={{ fontFamily: TH.mono, fontSize: 9, color: TH.muted, letterSpacing: 1.5, marginBottom: 8 }}>PARAMETERS</div>
            <div style={{ background: TH.bg, border: `1px solid ${TH.rule}`, marginBottom: 18 }}>
              {entry.params.map(([k, v], i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 14px', borderBottom: i < entry.params.length - 1 ? `1px solid ${TH.rule}` : 'none', fontFamily: TH.mono, fontSize: 12 }}>
                  <span style={{ color: TH.muted }}>{k}</span>
                  <span style={{ color: TH.accent }}>{v}</span>
                </div>
              ))}
            </div>

            {/* Analysis */}
            <div style={{ fontFamily: TH.mono, fontSize: 9, color: TH.muted, letterSpacing: 1.5, marginBottom: 8 }}>ANALYSIS</div>
            <div style={{ fontFamily: TH.serif, fontSize: 14, color: TH.inkSoft, lineHeight: 1.75, marginBottom: 14 }}>
              {entry.analysis}
            </div>

            {/* Walk-forward note */}
            <div style={{ borderLeft: `3px solid ${TH.accent}`, paddingLeft: 16, fontFamily: TH.serif, fontSize: 13, color: TH.inkSoft, lineHeight: 1.6, fontStyle: 'italic' }}>
              <span style={{ fontFamily: TH.mono, fontSize: 9, color: TH.accent, letterSpacing: 1.5, fontStyle: 'normal', display: 'block', marginBottom: 4 }}>WALK-FORWARD NOTE</span>
              {entry.wfNote}
            </div>

            <div style={{ marginTop: 18, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <Btn primary small onClick={() => go('backtester')}>Run in backtester →</Btn>
              <Btn ghost small onClick={() => go('methodology')}>Read methodology</Btn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// BTC SMA 50/200 equity curve: 29 monthly data points, starts 100, ends ~1400
const BTC_CURVE = [100,118,134,109,98,115,142,168,195,212,185,210,248,310,290,320,375,420,390,440,510,580,620,590,680,760,830,910,980,1050,1140,1280,1380];
// SOL Donchian equity curve: 23 monthly data points, starts 100, ends ~870
const SOL_CURVE = [100,95,88,115,140,108,130,175,160,200,250,220,280,340,390,360,420,500,560,620,700,760,840,870];

const ENTRIES = [
  {
    tag: 'COMPLETE',
    category: 'BACKTEST · TREND',
    date: 'APR 16, 2026',
    title: 'SMA 50/200 crossover — Bitcoin 2019–2026',
    summary: 'Classic golden/death-cross system walk-forward validated on 7.25 years of BTC daily data. Long when price is above the 200-day MA and the 50-day is above the 200-day. Flat otherwise.',
    period: '2019-01-01 → 2026-04-01',
    metrics: [
      { label: 'OOS CAGR', value: '+41.2%', color: TH.green },
      { label: 'SHARPE', value: '1.82', color: TH.green },
      { label: 'MAX DD', value: '-28.4%', color: TH.inkSoft },
      { label: 'TRADES', value: '14', color: TH.inkSoft },
      { label: 'WIN RATE', value: '57%', color: TH.inkSoft },
    ],
    curve: BTC_CURVE,
    params: [
      ['Asset', 'BTC/USDT · Binance daily'],
      ['Fast MA', '50 days'],
      ['Slow MA', '200 days'],
      ['Direction', 'Long only'],
      ['Period', '2019-01-01 → 2026-04-01 (7.25 yr)'],
      ['WF windows', '3Y in-sample · 1Y out-of-sample · 6M step'],
      ['Fees', '0.10% per trade · 5bps slippage'],
    ],
    analysis: 'The strategy underperforms buy-and-hold on raw return (BTC buy-and-hold CAGR: +52.1%) but substantially reduces drawdown and volatility. The Sharpe of 1.82 out-of-sample is robust across the tested window steps, with no single period responsible for the result. Parameter stability is high: fast MAs from 40–60 and slow MAs from 180–220 all produce out-of-sample Sharpe above 1.4.',
    wfNote: 'Out-of-sample Sharpe was consistent across all 11 test windows (range: 1.41–2.14). No single window dominates the aggregate result.',
  },
  {
    tag: 'COMPLETE',
    category: 'BACKTEST · BREAKOUT',
    date: 'APR 9, 2026',
    title: 'Donchian 20-day breakout — Solana 2022–2026',
    summary: 'Enter long on a new 20-day closing high. Exit on a new 10-day closing low. A trend-following system that works on high-volatility assets where trends are structurally persistent.',
    period: '2022-01-01 → 2026-04-01',
    metrics: [
      { label: 'OOS CAGR', value: '+68.4%', color: TH.green },
      { label: 'SHARPE', value: '1.21', color: TH.inkSoft },
      { label: 'MAX DD', value: '-51.3%', color: TH.red },
      { label: 'TRADES', value: '43', color: TH.inkSoft },
      { label: 'WIN RATE', value: '41%', color: TH.inkSoft },
    ],
    curve: SOL_CURVE,
    params: [
      ['Asset', 'SOL/USDT · Binance daily'],
      ['Entry', 'Long on 20-day closing high'],
      ['Exit', 'Close on 10-day closing low'],
      ['Direction', 'Long only'],
      ['Period', '2022-01-01 → 2026-04-01 (4.25 yr)'],
      ['WF windows', '18M in-sample · 6M out-of-sample · 3M step'],
      ['Fees', '0.10% per trade · 5bps slippage'],
    ],
    analysis: 'Higher CAGR than buy-and-hold (SOL buy-and-hold CAGR: +38.7% over the same period) with a lower terminal drawdown, at the cost of significant interim drawdowns. The low win rate (41%) is characteristic of trend-following — the strategy relies on a small number of large winning trades. The out-of-sample Sharpe is acceptable but not exceptional, and the strategy shows more parameter sensitivity than the BTC SMA system. We consider it a working strategy with higher operational risk.',
    wfNote: '2 of 7 out-of-sample windows were negative. The two negative windows occurred in 2022 (bear market) and Q3 2024 (range-bound). Full window-by-window results available to members in the backtester.',
  },
];

function Research({ go }) {
  const wide = useWide();
  return (
    <div style={{ background: TH.bg, color: TH.ink, fontFamily: TH.serif, minHeight: '100vh' }}>
      {/* Breadcrumb */}
      <div style={{ borderBottom: `1px solid ${TH.rule}`, padding: wide ? '12px 32px' : '12px 20px', fontFamily: TH.mono, fontSize: 11, color: TH.muted, letterSpacing: 1.5 }}>
        <span onClick={() => go('landing')} style={{ cursor: 'pointer', color: TH.accent }}>HOME</span>
        <span style={{ margin: '0 10px' }}>›</span>
        <span>RESEARCH</span>
      </div>

      <div style={{ maxWidth: 960, margin: '0 auto', padding: wide ? '48px 32px 80px' : '28px 20px 64px' }}>
        {/* Header */}
        <div style={{ fontFamily: TH.mono, fontSize: 11, color: TH.accent, letterSpacing: 2, marginBottom: 14 }}>§ RESEARCH & BACKTESTS</div>
        <div style={{ fontSize: wide ? 52 : 34, letterSpacing: -1.5, lineHeight: 1.05, marginBottom: 16 }}>
          Tested, <span style={{ fontStyle: 'italic', color: TH.accent }}>not told.</span>
        </div>
        <div style={{ fontFamily: TH.serif, fontSize: wide ? 17 : 15, color: TH.inkSoft, lineHeight: 1.7, maxWidth: 640, marginBottom: 36 }}>
          Every strategy published here has been walk-forward validated — parameters optimized in-sample, performance measured out-of-sample. The methodology is documented. The data is available to members. Two recent examples below.
        </div>

        {/* Methodology callout */}
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '12px 18px', border: `1px solid ${TH.rule}`, background: TH.panel, marginBottom: 36, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1.5 }}>NOT SURE WHAT WALK-FORWARD MEANS?</span>
          <span onClick={() => go('methodology')} style={{ fontFamily: TH.mono, fontSize: 10, color: TH.accent, letterSpacing: 1, cursor: 'pointer' }}>Read the methodology →</span>
        </div>

        {/* Entries */}
        {ENTRIES.map((entry, i) => (
          <BacktestEntry key={i} entry={entry} go={go} wide={wide}/>
        ))}

        {/* CTA */}
        <div style={{ marginTop: 16, padding: wide ? 36 : 24, background: TH.panel, border: `1px solid ${TH.accent}` }}>
          <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.accent, letterSpacing: 2, marginBottom: 12 }}>§ FULL ACCESS</div>
          <div style={{ fontFamily: TH.serif, fontSize: wide ? 26 : 22, marginBottom: 10, letterSpacing: -0.4 }}>
            The backtester is open to members.
          </div>
          <div style={{ fontFamily: TH.serif, fontSize: 15, color: TH.inkSoft, lineHeight: 1.6, marginBottom: 22, maxWidth: 520 }}>
            Run these strategies yourself, modify the parameters, and see the full equity curves and trade logs. Members also get the weekly research memo and Telegram community access.
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <Btn primary onClick={() => go('pricing')}>See membership →</Btn>
            <Btn ghost onClick={() => go('memo/140')}>Read a free memo</Btn>
          </div>
        </div>
      </div>
      <Footer/>
    </div>
  );
}

Object.assign(window, { Research, BacktestEntry, EquityCurve });
