// Section components — Nav, Hero, Metrics, Strategy
function HeroCanvas() {
  const ref = React.useRef(null);
  const meshRef = React.useRef(null);
  React.useEffect(() => {
    if (meshRef.current && window.initHeroMesh) window.initHeroMesh(meshRef.current);
    if (ref.current && window.initHeroCanvas) window.initHeroCanvas(ref.current);
  }, []);
  return (
    <>
      <canvas id="hero-mesh" ref={meshRef} aria-hidden="true" />
      <canvas id="hero-canvas" ref={ref} />
    </>
  );
}

function Logo({ size = 'nav' }) {
  const isLarge = size === 'large';
  const isHero = size === 'hero';
  const markH = isHero ? 76 : isLarge ? 36 : 26;
  const wordSize = isHero ? 56 : isLarge ? 26 : 20;
  const gap = isHero ? 18 : isLarge ? 12 : undefined;
  return (
    <a className={`logo${isHero ? ' logo-hero' : ''}`} href="#top" style={gap ? { gap } : {}}>
      <img src="logo.png" alt="H" style={{
        height: markH,
        width: 'auto',
        display: 'block',
        filter: 'brightness(0) invert(1)',
        flexShrink: 0,
      }} />
      <span className="logo-text" style={{ gap: isHero ? 3 : isLarge ? 2 : 1 }}>
        <span className="logo-high" style={{ fontSize: wordSize }}>HIGH</span>
        <span className="logo-stake" style={{ fontSize: wordSize }}>stake</span>
      </span>
    </a>
  );
}

function Nav() {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-left">
          <Logo size="nav" />
          <div className="nav-links">
            <a href="#strategy">Strategy</a>
            <a href="#performance">Performance</a>
            <a href="#risk">Risk</a>
            <a href="#terms">Terms</a>
            <a href="/letters/">Letters</a>
          </div>
        </div>
        <div className="nav-right">
          <span className="pill live ok"><span className="dot" />LIVE</span>
          <a className="btn" href="#" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event('open-tearsheet-form')); }}>Tear Sheet ↗</a>
          <a className="btn btn-primary" href="#" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event('open-request-form')); }}>Request Access</a>
        </div>
      </div>
    </nav>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-inner shell">
        <div className="hero-status">
          <div className="hero-status-left">
            <span className="pill live ok soft"><span className="dot" />OPERATIONAL</span>
            <span className="hero-status-meta">TRACK RECORD<b>Jan 2025 — Apr 2026 · 16 mo</b></span>
          </div>
          <div className="hero-status-right">
            <span>LAST UPDATE<b>{(() => {
              const d = new Date();
              const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
              const M = months[d.getUTCMonth()];
              const D = String(d.getUTCDate()).padStart(2,'0');
              const Y = d.getUTCFullYear();
              const h = String(d.getUTCHours()).padStart(2,'0');
              const m = String(d.getUTCMinutes()).padStart(2,'0');
              return `${M} ${D} ${Y} · ${h}:${m} UTC`;
            })()}</b></span>
          </div>
        </div>

        <div className="hero-body">
          <div>
            <h1 className="hero-h1">
              Uncorrelated alpha, <em>systematically captured</em>.
            </h1>
            <p className="hero-sub">
              Highstake is a boutique quantitative digital asset fund deploying systematic
              counter-trend strategies against forced-flow dislocations across Binance, Bybit,
              and Hyperliquid — fully automated, market-neutral, with layered capital protection.
            </p>
            <div className="hero-actions">
              <a href="#" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event('open-request-form')); }} className="btn btn-primary">Request Access ↗</a>
              <a href="#performance" className="btn">View Performance</a>
            </div>
          </div>
          <div className="hero-panel">
            <div className="hstat">
              <div className="hstat-label">
                <span>Cumulative Returns · 16 mo</span>
                <span className="hstat-pulse" />
              </div>
              <div className="hstat-val g">
                <Counter value={131.46} decimals={2} /><span className="hstat-pct">%</span>
              </div>
              <div className="hstat-note">Jan 2025 — Apr 2026 · net strategy returns, before performance fee</div>
            </div>
            <div className="hstat">
              <div className="hstat-label">
                <span>Sharpe Ratio</span>
                <span className="hstat-pulse" style={{ animationDelay: '0.8s' }} />
              </div>
              <div className="hstat-val">
                &gt;<Counter value={3.0} decimals={1} />
              </div>
              <div className="hstat-note">Annualized · realized</div>
            </div>
            <div className="hstat">
              <div className="hstat-label">
                <span>Max Drawdown</span>
                <span className="hstat-pulse r" style={{ animationDelay: '1.6s' }} />
              </div>
              <div className="hstat-val r">
                −<Counter value={6.7} decimals={1} /><span className="hstat-pct">%</span>
              </div>
              <div className="hstat-note">Peak-to-trough, full period</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Metrics() {
  const items = [
    { l: "Win Rate", v: 94.4, d: 1, u: "%", note: "405 of 429 trading days", tag: "consistent" },
    { l: "Avg Monthly Return", v: 5.39, d: 2, u: "%", note: "geometric, compounded", tag: "compounding" },
    { l: "Positive Months", raw: "16 / 16", note: "consecutive · Jan 2025 – Apr 2026", tag: "consistent" },
    { l: "BTC Correlation", v: 0.12, d: 2, u: "", note: "near-zero", tag: "uncorrelated" },
  ];
  return (
    <section className="section" id="metrics">
      <div className="shell">
        <div className="sec-head reveal">
          <div className="sec-label">01 / KEY METRICS</div>
          <h2 className="sec-title">Sixteen months. <em>Every one</em> positive.</h2>
          <div className="sec-sub">
            <span>Jan 2025 – Apr 2026</span>
            <span className="sec-sub-dot" />
            <span>Net of fees</span>
            <span className="sec-sub-dot" />
            <span>Verified</span>
          </div>
        </div>
        <div className="metrics-grid">
          {items.map((m, i) => (
            <div className="mcard" key={i}>
              <div className="mcard-lbl">
                <span>{m.l}</span>
                <span className="mcard-tag">{m.tag}</span>
              </div>
              <div className={`mcard-val ${m.cls || ''}`}>
                {m.raw ? m.raw : (
                  <>
                    {m.prefix || ''}<Counter value={m.v} decimals={m.d} />
                    {m.u && <span className="u">{m.u}</span>}
                  </>
                )}
              </div>
              <div className="mcard-note">{m.note}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function SignatureGraphic() {
  const sigRef = React.useRef(null);
  React.useEffect(() => {
    const node = sigRef.current;
    if (!node) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { node.classList.add('in'); io.disconnect(); }
    }, { threshold: 0.35 });
    io.observe(node);
    return () => io.disconnect();
  }, []);

  // Real trade — AAVEUSDT long, 18 Apr 2026 18:36 UTC
  // L1 18:36:53 @ $105.54 · L2 18:40:50 @ $103.03 · L3 18:42:45 @ $99.54 · Exit 18:45:03 @ $102.70
  const W = 1000, H = 260, PL = 56, PR = 80, PT = 30, PB = 42;
  const tMax = 8.5, pMin = 98, pMax = 107;
  const x = (t) => PL + (t / tMax) * (W - PL - PR);
  const y = (p) => PT + ((pMax - p) / (pMax - pMin)) * (H - PT - PB);
  const entries = [
    { t: 0,    p: 105.54, label: 'L1' },
    { t: 3.95, p: 103.03, label: 'L2' },
    { t: 5.87, p: 99.54,  label: 'L3' },
  ];
  const exit = { t: 8.17, p: 102.70 };
  const wap = 102.36;
  const path = `M ${x(entries[0].t)} ${y(entries[0].p)} L ${x(entries[1].t)} ${y(entries[1].p)} L ${x(entries[2].t)} ${y(entries[2].p)} L ${x(exit.t)} ${y(exit.p)}`;
  const tri = (cx, cy, dir = 'down') => dir === 'down'
    ? `${cx},${cy + 9} ${cx + 8},${cy - 5} ${cx - 8},${cy - 5}`
    : `${cx},${cy - 9} ${cx + 8},${cy + 5} ${cx - 8},${cy + 5}`;

  return (
    <div className="sig" ref={sigRef}>
      <div className="sig-head">
        <span className="sig-head-l">
          <img className="sig-logo" src="https://cryptologos.cc/logos/aave-aave-logo.svg" alt="" aria-hidden="true" />
          REAL TRADE · AAVE-PERP · 18 APR 2026 · 18:36 UTC
        </span>
        <span className="sig-tag g">+0.30% · 8m 10s</span>
      </div>
      <svg className="sig-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" aria-hidden="true">
        <defs>
          <linearGradient id="sig-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </linearGradient>
        </defs>
        <g className="sig-grid">
          {[0,2,4,6,8].map(t => <line key={`v${t}`} x1={x(t)} y1={PT} x2={x(t)} y2={H-PB} />)}
          {[100,102,104,106].map(p => <line key={`h${p}`} x1={PL} y1={y(p)} x2={W-PR} y2={y(p)} />)}
        </g>
        <line className="sig-fair" x1={PL} y1={y(wap)} x2={W-PR} y2={y(wap)} stroke="currentColor" />
        <path className="sig-price" d={path} />
        {entries.map((e, i) => (
          <g key={i} className={`sig-marker-g m${i+1}`}>
            <polygon className="sig-marker" points={tri(x(e.t), y(e.p), 'up')} />
            <text className="sig-label entry" x={x(e.t) + 12} y={y(e.p) + 4}>{e.label} ${e.p.toFixed(2)}</text>
          </g>
        ))}
        <g className="sig-marker-g m4">
          <polygon className="sig-marker exit" points={tri(x(exit.t), y(exit.p), 'down')} />
          <text className="sig-label rev" x={x(exit.t) - 12} y={y(exit.p) + 4} textAnchor="end">EXIT ${exit.p.toFixed(2)}</text>
        </g>
        <text className="sig-label fair" x={W - PR - 6} y={y(wap) - 6} textAnchor="end">WAP ${wap.toFixed(2)}</text>
        {[100,102,104,106].map(p => (
          <text key={p} className="sig-axis" x={PL - 8} y={y(p) + 3} textAnchor="end">{p}</text>
        ))}
        {[0,2,4,6,8].map(t => (
          <text key={t} className="sig-axis" x={x(t)} y={H - PB + 18} textAnchor="middle">{t}m</text>
        ))}
      </svg>
      <div className="sig-foot">
        <span>INSTRUMENT<b>AAVE-PERP</b></span>
        <span>WINDOW<b>8m 10s</b></span>
        <span>LAYERS<b>3 tranches</b></span>
        <span>RETURN<b className="g">+0.30%</b></span>
      </div>
    </div>
  );
}

function RecentEvents() {
  const stats = [
    { k: 'EVENTS',  v: '234' },
    { k: 'WINS',    v: '233', tone: 'g' },
    { k: 'LOSS',    v: '1',   tone: 'r' },
    { k: 'POS. DAYS',  v: '26/27', tone: 'g' },
    { k: 'WITHIN RISK', v: '100%', tone: 'g' },
  ];
  return (
    <div className="evrail">
      <div className="evrail-row">
        <span className="evrail-period">EXECUTION · APR 2026</span>
        <div className="evrail-stats">
          {stats.map((s, i) => (
            <span className="evrail-stat" key={i}>
              <span className="evrail-k">{s.k}</span>
              <span className={`evrail-v ${s.tone || ''}`}>{s.v}</span>
            </span>
          ))}
        </div>
      </div>
      <div className="evrail-foot">Trade-level detail available under NDA to qualified allocators.</div>
    </div>
  );
}

function Strategy() {
  const facts = [
    { n: '01', h: 'Counter-trend edge', b: 'We trade against forced-flow dislocations — short-term price deviations driven by leverage imbalances, liquidation cascades, and reactive crowd flow.' },
    { n: '02', h: 'Fully automated', b: 'Zero discretion. In-house bot infrastructure executes, monitors, and risk-manages every position end-to-end with no manual intervention required.' },
    { n: '03', h: 'Dynamic market-neutral', b: 'Long and short exposure adapts to flow conditions in real time. The system hedges when required and stands down entirely when edge conditions are absent.' },
    { n: '04', h: 'Execution discipline', b: 'Edge comes from frequency, structure, and flow gating — not directional bets. We optimize for process, not prediction. 566 trades in Q1 2026 alone, 16 of 16 months positive across the track record.' },
  ];
  return (
    <section className="section" id="strategy">
      <div className="shell">
        <div className="sec-head reveal">
          <div className="sec-label">02 / STRATEGY</div>
          <h2 className="sec-title">We don't predict markets — <em>we react</em> to forced-flow dislocations.</h2>
        </div>

        <SignatureGraphic />
        <RecentEvents />

        <div className="strat-mech">
          <div className="strat-mech-l">
            <div className="sec-label">MECHANICS</div>
            <h3 className="strat-mech-h">Four pillars <em>of the edge</em>.</h3>
            <p className="strat-mech-p">
              Highstake captures structural inefficiencies created by forced flows,
              leverage imbalances, and crowd positioning across perpetual futures markets.
            </p>
            <p className="strat-mech-p">
              The strategy compounds because each trade is a process, not a prediction —
              executed by proprietary infrastructure with zero discretion.
            </p>
          </div>
          <div className="strat-mech-r">
            {facts.map((f, i) => (
              <div key={i} className="sfact">
                <div className="sfact-n">{f.n}</div>
                <div className="sfact-body">
                  <h4 className="sfact-h">{f.h}</h4>
                  <p className="sfact-p">{f.b}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="strat-footer">
          <span className="sf-group">
            <span className="sf-k">VENUES</span>
            <span className="venue-pills">
              {[
                { name: 'Binance', logo: 'https://assets.coingecko.com/markets/images/52/small/binance.jpg' },
                { name: 'Bybit',   logo: 'https://assets.coingecko.com/markets/images/698/small/bybit_spot.png' },
                { name: 'Hyperliquid', logo: 'https://assets.coingecko.com/coins/images/50882/small/hyperliquid.jpg' },
              ].map(v => (
                <span className="vpill" key={v.name}>
                  <img src={v.logo} alt="" aria-hidden="true" onError={(e)=>{e.target.style.display='none';}} />
                  {v.name}
                </span>
              ))}
            </span>
          </span>
          <span className="sf-group">
            <span className="sf-k">DENOMINATION</span>
            <span className="denom-pills">
              {[
                { sym: 'USDT', logo: 'https://assets.coingecko.com/coins/images/325/small/Tether.png' },
                { sym: 'BTC',  logo: 'https://assets.coingecko.com/coins/images/1/small/bitcoin.png' },
                { sym: 'ETH',  logo: 'https://assets.coingecko.com/coins/images/279/small/ethereum.png' },
              ].map(d => (
                <span className="dpill" key={d.sym}>
                  <img src={d.logo} alt="" aria-hidden="true" onError={(e)=>{e.target.style.display='none';}} />
                  {d.sym}
                </span>
              ))}
            </span>
          </span>
          <span className="sf-group">
            <span className="sf-k">PER SMA</span>
            <span className="sf-v">~$5M capacity</span>
          </span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Metrics, Strategy, Logo, HeroCanvas, SignatureGraphic, RecentEvents });
