// Chart component — Highstake vs BTC vs S&P 500 — combined cumulative + monthly bars
const { useMemo, useState, useEffect, useRef, useCallback } = React;

function Chart() {
  const W = 1040, H = 340;
  const P = { l: 44, r: 60, t: 24, b: 36 };
  const data = window.HS_DATA;
  const n = data.cumulative.length; // 17 (includes leading 0)
  const N = n - 1; // 16 months
  const labels = ["J","F","M","A","M","J","J","A","S","O","N","D","J","F","M","A"];
  const months = ["Jan '25","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan '26","Feb","Mar","Apr"];

  const [progress, setProgress] = useState(0);
  const [hover, setHover] = useState(null);
  const [mode, setMode] = useState('combined'); // 'combined' | 'drawdown'
  const svgRef = useRef(null);
  const wrapRef = useRef(null);

  const monthlyVals = data.monthly.map(m => m.v);
  const drawdown = useMemo(() => {
    const out = [];
    let peak = 0;
    for (let i = 1; i < data.cumulative.length; i++) {
      const v = data.cumulative[i];
      if (v > peak) peak = v;
      out.push(-(peak - v));
    }
    return out;
  }, []);

  // Primary (left) axis config
  const config = useMemo(() => {
    if (mode === 'drawdown') {
      return { minY: -8, maxY: 1, ticks: [0,-2,-4,-6,-8], suffix: '%' };
    }
    return { minY: -35, maxY: 140, ticks: [-30,0,30,60,90,120], suffix: '%' };
  }, [mode]);

  // Secondary (right) axis — monthly bars 0..8%
  const barMax = 8;
  const barTicks = [0, 2, 4, 6, 8];

  const yScale = useCallback((v) => P.t + (H - P.t - P.b) * (1 - (v - config.minY) / (config.maxY - config.minY)), [config]);
  const yScaleR = useCallback((v) => P.t + (H - P.t - P.b) * (1 - v / barMax), []);
  const xScale = useCallback((i) => P.l + (W - P.l - P.r) * (i / (N - 1)), [N]);

  useEffect(() => {
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        let t0 = null;
        const step = (t) => {
          if (!t0) t0 = t;
          const p = Math.min(1, (t - t0) / 1800);
          setProgress(p < 1 ? 1 - Math.pow(1 - p, 3) : 1);
          if (p < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
        io.disconnect();
      }
    }, { threshold: 0.2 });
    if (wrapRef.current) io.observe(wrapRef.current);
    return () => io.disconnect();
  }, []);

  const handleMouseMove = useCallback((e) => {
    if (!svgRef.current) return;
    const rect = svgRef.current.getBoundingClientRect();
    const mx = (e.clientX - rect.left) * (W / rect.width);
    let best = 0, bestDist = Infinity;
    for (let i = 0; i < N; i++) {
      const d = Math.abs(mx - xScale(i));
      if (d < bestDist) { bestDist = d; best = i; }
    }
    const val = mode === 'drawdown' ? drawdown[best] : data.cumulative[best + 1];
    setHover({ idx: best, x: xScale(best), y: yScale(val) });
  }, [mode, xScale, yScale, drawdown]);

  const handleMouseLeave = useCallback(() => setHover(null), []);

  const pathHS = useMemo(() => {
    if (mode !== 'combined') return '';
    const pts = data.cumulative.slice(1).map((v, i) => [xScale(i), yScale(v)]);
    return "M " + pts.map(p => p.join(",")).join(" L ");
  }, [mode, yScale, xScale]);
  const areaHS = mode === 'combined' ? pathHS + ` L ${xScale(N - 1)},${yScale(config.minY)} L ${xScale(0)},${yScale(config.minY)} Z` : '';
  const pathSP = useMemo(() => {
    if (mode !== 'combined') return '';
    const pts = data.sp500Cum.slice(1).map((v, i) => [xScale(i), yScale(v)]);
    return "M " + pts.map(p => p.join(",")).join(" L ");
  }, [mode, yScale, xScale]);
  const pathBTC = useMemo(() => {
    if (mode !== 'combined') return '';
    const pts = data.btcCum.slice(1).map((v, i) => [xScale(i), yScale(v)]);
    return "M " + pts.map(p => p.join(",")).join(" L ");
  }, [mode, yScale, xScale]);

  const pathDD = useMemo(() => {
    if (mode !== 'drawdown') return '';
    const pts = drawdown.map((v, i) => [xScale(i), yScale(v)]);
    return "M " + pts.map(p => p.join(",")).join(" L ");
  }, [mode, yScale, xScale]);
  const areaDD = mode === 'drawdown' ? pathDD + ` L ${xScale(N - 1)},${yScale(0)} L ${xScale(0)},${yScale(0)} Z` : '';

  const barWidth = (xScale(1) - xScale(0)) * 0.5;

  return (
    <div className="chart-wrap" ref={wrapRef}>
      <div className="chart-head">
        <div className="chart-legend">
          <div className="legend-item"><span className="legend-swatch hs" /><span>HIGHSTAKE</span></div>
          {mode === 'combined' && <div className="legend-item"><span className="legend-swatch btc" /><span>BTC</span></div>}
          {mode === 'combined' && <div className="legend-item"><span className="legend-swatch sp" /><span>S&P 500</span></div>}
          {mode === 'combined' && <div className="legend-item"><span className="legend-swatch bars" /><span>MONTHLY %</span></div>}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <span className="cmd"><span className="caret">›</span> 16-month window · net strategy returns · before perf. fee</span>
          <div className="chart-tabs">
            {[['combined','PERFORMANCE'],['drawdown','DRAWDOWN']].map(([m, label]) => (
              <button key={m} className={`chart-tab ${mode === m ? 'active' : ''}`} onClick={() => { setMode(m); setHover(null); }}>{label}</button>
            ))}
          </div>
        </div>
      </div>

      <svg
        ref={svgRef}
        viewBox={`0 0 ${W} ${H}`}
        className="chart-svg"
        style={{ overflow: 'visible' }}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
      >
        <defs>
          <linearGradient id="hsfill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.18" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </linearGradient>
          <linearGradient id="ddfill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="var(--red)" stopOpacity="0" />
            <stop offset="100%" stopColor="var(--red)" stopOpacity="0.18" />
          </linearGradient>
          <clipPath id="revealHS">
            <rect x="0" y="0" width={W * progress} height={H} />
          </clipPath>
          <filter id="glow">
            <feGaussianBlur stdDeviation="2" result="blur" />
            <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
        </defs>

        {/* Left axis (cumulative or drawdown) */}
        {config.ticks.map((t) => (
          <g key={t}>
            <line x1={P.l} x2={W - P.r} y1={yScale(t)} y2={yScale(t)} stroke="var(--line)" strokeWidth="1" strokeDasharray={t === 0 ? "" : "2,4"} />
            <text x={P.l - 10} y={yScale(t) + 3} fill="var(--fg-3)" fontSize="9" fontFamily="JetBrains Mono" textAnchor="end">{t}{config.suffix}</text>
          </g>
        ))}

        {/* Right axis (monthly bars) — only in combined mode */}
        {mode === 'combined' && barTicks.map((t) => (
          <text key={`r-${t}`} x={W - P.r + 8} y={yScaleR(t) + 3} fill="var(--fg-3)" fontSize="9" fontFamily="JetBrains Mono" textAnchor="start" opacity="0.6">{t}%</text>
        ))}

        {labels.map((l, i) => (
          <text key={i} x={xScale(i)} y={H - 12} fill="var(--fg-3)" fontSize="9" fontFamily="JetBrains Mono" textAnchor="middle">{l}</text>
        ))}
        <text x={xScale(5.5)} y={H - 1} fill="var(--fg-3)" fontSize="8" fontFamily="JetBrains Mono" textAnchor="middle" letterSpacing="0.1em">2025</text>
        <text x={xScale(13.5)} y={H - 1} fill="var(--fg-3)" fontSize="8" fontFamily="JetBrains Mono" textAnchor="middle" letterSpacing="0.1em">'26</text>

        <g clipPath="url(#revealHS)">
          {mode === 'combined' && (
            <>
              {/* Monthly bars (background) */}
              {monthlyVals.map((v, i) => {
                const y = yScaleR(v);
                const y0 = yScaleR(0);
                const isHover = hover?.idx === i;
                return (
                  <rect key={`bar-${i}`}
                    x={xScale(i) - barWidth / 2}
                    y={y}
                    width={barWidth}
                    height={Math.max(0, y0 - y)}
                    fill="var(--accent)"
                    opacity={isHover ? 0.32 : 0.14}
                    rx="1"
                  />
                );
              })}
              {/* Cumulative area + lines (foreground) */}
              <path d={areaHS} fill="url(#hsfill)" />
              <path d={pathBTC} fill="none" stroke="#fbbf24" strokeWidth="1.4" strokeDasharray="5,3" opacity="0.85" />
              <path d={pathSP} fill="none" stroke="var(--fg-3)" strokeWidth="1.4" strokeDasharray="3,4" />
              <path d={pathHS} fill="none" stroke="var(--accent)" strokeWidth="2" filter="url(#glow)" />
              {data.cumulative.slice(1).map((v, i) => (
                <circle key={i} cx={xScale(i)} cy={yScale(v)} r={hover?.idx === i ? 4 : 2}
                  fill={hover?.idx === i ? "var(--accent)" : "var(--bg-2)"}
                  stroke="var(--accent)" strokeWidth="1.5" />
              ))}
            </>
          )}
          {mode === 'drawdown' && (
            <>
              <path d={areaDD} fill="url(#ddfill)" />
              <path d={pathDD} fill="none" stroke="var(--red)" strokeWidth="1.8" />
              {drawdown.map((v, i) => (
                <circle key={i} cx={xScale(i)} cy={yScale(v)} r={hover?.idx === i ? 4 : 2}
                  fill={hover?.idx === i ? "var(--red)" : "var(--bg-2)"}
                  stroke="var(--red)" strokeWidth="1.5" />
              ))}
            </>
          )}
        </g>

        {hover && (() => {
          const isCombined = mode === 'combined';
          const isDD = mode === 'drawdown';
          const color = isDD ? "var(--red)" : "var(--accent)";
          const primary = isCombined ? data.cumulative[hover.idx + 1] : drawdown[hover.idx];
          const sign = primary > 0 ? '+' : '';
          const tipW = 158, tipH = isCombined ? 88 : 46;
          const tx = Math.min(hover.x + 10, W - tipW - 4);
          const ty = Math.max(hover.y - tipH - 4, P.t);
          return (
            <g>
              <line x1={hover.x} x2={hover.x} y1={P.t} y2={H - P.b} stroke={color} strokeWidth="1" strokeDasharray="3,3" opacity="0.7" />
              <line x1={P.l} x2={W - P.r} y1={hover.y} y2={hover.y} stroke={color} strokeWidth="1" strokeDasharray="3,3" opacity="0.35" />
              <g transform={`translate(${tx}, ${ty})`}>
                <rect x="0" y="0" width={tipW} height={tipH} rx="4" fill="var(--bg)" stroke="var(--line-hi)" strokeWidth="1" />
                <text x="10" y="16" fill="var(--fg-3)" fontSize="9" fontFamily="JetBrains Mono" letterSpacing="0.08em">{months[hover.idx].toUpperCase()}</text>
                <text x="10" y="34" fill={color} fontSize="15" fontFamily="Instrument Serif" fontStyle="italic">{isDD ? 'DD' : 'HS'}: {sign}{primary.toFixed(2)}%</text>
                {isCombined && <text x="10" y="50" fill="var(--accent)" fontSize="10" fontFamily="JetBrains Mono" opacity="0.85">MONTH: +{monthlyVals[hover.idx].toFixed(2)}%</text>}
                {isCombined && <text x="10" y="64" fill="#fbbf24" fontSize="10" fontFamily="JetBrains Mono">BTC: {data.btcCum[hover.idx + 1] >= 0 ? '+' : ''}{data.btcCum[hover.idx + 1].toFixed(1)}%</text>}
                {isCombined && <text x="10" y="78" fill="var(--fg-3)" fontSize="10" fontFamily="JetBrains Mono">SP: {data.sp500Cum[hover.idx + 1] >= 0 ? '+' : ''}{data.sp500Cum[hover.idx + 1].toFixed(1)}%</text>}
              </g>
            </g>
          );
        })()}

        {mode === 'combined' && progress > 0.8 && !hover && (
          <>
            <g transform={`translate(${xScale(N - 1) + 8}, ${yScale(data.cumulative[n - 1])})`}>
              <text fill="var(--accent)" fontSize="11" fontFamily="Instrument Serif" fontStyle="italic">+{data.cumulative[n - 1].toFixed(2)}%</text>
            </g>
            <g transform={`translate(${xScale(N - 1) + 8}, ${yScale(data.sp500Cum[n - 1]) + 4})`}>
              <text fill="var(--fg-3)" fontSize="10" fontFamily="JetBrains Mono">+{data.sp500Cum[n - 1].toFixed(1)}%</text>
            </g>
            <g transform={`translate(${xScale(N - 1) + 8}, ${yScale(data.btcCum[n - 1]) + 4})`}>
              <text fill="#fbbf24" fontSize="10" fontFamily="JetBrains Mono">{data.btcCum[n - 1].toFixed(1)}%</text>
            </g>
          </>
        )}
      </svg>

      <div className="chart-footer">
        <div>
          <div className="chart-stat-label">{mode === 'drawdown' ? 'Max Drawdown' : 'Alpha vs S&P 500'}</div>
          <div className="chart-stat-value">
            {mode === 'drawdown' ? <>−{Math.abs(Math.min(...drawdown)).toFixed(2)}<span style={{ color: 'var(--fg-3)', fontSize: 15 }}>%</span></> : <>+{(data.cumulative[n-1] - data.sp500Cum[n-1]).toFixed(2)}<span style={{ color: 'var(--fg-3)', fontSize: 15 }}>pp</span></>}
          </div>
        </div>
        <div>
          <div className="chart-stat-label">Avg Monthly</div>
          <div className="chart-stat-value">{(monthlyVals.reduce((a,b)=>a+b,0)/monthlyVals.length).toFixed(2)}<span style={{ color: 'var(--fg-3)', fontSize: 15 }}>%</span></div>
        </div>
        <div>
          <div className="chart-stat-label">Positive Months</div>
          <div className="chart-stat-value">16<span style={{ color: 'var(--fg-3)', fontSize: 15 }}>/16</span></div>
        </div>
      </div>
    </div>
  );
}

window.Chart = Chart;
