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

type Pin = { a: number; r: number; emoji: string; ph: number; sp: number };

/** Distribución fija (no aleatoria) para que el radar se vea igual en cada carga. */
const SEED: Array<[number, number, string]> = [
  [-0.55, 0.16, "🎺"], [0.9, 0.2, "🥁"], [2.3, 0.145, "🎸"],
  [-2.1, 0.235, "🎻"], [1.75, 0.3, "🎤"], [-1.25, 0.285, "🪗"],
  [3.0, 0.245, "🎹"], [0.25, 0.33, "🎷"], [-2.75, 0.35, "🎧"],
  [2.75, 0.4, "🪘"], [-0.15, 0.425, "🎼"], [1.2, 0.46, "🎸"],
];

/**
 * Radar del hero: retícula radial + ondas de alcance + pins de músicos latiendo.
 *
 * Es Canvas y no MapLibre a propósito: el hero necesita verse siempre, y un mapa vectorial
 * depende de tiles remotos (si no hay red, queda un hueco negro). Acá lo que se cuenta es la
 * geolocalización, no la cartografía. El mapa real vive en /buscar.
 */
export function HeroRadar() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

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

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const pins: Pin[] = SEED.map(([a, r, emoji], i) => ({
      a, r, emoji,
      ph: (i * 2.39) % (Math.PI * 2), // ángulo áureo: laten desincronizados sin usar random
      sp: 0.8 + ((i * 7) % 10) / 14,
    }));

    let w = 0, h = 0, cx = 0, cy = 0;
    let px = 0, py = 0, tx = 0, ty = 0; // parallax actual y objetivo
    let raf = 0;

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      cx = w / 2;
      cy = h * 0.46;
    };
    resize();

    const onMove = (e: PointerEvent) => {
      tx = (e.clientX / window.innerWidth - 0.5) * -26;
      ty = (e.clientY / window.innerHeight - 0.5) * -16;
    };

    const radius = () => Math.max(w, h) * 0.92;

    const drawGrid = () => {
      const rad = radius();
      ctx.save();
      ctx.translate(cx + px, cy + py);
      for (let i = 0; i < 22; i++) {
        const a = (i / 22) * Math.PI * 2 + 0.14;
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(Math.cos(a) * rad, Math.sin(a) * rad * 0.62);
        ctx.strokeStyle = i % 4 === 0 ? "rgba(120,170,220,.16)" : "rgba(120,170,220,.07)";
        ctx.lineWidth = i % 4 === 0 ? 1.1 : 0.7;
        ctx.stroke();
      }
      for (let r = 0.07; r < 1; r += 0.075) {
        ctx.beginPath();
        ctx.ellipse(0, 0, rad * r, rad * r * 0.62, 0, 0, Math.PI * 2);
        ctx.strokeStyle = "rgba(120,170,220,.075)";
        ctx.lineWidth = 0.7;
        ctx.stroke();
      }
      // Anillos de alcance rotulados: el vocabulario del producto, dibujado.
      ([[0.3, "5 KM"], [0.52, "15 KM"], [0.76, "40 KM"]] as const).forEach(([r, label]) => {
        ctx.beginPath();
        ctx.setLineDash([3, 7]);
        ctx.ellipse(0, 0, rad * r, rad * r * 0.62, 0, 0, Math.PI * 2);
        ctx.strokeStyle = "rgba(34,211,238,.30)";
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.setLineDash([]);
        ctx.font = "600 9px ui-monospace, monospace";
        ctx.fillStyle = "rgba(34,211,238,.5)";
        ctx.textAlign = "left";
        ctx.fillText(label, 6, -rad * r * 0.62 - 5);
      });
      ctx.restore();
    };

    const drawWaves = (t: number) => {
      const rad = radius();
      ctx.save();
      ctx.translate(cx + px, cy + py);
      for (let k = 0; k < 3; k++) {
        const p = (t / 4200 + k / 3) % 1;
        const e = 1 - Math.pow(1 - p, 2);
        ctx.beginPath();
        ctx.ellipse(0, 0, rad * e, rad * e * 0.62, 0, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(34,211,238,${(1 - p) * 0.32})`;
        ctx.lineWidth = 1.5 * (1 - p) + 0.4;
        ctx.stroke();
      }
      ctx.restore();
    };

    const drawPins = (t: number) => {
      const rad = radius();
      pins.forEach((p) => {
        const x = cx + px + Math.cos(p.a) * rad * p.r;
        const y = cy + py + Math.sin(p.a) * rad * p.r * 0.62;
        const pulse = (Math.sin((t / 1000) * p.sp + p.ph) + 1) / 2;

        ctx.beginPath();
        ctx.arc(x, y, 13 + pulse * 11, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(34,211,238,${0.12 * (1 - pulse) + 0.04})`;
        ctx.fill();

        ctx.beginPath();
        ctx.arc(x, y, 4.6, 0, Math.PI * 2);
        ctx.fillStyle = "#22d3ee";
        ctx.shadowColor = "#22d3ee";
        ctx.shadowBlur = 16;
        ctx.fill();
        ctx.shadowBlur = 0;

        ctx.font = "15px system-ui, 'Segoe UI Emoji', 'Noto Color Emoji'";
        ctx.textAlign = "center";
        ctx.globalAlpha = 0.5 + pulse * 0.4;
        ctx.fillText(p.emoji, x, y - 15);
        ctx.globalAlpha = 1;
      });

      // Vos, en el centro. Azul Boracurve para distinguirte de los músicos (teal).
      const b = (Math.sin(t / 760) + 1) / 2;
      ctx.beginPath();
      ctx.arc(cx + px, cy + py, 15 + b * 14, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(59,130,246,${0.22 * (1 - b)})`;
      ctx.fill();
      ctx.beginPath();
      ctx.arc(cx + px, cy + py, 6.5, 0, Math.PI * 2);
      ctx.fillStyle = "#3b82f6";
      ctx.shadowColor = "#3b82f6";
      ctx.shadowBlur = 22;
      ctx.fill();
      ctx.shadowBlur = 0;
      ctx.strokeStyle = "rgba(255,255,255,.9)";
      ctx.lineWidth = 1.6;
      ctx.stroke();
    };

    const frame = (t: number) => {
      px += (tx - px) * 0.045;
      py += (ty - py) * 0.045;
      ctx.clearRect(0, 0, w, h);
      drawGrid();
      drawWaves(t);
      drawPins(t);
      raf = requestAnimationFrame(frame);
    };

    window.addEventListener("resize", resize);
    if (reduced) {
      drawGrid();
      drawPins(0);
    } else {
      window.addEventListener("pointermove", onMove);
      raf = requestAnimationFrame(frame);
    }

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

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