"use client";

import { useEffect, useRef } from "react";
import { prefersReducedMotion } from "./gsap-setup";

/** Target particle density: one particle per this many square px of canvas. */
const AREA_PER_PARTICLE = 9000;
const MIN_PARTICLES = 26;
const MAX_PARTICLES = 90;

/** Particles closer than this link with a line; opacity fades to 0 at the limit. */
const LINK_DISTANCE = 130;
/** Radius within which the pointer also grabs lines to nearby particles. */
const POINTER_LINK_DISTANCE = 160;

const SPEED = 0.35;
const RADIUS_MIN = 1;
const RADIUS_MAX = 2.4;

type Particle = { x: number; y: number; vx: number; vy: number; r: number };

/**
 * The classic particles.js network — small drifting dots, linked by fading
 * lines when close, with lines reaching out to the pointer on hover —
 * scoped to the hero rather than the whole page. Hand-rolled canvas 2D to
 * match AmbientScene rather than pulling in the particles.js runtime for
 * one section's worth of effect.
 */
export default function Particles() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

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

    // Colours track the page's theme tokens rather than a fixed palette, so
    // the network stays legible if the visitor flips light/dark.
    const themeRoot = canvas.closest(".immersive") ?? canvas;
    let lineHsl = "0 0% 100%";
    let accentHsl = "129 40% 52%";
    const readColors = () => {
      const style = getComputedStyle(themeRoot);
      lineHsl = style.getPropertyValue("--foreground").trim() || lineHsl;
      accentHsl = style.getPropertyValue("--primary").trim() || accentHsl;
    };
    readColors();

    let width = 0;
    let height = 0;
    let particles: Particle[] = [];
    let frame = 0;
    let running = true;

    const pointer = { x: -9999, y: -9999, active: false };

    const seedParticles = () => {
      const area = width * height;
      const count = Math.round(
        Math.min(MAX_PARTICLES, Math.max(MIN_PARTICLES, area / AREA_PER_PARTICLE))
      );
      particles = Array.from({ length: count }, () => ({
        x: Math.random() * width,
        y: Math.random() * height,
        vx: (Math.random() - 0.5) * SPEED,
        vy: (Math.random() - 0.5) * SPEED,
        r: RADIUS_MIN + Math.random() * (RADIUS_MAX - RADIUS_MIN),
      }));
    };

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      width = canvas.clientWidth;
      height = canvas.clientHeight;
      canvas.width = Math.floor(width * dpr);
      canvas.height = Math.floor(height * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      seedParticles();
    };

    const onPointerMove = (e: PointerEvent) => {
      const rect = canvas.getBoundingClientRect();
      pointer.x = e.clientX - rect.left;
      pointer.y = e.clientY - rect.top;
      pointer.active = true;
    };

    const onPointerLeave = () => {
      pointer.active = false;
    };

    const draw = () => {
      ctx.clearRect(0, 0, width, height);

      for (const p of particles) {
        p.x += p.vx;
        p.y += p.vy;
        if (p.x <= 0 || p.x >= width) p.vx *= -1;
        if (p.y <= 0 || p.y >= height) p.vy *= -1;
        p.x = Math.min(Math.max(p.x, 0), width);
        p.y = Math.min(Math.max(p.y, 0), height);
      }

      ctx.fillStyle = `hsl(${lineHsl} / 0.55)`;
      for (const p of particles) {
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fill();
      }

      ctx.lineWidth = 1;
      for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
          const a = particles[i];
          const b = particles[j];
          const dist = Math.hypot(a.x - b.x, a.y - b.y);
          if (dist < LINK_DISTANCE) {
            ctx.strokeStyle = `hsl(${lineHsl} / ${0.22 * (1 - dist / LINK_DISTANCE)})`;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }

      if (pointer.active) {
        for (const p of particles) {
          const dist = Math.hypot(p.x - pointer.x, p.y - pointer.y);
          if (dist < POINTER_LINK_DISTANCE) {
            ctx.strokeStyle = `hsl(${accentHsl} / ${0.5 * (1 - dist / POINTER_LINK_DISTANCE)})`;
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(pointer.x, pointer.y);
            ctx.stroke();
          }
        }
      }
    };

    const render = () => {
      if (!running) return;
      draw();
      frame = requestAnimationFrame(render);
    };

    const onVisibility = () => {
      running = document.visibilityState === "visible";
      if (running) frame = requestAnimationFrame(render);
      else cancelAnimationFrame(frame);
    };

    resize();
    window.addEventListener("resize", resize);

    // Theme toggling flips a class on the nearest `.immersive` ancestor, not
    // on this component's props — re-read the tokens whenever it changes.
    const themeObserver = new MutationObserver(readColors);
    themeObserver.observe(themeRoot, { attributes: true, attributeFilter: ["class"] });

    if (prefersReducedMotion()) {
      draw();
      return () => {
        window.removeEventListener("resize", resize);
        themeObserver.disconnect();
      };
    }

    window.addEventListener("pointermove", onPointerMove, { passive: true });
    document.documentElement.addEventListener("pointerleave", onPointerLeave);
    document.addEventListener("visibilitychange", onVisibility);
    frame = requestAnimationFrame(render);

    return () => {
      running = false;
      cancelAnimationFrame(frame);
      window.removeEventListener("resize", resize);
      window.removeEventListener("pointermove", onPointerMove);
      document.documentElement.removeEventListener("pointerleave", onPointerLeave);
      document.removeEventListener("visibilitychange", onVisibility);
      themeObserver.disconnect();
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      aria-hidden
      className="pointer-events-none absolute inset-0 h-full w-full"
    />
  );
}
