"use client";
import { useEffect, useRef } from "react";

export default function CircuitBackground() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let animId: number;
    let nodes: { x: number; y: number; size: number; alpha: number; speed: number; phase: number }[] = [];

    const resize = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      initNodes();
    };

    const initNodes = () => {
      nodes = [];
      const cols = Math.floor(canvas.width / 56);
      const rows = Math.floor(canvas.height / 56);
      for (let r = 0; r <= rows; r++) {
        for (let c = 0; c <= cols; c++) {
          if (Math.random() > 0.88) {
            nodes.push({
              x: c * 56,
              y: r * 56,
              size: Math.random() * 1.8 + 0.8,
              alpha: Math.random() * 0.35 + 0.08,
              speed: Math.random() * 0.02 + 0.005,
              phase: Math.random() * Math.PI * 2,
            });
          }
        }
      }
    };

    let tick = 0;
    const draw = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      tick += 0.01;
      nodes.forEach((node) => {
        const pulse = Math.sin(tick * node.speed * 100 + node.phase);
        const alpha = node.alpha * (0.5 + 0.5 * pulse);
        ctx.beginPath();
        ctx.arc(node.x, node.y, node.size * (1 + 0.3 * pulse), 0, Math.PI * 2);
        ctx.fillStyle = `rgba(29, 111, 235, ${alpha})`;
        ctx.fill();

        const g = ctx.createRadialGradient(node.x, node.y, 0, node.x, node.y, node.size * 7);
        g.addColorStop(0, `rgba(74, 144, 245, ${alpha * 0.35})`);
        g.addColorStop(1, "rgba(29, 111, 235, 0)");
        ctx.beginPath();
        ctx.arc(node.x, node.y, node.size * 7, 0, Math.PI * 2);
        ctx.fillStyle = g;
        ctx.fill();
      });
      animId = requestAnimationFrame(draw);
    };

    resize();
    draw();
    window.addEventListener("resize", resize);
    return () => { cancelAnimationFrame(animId); window.removeEventListener("resize", resize); };
  }, []);

  return (
    <canvas ref={canvasRef} className="fixed inset-0 pointer-events-none z-0 opacity-50" aria-hidden="true" />
  );
}
