"use client";

import * as React from "react";

/**
 * AbstractCircuit: Premium Canvas Binary Data Flow
 *
 * - Binary 0/1 characters flow in structured horizontal lanes
 * - Vertical cross-traffic for depth
 * - Characters "breathe" with sine-wave opacity
 * - High performance: uses requestAnimationFrame, minimal allocations per frame
 */

interface Char {
  x: number;
  y: number;
  val: number; // 0 or 1
  speed: number; // px per frame
  vertical: boolean;
  size: number;
  baseAlpha: number;
  phase: number; // sine-wave phase offset
  flipIn: number; // frames until next flip
}

export const AbstractCircuit: React.FC<{
  invert?: boolean;
  className?: string;
}> = ({ invert = false, className = "" }) => {
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const stateRef = React.useRef({
    chars: [] as Char[],
    frame: 0,
    dpr: 1,
    w: 0,
    h: 0,
  });

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d", { alpha: true })!;
    const s = stateRef.current;
    let raf = 0;

    // ── Sizing ──
    const resize = () => {
      s.dpr = Math.min(window.devicePixelRatio || 1, 2);
      s.w = canvas.offsetWidth;
      s.h = canvas.offsetHeight;
      canvas.width = s.w * s.dpr;
      canvas.height = s.h * s.dpr;
      seed();
    };

    // ── Seed characters ──
    const LANE = 28;
    const GAP = 20;

    const seed = () => {
      const chars: Char[] = [];
      const { w, h } = s;

      // Horizontal lanes
      for (let y = 0; y < h; y += LANE) {
        const dir = Math.floor(y / LANE) % 3 === 0 ? -1 : 1;
        const spd = (0.15 + Math.random() * 0.6) * dir;
        for (let x = 0; x < w + GAP; x += GAP) {
          if (Math.random() > 0.45) continue;
          chars.push({
            x: x + (Math.random() - 0.5) * 6,
            y: y + LANE / 2 + (Math.random() - 0.5) * 4,
            val: Math.random() > 0.5 ? 1 : 0,
            speed: spd,
            vertical: false,
            size: 9 + Math.floor(Math.random() * 2),
            baseAlpha: 0.035 + Math.random() * 0.045,
            phase: Math.random() * Math.PI * 2,
            flipIn: 120 + Math.floor(Math.random() * 400),
          });
        }
      }

      // Vertical lanes (sparser)
      for (let x = 0; x < w; x += LANE * 2.5) {
        const dir = Math.floor(x / LANE) % 2 === 0 ? 1 : -1;
        const spd = (0.1 + Math.random() * 0.4) * dir;
        for (let y = 0; y < h + GAP; y += GAP) {
          if (Math.random() > 0.3) continue;
          chars.push({
            x: x + (Math.random() - 0.5) * 4,
            y: y + (Math.random() - 0.5) * 6,
            val: Math.random() > 0.5 ? 1 : 0,
            speed: spd,
            vertical: true,
            size: 8 + Math.floor(Math.random() * 2),
            baseAlpha: 0.025 + Math.random() * 0.035,
            phase: Math.random() * Math.PI * 2,
            flipIn: 150 + Math.floor(Math.random() * 500),
          });
        }
      }
      s.chars = chars;
    };

    // ── Mouse tracking — use canvas-relative coordinates ──

    // ── Render loop ──
    const render = () => {
      const { w, h, dpr, chars } = s;
      s.frame++;

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

      const t = s.frame * 0.02; // global time

      // ── Draw characters ──
      for (let i = 0, len = chars.length; i < len; i++) {
        const c = chars[i];

        // Move
        if (c.vertical) {
          c.y += c.speed;
          if (c.y > h + 15) c.y = -15;
          else if (c.y < -15) c.y = h + 15;
        } else {
          c.x += c.speed;
          if (c.x > w + 15) c.x = -15;
          else if (c.x < -15) c.x = w + 15;
        }

        // Flip timer
        if (--c.flipIn <= 0) {
          c.val ^= 1;
          c.flipIn = 120 + Math.floor(Math.random() * 400);
        }

        // Sine-wave "breathing"
        const breath = Math.sin(t + c.phase) * 0.015;

        let alpha = c.baseAlpha + breath;

        // ── Draw ──
        const sz = c.size;
        ctx.font = `bold ${sz}px "SF Mono", "Fira Code", "Cascadia Code", "Menlo", monospace`;

        ctx.fillStyle = invert
          ? `rgba(255,255,255,${Math.max(alpha, 0)})`
          : `rgba(100,116,139,${Math.max(alpha, 0)})`;
        ctx.shadowColor = "transparent";
        ctx.shadowBlur = 0;

        ctx.fillText(c.val ? "1" : "0", c.x, c.y);
      }

      raf = requestAnimationFrame(render);
    };

    // ── Event listeners ──
    // Listen on the PARENT element (the section) to capture all mouse movement
    window.addEventListener("resize", resize);

    resize();
    raf = requestAnimationFrame(render);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, [invert]);

  return (
    <div
      className={`absolute inset-0 overflow-hidden ${className}`}
      aria-hidden="true"
    >
      <canvas ref={canvasRef} className="absolute inset-0 w-full h-full" />
    </div>
  );
};
