"use client";

import { useEffect, useRef } from "react";

type Props = {
  currentTime?: number;
  accent?: string;
  isPlaying?: boolean;
  audioElement?: HTMLAudioElement | null;
  previewMode?: boolean;
};

// Global cache so createMediaElementSource is only ever called once per HTMLAudioElement
const audioNodeCache = new WeakMap<
  HTMLAudioElement,
  {
    ctx: AudioContext;
    analyser: AnalyserNode;
    source: MediaElementAudioSourceNode;
  }
>();

/* eslint-disable @typescript-eslint/no-unused-vars */
export default function AudioVisualizer({
  accent = "#f5caca",
  isPlaying = false,
  currentTime: _currentTime,
  audioElement,
  previewMode = false,
}: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const animFrameRef = useRef<number | null>(null);
  const activeAnalyserRef = useRef<AnalyserNode | null>(null);

  // Connect Web Audio API Analyser to the audio element
  useEffect(() => {
    if (!audioElement || previewMode) return;

    let attached = false;

    const attachAnalyser = () => {
      try {
        const AudioCtx =
          window.AudioContext ||
          (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
        if (!AudioCtx) return;

        let node = audioNodeCache.get(audioElement);
        if (!node) {
          const ctx = new AudioCtx();
          const analyser = ctx.createAnalyser();
          analyser.fftSize = 256;
          analyser.smoothingTimeConstant = 0.8;

          const source = ctx.createMediaElementSource(audioElement);
          source.connect(analyser);
          analyser.connect(ctx.destination);

          node = { ctx, analyser, source };
          audioNodeCache.set(audioElement, node);
        }

        activeAnalyserRef.current = node.analyser;

        if (node.ctx.state === "suspended") {
          node.ctx.resume().catch(() => {});
        }

        attached = true;
      } catch (err) {
        console.warn("Web Audio Analyser attach attempt:", err);
      }
    };

    attachAnalyser();

    const handleUserGesture = () => {
      const node = audioNodeCache.get(audioElement);
      if (node && node.ctx.state === "suspended") {
        node.ctx.resume().catch(() => {});
      } else if (!attached) {
        attachAnalyser();
      }
    };

    window.addEventListener("click", handleUserGesture, { passive: true });
    window.addEventListener("keydown", handleUserGesture, { passive: true });
    window.addEventListener("touchstart", handleUserGesture, { passive: true });

    return () => {
      window.removeEventListener("click", handleUserGesture);
      window.removeEventListener("keydown", handleUserGesture);
      window.removeEventListener("touchstart", handleUserGesture);
    };
  }, [audioElement, previewMode]);

  // Canvas rendering loop using the exact symmetric mirrored waveform algorithm from LoveWrld
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const rawFreq = new Uint8Array(128);

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      const dpr = window.devicePixelRatio || 1;
      const w = Math.max(1, Math.round(rect.width));
      const h = Math.max(1, Math.round(rect.height));

      if (canvas.width !== w * dpr || canvas.height !== h * dpr) {
        canvas.width = w * dpr;
        canvas.height = h * dpr;
      }
    };

    resize();
    window.addEventListener("resize", resize, { passive: true });

    const render = () => {
      animFrameRef.current = requestAnimationFrame(render);

      const dpr = window.devicePixelRatio || 1;
      const width = canvas.width / dpr;
      const height = canvas.height / dpr;

      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, width, height);

      const analyser = activeAnalyserRef.current;
      const isMuted = Boolean(audioElement && (audioElement.muted || audioElement.volume === 0));
      const silent = !isPlaying || isMuted || !analyser;

      if (analyser && !silent) {
        analyser.getByteFrequencyData(rawFreq);
      }

      const now = performance.now();
      const progress =
        audioElement && audioElement.duration ? audioElement.currentTime / audioElement.duration : 0;
      const playheadX = progress * width;

      // Exact parameters from the LoveWrld audio visualizer:
      // 60 mirrored bars, lower 40% spectrum mapping, center-out mirroring
      const bars = Math.min(80, Math.max(48, Math.floor(width / 14)));
      const barWidth = Math.max(2, (width / bars) * 0.4);
      const barSpacing = width / bars;
      const centerX = width / 2;

      const drawBar = (x: number, intensity: number) => {
        const barHeight = Math.max(height * 0.16, intensity * height * 0.78);
        const barCenter = x + barWidth / 2;
        const played = barCenter <= playheadX;
        const isMarker = played && playheadX - barCenter < barSpacing;

        if (isMarker) {
          ctx.fillStyle = accent;
          ctx.shadowColor = accent;
          ctx.shadowBlur = barWidth * 3.5;
        } else {
          ctx.fillStyle = played
            ? `${accent}${Math.floor((0.55 + intensity * 0.45) * 255).toString(16).padStart(2, "0")}`
            : `rgba(0, 0, 0, ${0.14 + intensity * 0.3})`;
          ctx.shadowBlur = 0;
        }

        // Draw centered vertically
        ctx.fillRect(x, (height - barHeight) / 2, barWidth, barHeight);
        ctx.shadowBlur = 0;
      };

      for (let i = 0; i < bars / 2; i++) {
        // Map across the lower ~40% spectrum where musical energy resides
        const dataIndex = Math.floor((i * (rawFreq.length * 0.4)) / (bars / 2));
        const live = rawFreq[dataIndex] / 255;
        // Idle breathing sine wave fallback when silent or paused
        const idle = 0.18 + 0.1 * (0.5 + 0.5 * Math.sin(now / 550 - i * 0.3));
        const intensity = silent ? idle : Math.max(live, 0.18);

        // Mirror symmetrically left & right from the center
        drawBar(centerX + i * barSpacing, intensity);
        drawBar(centerX - i * barSpacing - barWidth, intensity);
      }
    };

    animFrameRef.current = requestAnimationFrame(render);

    return () => {
      window.removeEventListener("resize", resize);
      if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
    };
  }, [accent, isPlaying, audioElement]);

  return (
    <div
      aria-hidden="true"
      style={{
        position: previewMode ? "absolute" : "fixed",
        top: "50%",
        left: 0,
        right: 0,
        transform: "translateY(-50%)",
        width: "100%",
        height: previewMode ? "100%" : "min(280px, 35vh)",
        pointerEvents: "none",
        zIndex: 1, // Sits between background media and profile card (zIndex: 3)
        opacity: 0.85,
        overflow: "hidden",
      }}
    >
      <canvas
        ref={canvasRef}
        style={{
          width: "100%",
          height: "100%",
          display: "block",
          filter: `drop-shadow(0 0 16px ${accent}66)`,
        }}
      />
    </div>
  );
}
