// Ambient market microstructure visualization for the hero.
// Renders order-book depth, price discovery line, and liquidity heat
// on a canvas. Driven by a deterministic-feeling random walk.

const MarketField = ({ height = 520, density = 1, paused = false }) => {
  const canvasRef = React.useRef(null);
  const stateRef = React.useRef(null);
  const [resizeKey, setResizeKey] = React.useState(0);

  React.useEffect(() => {
    const onResize = () => setResizeKey(k => k + 1);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    const parent = canvas.parentElement;
    const w = parent.clientWidth;
    const h = height;
    canvas.width = w * dpr;
    canvas.height = h * dpr;
    canvas.style.width = w + 'px';
    canvas.style.height = h + 'px';
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);

    // Initialize price walk
    const N = 280;
    const prices = new Array(N).fill(0).map((_, i) => 100 + Math.sin(i * 0.07) * 4 + Math.cos(i * 0.13) * 2);
    let t = 0;
    let raf;

    const getCSS = (v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim();

    const draw = () => {
      const ink = getCSS('--ink');
      const ink3 = getCSS('--ink-3');
      const ink4 = getCSS('--ink-4');
      const accent = getCSS('--accent');
      const hairline = getCSS('--hairline');
      const isDark = document.documentElement.dataset.theme === 'dark';

      ctx.clearRect(0, 0, w, h);

      // Grid
      ctx.strokeStyle = hairline;
      ctx.lineWidth = 1;
      const gridX = 12;
      const gridY = 8;
      for (let i = 0; i <= gridX; i++) {
        const x = (w / gridX) * i;
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();
      }
      for (let i = 0; i <= gridY; i++) {
        const y = (h / gridY) * i;
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke();
      }

      // Update prices
      if (!paused) {
        prices.shift();
        const last = prices[prices.length - 1];
        const drift = Math.sin(t * 0.012) * 0.04;
        const noise = (Math.random() - 0.5) * 0.6;
        prices.push(last + drift + noise);
        t++;
      }

      const minP = Math.min(...prices);
      const maxP = Math.max(...prices);
      const range = (maxP - minP) || 1;
      const padY = 80;

      const xAt = (i) => (i / (N - 1)) * w;
      const yAt = (p) => padY + (1 - (p - minP) / range) * (h - 2 * padY);

      // Liquidity heat (vertical bars below price)
      for (let i = 0; i < N; i += 2) {
        const x = xAt(i);
        const intensity = (Math.sin(i * 0.21 + t * 0.02) * 0.5 + 0.5) * (Math.cos(i * 0.07) * 0.3 + 0.7);
        const barH = intensity * 14 * density;
        ctx.fillStyle = isDark
          ? `rgba(240,236,226,${0.04 + intensity * 0.06})`
          : `rgba(28,27,24,${0.03 + intensity * 0.05})`;
        ctx.fillRect(x - 1, h - padY * 0.6 - barH, 2, barH);
      }

      // Order book depth — left side bids, right side asks (faint mirrored bars)
      ctx.save();
      for (let i = 0; i < 30; i++) {
        const yA = padY + (i / 30) * (h - 2 * padY);
        const w1 = (Math.sin(i * 0.4 + t * 0.01) * 0.5 + 0.5) * 60 + 10;
        const w2 = (Math.cos(i * 0.5 + t * 0.012) * 0.5 + 0.5) * 60 + 10;
        ctx.fillStyle = isDark ? 'rgba(240,236,226,0.05)' : 'rgba(28,27,24,0.04)';
        ctx.fillRect(0, yA, w1, 1.2);
        ctx.fillRect(w - w2, yA, w2, 1.2);
      }
      ctx.restore();

      // Faint moving average (background)
      ctx.strokeStyle = ink4;
      ctx.lineWidth = 1;
      ctx.beginPath();
      const window_ = 20;
      for (let i = window_; i < N; i++) {
        let sum = 0;
        for (let j = i - window_; j < i; j++) sum += prices[j];
        const avg = sum / window_;
        const x = xAt(i);
        const y = yAt(avg);
        if (i === window_) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
      }
      ctx.stroke();

      // Main price line
      ctx.strokeStyle = ink;
      ctx.lineWidth = 1.4;
      ctx.beginPath();
      for (let i = 0; i < N; i++) {
        const x = xAt(i);
        const y = yAt(prices[i]);
        if (i === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
      }
      ctx.stroke();

      // Last-price marker
      const lastX = xAt(N - 1);
      const lastY = yAt(prices[N - 1]);
      ctx.fillStyle = accent;
      ctx.beginPath();
      ctx.arc(lastX, lastY, 3, 0, Math.PI * 2);
      ctx.fill();
      ctx.strokeStyle = accent;
      ctx.setLineDash([2, 4]);
      ctx.lineWidth = 0.8;
      ctx.beginPath();
      ctx.moveTo(0, lastY); ctx.lineTo(w, lastY);
      ctx.stroke();
      ctx.setLineDash([]);

      // Axis labels (right)
      ctx.fillStyle = ink3;
      ctx.font = '10px JetBrains Mono, monospace';
      ctx.textAlign = 'right';
      for (let i = 0; i < 5; i++) {
        const p = minP + (range * (4 - i)) / 4;
        const y = yAt(p);
        ctx.fillText(p.toFixed(2), w - 8, y - 4);
      }
      // last price label
      ctx.fillStyle = accent;
      ctx.fillText(prices[N - 1].toFixed(4), w - 8, lastY - 6);

      raf = requestAnimationFrame(draw);
    };

    draw();
    return () => cancelAnimationFrame(raf);
  }, [resizeKey, height, density, paused]);

  return (
    <div style={{ position: 'relative', width: '100%', height }}>
      <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
    </div>
  );
};

window.MarketField = MarketField;
