// chart.jsx — original crashing-candle chart on canvas
// Generates plausible candle data that trends down hard. Animates "live" tick.

function CrashChart({ severity = 1, running = true }) {
  const canvasRef = React.useRef(null);
  const dataRef = React.useRef(null);
  const [portfolio, setPortfolio] = React.useState(1000000);
  const tickRef = React.useRef(0);

  // generate candles
  const genCandles = React.useCallback((n) => {
    const out = [];
    let price = 100;
    for (let i = 0; i < n; i++) {
      // overall downtrend with volatility, accelerating crash near end
      const crashWeight = Math.pow(i / n, 1.7) * severity;
      const drift = -0.6 * crashWeight - 0.04;
      const vol = 1.2 + 2.5 * crashWeight;
      const open = price;
      const change = drift + (Math.random() - 0.45) * vol;
      const close = Math.max(2, open + change);
      const high = Math.max(open, close) + Math.random() * vol * 0.8;
      const low = Math.min(open, close) - Math.random() * vol * 0.8;
      out.push({ open, close, high, low: Math.max(1, low) });
      price = close;
    }
    return out;
  }, [severity]);

  React.useEffect(() => {
    dataRef.current = genCandles(60);
  }, [genCandles]);

  // animation loop: shift candles left, push new one
  React.useEffect(() => {
    if (!running) return;
    let raf;
    const tick = () => {
      tickRef.current++;
      if (tickRef.current % 10 === 0) {
        const arr = dataRef.current;
        if (arr) {
          const last = arr[arr.length - 1];
          const drift = -1.2 * severity;
          const vol = 4 * severity;
          const open = last.close;
          const close = Math.max(1, open + drift + (Math.random() - 0.5) * vol);
          const high = Math.max(open, close) + Math.random() * vol;
          const low = Math.max(0.5, Math.min(open, close) - Math.random() * vol);
          arr.shift();
          arr.push({ open, close, high, low });
          // portfolio ticks
          setPortfolio((p) => {
            const next = p - (8000 + Math.random() * 18000) * severity;
            return Math.round(next);
          });
        }
      }
      drawChart();
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [running, severity]);

  const drawChart = () => {
    const c = canvasRef.current;
    if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = c.getBoundingClientRect();
    if (c.width !== rect.width * dpr) {
      c.width = rect.width * dpr; c.height = rect.height * dpr;
    }
    const ctx = c.getContext('2d');
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    const W = rect.width, H = rect.height;
    ctx.clearRect(0, 0, W, H);

    // grid
    ctx.strokeStyle = 'oklch(0.18 0.005 30)';
    ctx.lineWidth = 1;
    for (let i = 1; i < 6; i++) {
      const y = (H / 6) * i;
      ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();
    }
    for (let i = 1; i < 8; i++) {
      const x = (W / 8) * i;
      ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke();
    }

    const data = dataRef.current || [];
    if (!data.length) return;
    let lo = Infinity, hi = -Infinity;
    for (const d of data) { if (d.low < lo) lo = d.low; if (d.high > hi) hi = d.high; }
    const pad = (hi - lo) * 0.08;
    lo -= pad; hi += pad;

    const cw = W / data.length;
    const bw = Math.max(2, cw * 0.65);
    const yOf = (p) => H - ((p - lo) / (hi - lo)) * H;

    data.forEach((d, i) => {
      const x = i * cw + cw / 2;
      const isDown = d.close <= d.open;
      const color = isDown ? 'oklch(0.58 0.22 25)' : 'oklch(0.7 0.18 145)';
      const glow  = isDown ? 'oklch(0.58 0.22 25 / 0.5)' : 'oklch(0.7 0.18 145 / 0.5)';
      // wick
      ctx.strokeStyle = color;
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, yOf(d.high));
      ctx.lineTo(x, yOf(d.low));
      ctx.stroke();
      // body
      ctx.shadowColor = glow;
      ctx.shadowBlur = 6;
      ctx.fillStyle = color;
      const top = yOf(Math.max(d.open, d.close));
      const bot = yOf(Math.min(d.open, d.close));
      ctx.fillRect(x - bw/2, top, bw, Math.max(1, bot - top));
      ctx.shadowBlur = 0;
    });

    // crash line trace overlay (last close)
    const last = data[data.length - 1];
    const yLast = yOf(last.close);
    ctx.strokeStyle = 'oklch(0.58 0.22 25 / 0.8)';
    ctx.setLineDash([4, 4]);
    ctx.beginPath();
    ctx.moveTo(0, yLast); ctx.lineTo(W, yLast);
    ctx.stroke();
    ctx.setLineDash([]);

    // price tag
    ctx.fillStyle = 'oklch(0.05 0 0)';
    ctx.fillRect(W - 70, yLast - 10, 66, 20);
    ctx.strokeStyle = 'oklch(0.58 0.22 25)';
    ctx.strokeRect(W - 70, yLast - 10, 66, 20);
    ctx.fillStyle = 'oklch(0.92 0.012 80)';
    ctx.font = "12px 'VT323', monospace";
    ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
    ctx.fillText('$' + last.close.toFixed(2), W - 8, yLast);
  };

  React.useEffect(() => { drawChart(); }, []);

  const fmt = (n) => {
    const abs = Math.abs(n);
    const s = abs.toLocaleString('en-US');
    return n < 0 ? '-$' + s : '$' + s;
  };
  const initial = 1000000;
  const delta = portfolio - initial;
  const pct = ((delta / initial) * 100).toFixed(2);

  return (
    <div className="crt-frame">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '0 4px 10px', fontFamily: "'Press Start 2P', monospace", fontSize: 8, color: 'var(--ink-dim)', letterSpacing: '0.08em' }}>
        <span>$RESTART / USD &nbsp; LIVE</span>
        <span style={{ color: 'var(--red-glow)' }} className="blink">REC ●</span>
      </div>
      <canvas ref={canvasRef} className="chart-canvas"></canvas>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 14 }}>
        <div className="portfolio-card" style={{ border: 'none', padding: '4px 6px', background: 'transparent' }}>
          <div className="label">PORTFOLIO</div>
          <div className="value tabular" style={{ fontSize: 28 }}>{fmt(portfolio)}</div>
        </div>
        <div className="portfolio-card" style={{ border: 'none', padding: '4px 6px', background: 'transparent', textAlign: 'right' }}>
          <div className="label">SINCE ENTRY</div>
          <div className="value tabular" style={{ fontSize: 28 }}>{pct}%</div>
        </div>
      </div>
      <div className="led"></div>
      <div className="label-tag">DOOMER-CRT 14"</div>
    </div>
  );
}

window.CrashChart = CrashChart;
