"use client";

import { useEffect, useRef } from "react";

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

export default function Effects({
  accent,
  effect,
  cursor,
}: Props) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const activeEffect =
    effect === "glow" ||
    effect === "particles" ||
    effect === "snow" ||
    effect === "rain" ||
    effect === "halloween"
      ? effect
      : "none";
  const activeCursor =
    cursor === "trail" ||
    cursor === "dot" ||
    cursor === "particles" ||
    cursor === "sparkles" ||
    cursor === "embers" ||
    cursor === "ghost"
      ? cursor
      : "none";

  useEffect(() => {
    if (activeEffect === "none" && activeCursor === "none") return;

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

    let w = (canvas.width = window.innerWidth);
    let h = (canvas.height = window.innerHeight);
    const onResize = () => {
      w = canvas.width = window.innerWidth;
      h = canvas.height = window.innerHeight;
    };
    window.addEventListener("resize", onResize);

    type P = {
      x: number;
      y: number;
      vx: number;
      vy: number;
      r: number;
      life: number;
      kind?: "dot" | "rain" | "bat" | "ember";
      wingPhase?: number;
      wingSpeed?: number;
    };
    const ambient: P[] = [];
    const trail: P[] = [];
    let pointer: { x: number; y: number } | null = null;

    if (activeEffect === "particles") {
      for (let i = 0; i < 60; i++) {
        ambient.push({
          x: Math.random() * w,
          y: Math.random() * h,
          vx: (Math.random() - 0.5) * 0.3,
          vy: (Math.random() - 0.5) * 0.3,
          r: Math.random() * 2 + 0.5,
          life: 1,
          kind: "dot",
        });
      }
    }

    if (activeEffect === "snow" || activeEffect === "rain") {
      const count = activeEffect === "snow" ? 50 : 72;
      for (let i = 0; i < count; i++) {
        ambient.push({
          x: Math.random() * w,
          y: Math.random() * h,
          vx: activeEffect === "rain" ? Math.random() * 1.1 + 1.2 : (Math.random() - 0.5) * 0.35,
          vy: activeEffect === "rain" ? Math.random() * 2.2 + 3.8 : Math.random() * 0.8 + 0.5,
          r: activeEffect === "rain" ? Math.random() * 0.4 + 0.7 : Math.random() * 2 + 0.8,
          life: 1,
          kind: activeEffect === "rain" ? "rain" : "dot",
        });
      }
    }

    if (activeEffect === "halloween") {
      // Bats flying across the screen
      for (let i = 0; i < 9; i++) {
        ambient.push({
          x: Math.random() * w,
          y: Math.random() * h * 0.8,
          vx: (Math.random() * 1.4 + 0.8) * (Math.random() > 0.4 ? 1 : -1),
          vy: (Math.random() - 0.5) * 0.6,
          r: Math.random() * 6 + 10,
          life: 1,
          kind: "bat",
          wingPhase: Math.random() * Math.PI * 2,
          wingSpeed: 0.18 + Math.random() * 0.08,
        });
      }
      // Floating glowing embers
      for (let i = 0; i < 35; i++) {
        ambient.push({
          x: Math.random() * w,
          y: Math.random() * h,
          vx: (Math.random() - 0.5) * 0.4,
          vy: -(Math.random() * 0.9 + 0.4),
          r: Math.random() * 1.8 + 0.8,
          life: Math.random(),
          kind: "ember",
        });
      }
    }

    const onMove = (e: MouseEvent) => {
      if (activeCursor === "none") return;
      pointer = { x: e.clientX, y: e.clientY };
      if (activeCursor === "dot") return;
      const count =
        activeCursor === "trail" || activeCursor === "sparkles"
          ? 3
          : activeCursor === "embers" || activeCursor === "ghost"
            ? 2
            : 1;
      for (let i = 0; i < count; i++) {
        trail.push({
          x: e.clientX,
          y: e.clientY,
          vx: (Math.random() - 0.5) * (activeCursor === "ghost" ? 0.8 : 1.2),
          vy: activeCursor === "embers" ? -(Math.random() * 1.4 + 0.4) : (Math.random() - 0.5) * 1.2,
          r: activeCursor === "ghost" ? Math.random() * 4 + 3 : activeCursor === "sparkles" ? Math.random() * 3 + 1.5 : Math.random() * 2.8 + 1.2,
          life: 1,
        });
      }
      if (trail.length > 220) trail.splice(0, trail.length - 220);
    };
    window.addEventListener("mousemove", onMove);

    let raf = 0;
    const draw = () => {
      ctx.clearRect(0, 0, w, h);

      for (const p of ambient) {
        p.x += p.vx;
        p.y += p.vy;

        if (p.kind === "bat") {
          p.wingPhase = (p.wingPhase || 0) + (p.wingSpeed || 0.2);
          if (p.x < -40) p.x = w + 40;
          if (p.x > w + 40) p.x = -40;
          if (p.y < 0) p.y = h * 0.8;
          if (p.y > h * 0.9) p.y = 20;

          // Draw bat
          ctx.save();
          ctx.translate(p.x, p.y);
          if (p.vx < 0) ctx.scale(-1, 1);
          const flap = Math.sin(p.wingPhase);
          ctx.fillStyle = "rgba(18, 16, 24, 0.85)";
          // wings
          ctx.beginPath();
          ctx.moveTo(0, 0);
          ctx.quadraticCurveTo(-p.r * 0.8, -p.r * 0.4 + flap * 6, -p.r * 1.8, -p.r * 0.2 + flap * 8);
          ctx.quadraticCurveTo(-p.r * 0.9, p.r * 0.4, 0, p.r * 0.3);
          ctx.quadraticCurveTo(p.r * 0.9, p.r * 0.4, p.r * 1.8, -p.r * 0.2 + flap * 8);
          ctx.quadraticCurveTo(p.r * 0.8, -p.r * 0.4 + flap * 6, 0, 0);
          ctx.fill();
          // body
          ctx.beginPath();
          ctx.ellipse(0, 0, p.r * 0.35, p.r * 0.6, 0, 0, Math.PI * 2);
          ctx.fill();
          // glowing eyes
          ctx.fillStyle = "#ffffff";
          ctx.beginPath();
          const eyeX = Math.max(1.5, p.r * 0.12);
          const eyeY = -p.r * 0.2;
          const eyeR = Math.max(0.8, p.r * 0.08);
          ctx.arc(-eyeX, eyeY, eyeR, 0, Math.PI * 2);
          ctx.arc(eyeX, eyeY, eyeR, 0, Math.PI * 2);
          ctx.fill();
          ctx.restore();
          continue;
        }

        if (p.kind === "ember") {
          p.life += 0.02;
          if (p.y < -10) {
            p.y = h + 10;
            p.x = Math.random() * w;
          }
          if (p.x < 0) p.x = w;
          if (p.x > w) p.x = 0;
          const emberAlpha = Math.abs(Math.sin(p.life)) * 0.7 + 0.2;
          ctx.fillStyle = `rgba(255, 255, 255, ${emberAlpha})`;
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
          ctx.fill();
          continue;
        }

        if (p.x < 0) p.x = w;
        if (p.x > w) p.x = 0;
        if (p.y < 0) p.y = h;
        if (p.y > h) p.y = 0;
        ctx.fillStyle = accent;
        if (p.kind === "rain") {
          ctx.globalAlpha = 0.42;
          ctx.strokeStyle = accent;
          ctx.lineWidth = p.r;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.moveTo(p.x, p.y);
          ctx.lineTo(p.x - p.vx * 2.2, p.y - p.vy * 2.2);
          ctx.stroke();
        } else {
          ctx.globalAlpha = 0.72;
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      for (let i = trail.length - 1; i >= 0; i--) {
        const p = trail[i];
        p.x += p.vx;
        p.y += p.vy;
        p.life -= 0.03;
        if (p.life <= 0) {
          trail.splice(i, 1);
          continue;
        }
        if (activeCursor === "sparkles") {
          ctx.globalAlpha = p.life;
          ctx.fillStyle = "#fdf6f6";
          ctx.beginPath();
          const size = p.r * p.life * 1.4;
          ctx.moveTo(p.x, p.y - size);
          ctx.quadraticCurveTo(p.x, p.y, p.x + size, p.y);
          ctx.quadraticCurveTo(p.x, p.y, p.x, p.y + size);
          ctx.quadraticCurveTo(p.x, p.y, p.x - size, p.y);
          ctx.quadraticCurveTo(p.x, p.y, p.x, p.y - size);
          ctx.fill();
        } else if (activeCursor === "embers") {
          ctx.globalAlpha = p.life;
          ctx.fillStyle = p.life > 0.5 ? "#f9ebeb" : "#efbfbf";
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r * p.life, 0, Math.PI * 2);
          ctx.fill();
        } else if (activeCursor === "ghost") {
          ctx.globalAlpha = p.life * 0.45;
          ctx.fillStyle = "#fdeeee";
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r * (2 - p.life), 0, Math.PI * 2);
          ctx.fill();
        } else {
          ctx.globalAlpha = activeCursor === "trail" ? p.life : Math.min(1, p.life * 1.4);
          ctx.fillStyle = accent;
          ctx.beginPath();
          ctx.arc(p.x, p.y, p.r * p.life, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      if (activeCursor === "dot" && pointer) {
        ctx.globalAlpha = 0.96;
        ctx.fillStyle = accent;
        ctx.beginPath();
        ctx.arc(pointer.x, pointer.y, 6, 0, Math.PI * 2);
        ctx.fill();
        ctx.strokeStyle = "rgba(0, 0, 0, .9)";
        ctx.lineWidth = 1.5;
        ctx.stroke();
      }

      ctx.globalAlpha = 1;
      raf = requestAnimationFrame(draw);
    };
    draw();

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", onResize);
      window.removeEventListener("mousemove", onMove);
    };
  }, [accent, activeEffect, activeCursor]);

  return (
    <>
      <canvas
        ref={canvasRef}
        aria-hidden="true"
        style={{
          position: "fixed",
          inset: 0,
          pointerEvents: "none",
          zIndex: 4,
          opacity: activeEffect === "none" && activeCursor === "none" ? 0 : 1,
        }}
      />
      {activeEffect === "glow" && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            pointerEvents: "none",
            zIndex: 1,
            background: `radial-gradient(circle at 50% 40%, ${accent}22, transparent 60%)`,
            animation: "glow 5s ease-in-out infinite",
          }}
        />
      )}
      {activeEffect === "halloween" && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            pointerEvents: "none",
            zIndex: 1,
            background: "radial-gradient(circle at 50% 10%, rgba(255, 255, 255, 0.08), transparent 60%)",
          }}
        />
      )}
    </>
  );
}
