"use client";

import { firework } from "@/lib/particles";
import { sfx } from "@/lib/sfx";

import { useState, useEffect } from "react";
import { Heart } from "lucide-react";
import clsx from "clsx";

// Small fixed set of burst directions so the particle animation is cheap
// (no random re-renders) but still feels lively.
const PARTICLES = [
  { tx: -18, ty: -14 },
  { tx: 0, ty: -20 },
  { tx: 18, ty: -14 },
  { tx: -14, ty: 10 },
  { tx: 14, ty: 10 },
  { tx: 0, ty: 16 },
];

export function LikeButton({
  liked,
  size = 18,
  className,
  onToggle,
}: {
  liked: boolean;
  size?: number;
  className?: string;
  onToggle: () => void;
}) {
  const [popping, setPopping] = useState(false);
  const [bursting, setBursting] = useState(false);

  useEffect(() => {
    if (!popping) return;
    const t = setTimeout(() => setPopping(false), 380);
    return () => clearTimeout(t);
  }, [popping]);

  useEffect(() => {
    if (!bursting) return;
    const t = setTimeout(() => setBursting(false), 500);
    return () => clearTimeout(t);
  }, [bursting]);

  function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
    const willLike = !liked;
    setPopping(true);
    if (willLike) {
      setBursting(true);
      firework(e.currentTarget, ["#ff5a7a", "#ff8a95", "#ffd0d6", "#ffffff"]);
      sfx.like();
    }
    onToggle();
  }

  return (
    <button
      onClick={handleClick}
      className={clsx("relative inline-flex items-center justify-center", className)}
    >
      {bursting && (
        <span
          aria-hidden
          className="like-ring absolute inset-0 rounded-full border-rose-500 pointer-events-none"
        />
      )}
      {bursting && (
        <span className="like-burst absolute inset-0 pointer-events-none">
          {PARTICLES.map((p, i) => (
            <span
              key={i}
              className="absolute left-1/2 top-1/2 w-1 h-1 rounded-full bg-rose-500"
              style={{ ["--tx" as string]: `${p.tx}px`, ["--ty" as string]: `${p.ty}px` }}
            />
          ))}
        </span>
      )}
      <Heart
        size={size}
        fill={liked ? "currentColor" : "none"}
        className={clsx(popping && "animate-like-pop")}
      />
    </button>
  );
}
