import { useEffect, useRef } from 'react';
import { useWebSocket } from '../../hooks/useWebSocket';

// Full matrix alphabet: katakana + hex + braille dots for visual density
const KATAKANA =
  'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン';
const HEX = '0123456789ABCDEFabcdef';
const SYMBOLS = '!@#$%^&*<>/?|\\~';
const ALPHABET = KATAKANA + HEX + SYMBOLS;

const FONT_SIZE = 10;

interface Column {
  y: number;
  speed: number;
  // occasionally carry a char from live data
  liveSrc: string;
  livePos: number;
}

export default function MatrixRain() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);
  const { agents, recentShares, commandResults } = useWebSocket();

  // ── Live data pool ──────────────────────────────────────────────────────────
  // Collect strings from the fleet that will be injected character-by-character
  // into the rain columns so real data scrolls through the matrix.
  const livePoolRef = useRef<string[]>([]);
  useEffect(() => {
    const pool: string[] = [];
    for (const a of agents) {
      pool.push(a.id.replace(/-/g, ''));               // stripped UUID
      if (a.hashrate_15s > 0) pool.push(`${a.hashrate_15s.toFixed(0)}H`);
      if (a.ip) pool.push(a.ip.replace(/\./g, ''));
    }
    for (const s of recentShares.slice(0, 8)) {
      if (s.hash) pool.push(s.hash.replace(/[^a-fA-F0-9]/g, '').slice(0, 24));
    }
    for (const r of (commandResults ?? []).slice(-5)) {
      if (r.action) pool.push(r.action.toUpperCase().padEnd(8, '_'));
    }
    livePoolRef.current = pool.length > 0 ? pool : ['AETHERFORGE', 'MINING', '00E5FF'];
  }, [agents, recentShares, commandResults]);

  // ── Event log feed ──────────────────────────────────────────────────────────
  // We inject one short log line per meaningful event, shown as a dim overlay
  // row scrolling through the canvas.
  const eventLogRef = useRef<{ text: string; alpha: number }[]>([]);
  const prevShareLen = useRef(0);
  const prevAgentLen = useRef(0);
  useEffect(() => {
    const newEvents: string[] = [];
    if (recentShares.length > prevShareLen.current) {
      const s = recentShares[0];
      newEvents.push(`SHARE ${s.accepted ? 'OK' : 'REJECT'} ${s.agent_id?.slice(0, 6) ?? '??'}`);
    }
    prevShareLen.current = recentShares.length;
    if (agents.length > prevAgentLen.current) {
      const a = agents[agents.length - 1];
      newEvents.push(`AGENT ONLINE ${a.name?.slice(0, 8) ?? '??'}`);
    }
    prevAgentLen.current = agents.length;
    for (const ev of newEvents) {
      eventLogRef.current.push({ text: ev, alpha: 1 });
      if (eventLogRef.current.length > 6) eventLogRef.current.shift();
    }
  }, [recentShares, agents]);

  // ── Canvas renderer ─────────────────────────────────────────────────────────
  useEffect(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // Resize canvas to match wrapper
    const resize = () => {
      const r = wrap.getBoundingClientRect();
      canvas.width = Math.floor(r.width);
      canvas.height = Math.floor(r.height);
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(wrap);

    let cols: Column[] = [];
    const resetCols = () => {
      const numCols = Math.max(1, Math.floor(canvas.width / FONT_SIZE));
      cols = Array.from({ length: numCols }, (_, i) => ({
        y: Math.random() * -(canvas.height * 2),
        speed: 0.3 + Math.random() * 0.55,
        liveSrc: '',
        livePos: 0,
      }));
    };
    resetCols();

    // Periodically inject live data strings into random columns
    const injectInterval = setInterval(() => {
      const pool = livePoolRef.current;
      if (pool.length === 0 || cols.length === 0) return;
      const colIdx = Math.floor(Math.random() * cols.length);
      const src = pool[Math.floor(Math.random() * pool.length)];
      cols[colIdx].liveSrc = src;
      cols[colIdx].livePos = 0;
    }, 180);

    let raf: number;
    let lastTime = 0;
    const FPS = 24; // keep CPU gentle
    const MS_PER_FRAME = 1000 / FPS;

    const draw = (ts: number) => {
      raf = requestAnimationFrame(draw);
      if (ts - lastTime < MS_PER_FRAME) return;
      lastTime = ts;

      const W = canvas.width;
      const H = canvas.height;

      // Fade trail
      ctx.fillStyle = 'rgba(0,0,0,0.18)';
      ctx.fillRect(0, 0, W, H);

      ctx.font = `${FONT_SIZE}px 'Courier New', monospace`;

      for (let i = 0; i < cols.length; i++) {
        const col = cols[i];
        const x = i * FONT_SIZE;
        const y = col.y;

        // Pick character: live data char or random alphabet
        let ch: string;
        if (col.liveSrc && col.livePos < col.liveSrc.length) {
          ch = col.liveSrc[col.livePos];
          col.livePos++;
        } else {
          ch = ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
        }

        // Head character — bright white flash
        ctx.fillStyle = 'rgba(255,255,255,0.95)';
        ctx.fillText(ch, x, y * FONT_SIZE);

        // Second char — bright cyan-green (neon)
        if (y > 1) {
          ctx.fillStyle = '#00ff41';
          ctx.fillText(
            ALPHABET[Math.floor(Math.random() * ALPHABET.length)],
            x,
            (y - 1) * FONT_SIZE,
          );
        }

        // Dim previous chars handled by fade overlay above.
        // Occasionally render a mid-column dim glyph for density.
        if (Math.random() < 0.04) {
          const dimY = Math.floor(Math.random() * (y - 2));
          ctx.fillStyle = 'rgba(0,180,60,0.22)';
          ctx.fillText(
            ALPHABET[Math.floor(Math.random() * ALPHABET.length)],
            x,
            dimY * FONT_SIZE,
          );
        }

        col.y += col.speed;
        if (col.y * FONT_SIZE > H && Math.random() > 0.96) {
          col.y = Math.random() * -20;
          col.speed = 0.3 + Math.random() * 0.55;
          col.liveSrc = '';
          col.livePos = 0;
        }
      }

      // ── Event log overlay — bottom of canvas ──────────────────────────
      const logs = eventLogRef.current;
      const lineH = FONT_SIZE + 2;
      ctx.font = `${FONT_SIZE - 1}px 'Courier New', monospace`;
      for (let j = 0; j < logs.length; j++) {
        const entry = logs[logs.length - 1 - j];
        const oy = H - 6 - j * lineH;
        if (oy < 0) break;
        ctx.fillStyle = `rgba(0,255,65,${(entry.alpha * 0.55).toFixed(2)})`;
        ctx.fillText(`> ${entry.text}`, 4, oy);
        // fade over time
        entry.alpha = Math.max(0, entry.alpha - 0.003);
      }
    };

    raf = requestAnimationFrame(draw);

    return () => {
      cancelAnimationFrame(raf);
      clearInterval(injectInterval);
      ro.disconnect();
    };
  }, []);

  return (
    <div ref={wrapRef} className="matrix-rain-wrap" aria-hidden="true">
      <canvas ref={canvasRef} className="matrix-rain-canvas" />
      {/* Scanline overlay for authentic CRT feel */}
      <div className="matrix-rain-scanlines" />
      {/* Top and bottom vignette fades */}
      <div className="matrix-rain-vignette-top" />
      <div className="matrix-rain-vignette-btm" />
    </div>
  );
}
