'use client';

import { useState } from 'react';
import * as motion from 'framer-motion/m';
import { AnimatePresence } from 'framer-motion';
import { Heart } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useWishlistStore } from '@/store/wishlistStore';

interface WishlistButtonProps {
  productId: string;
  variantId?: string | null;
  className?: string;
  size?: number;
}

// 5-6 tiny particles bursting outward from the heart — pure CSS/Framer
// positions (no physics engine needed for something this short-lived).
const PARTICLES = [
  { angle: -90, distance: 22 },
  { angle: -40, distance: 20 },
  { angle: -140, distance: 20 },
  { angle: 20, distance: 18 },
  { angle: 200, distance: 18 },
  { angle: 160, distance: 16 },
];

export default function WishlistButton({
  productId,
  variantId = null,
  className = '',
  size = 20,
}: WishlistButtonProps) {
  const { isInWishlist, addToWishlist, removeFromWishlist, items } =
    useWishlistStore();
  const t = useTranslations('ProductDetail');
  const [loading, setLoading] = useState(false);
  const [justActivated, setJustActivated] = useState(false);

  const inWishlist = isInWishlist(productId);
  const wishlistItem = items.find((item) => item.product_id === productId);

  const handleToggle = async (e: React.MouseEvent) => {
    // Rendered inside product cards next to links — never let the click
    // bubble into card navigation.
    e.preventDefault();
    e.stopPropagation();
    setLoading(true);
    if (inWishlist && wishlistItem) {
      await removeFromWishlist(wishlistItem.id);
    } else {
      await addToWishlist(productId, variantId);
      setJustActivated(true);
      setTimeout(() => setJustActivated(false), 500);
    }
    setLoading(false);
  };

  return (
    <button
      onClick={handleToggle}
      disabled={loading}
      className={`relative p-2 rounded-full transition-all ${
        inWishlist
          ? 'text-red-500 bg-red-50 hover:bg-red-100'
          : 'text-gray-400 bg-gray-50 hover:bg-gray-100'
      } ${className}`}
      title={inWishlist ? t('wishlistRemove') : t('wishlistAdd')}
      aria-label={inWishlist ? t('wishlistRemove') : t('wishlistAdd')}
      aria-pressed={inWishlist}
    >
      <motion.span
        animate={inWishlist ? { scale: [1, 1.3, 1] } : { scale: 1 }}
        transition={{ duration: 0.35, ease: [0.34, 1.56, 0.64, 1] }}
        className="block"
      >
        <Heart
          size={size}
          fill={inWishlist ? 'currentColor' : 'none'}
          className={loading ? 'animate-pulse' : ''}
        />
      </motion.span>

      <AnimatePresence>
        {justActivated && (
          <>
            {PARTICLES.map((p, i) => {
              const rad = (p.angle * Math.PI) / 180;
              return (
                <motion.span
                  key={i}
                  initial={{ x: 0, y: 0, opacity: 1, scale: 1 }}
                  animate={{
                    x: Math.cos(rad) * p.distance,
                    y: Math.sin(rad) * p.distance,
                    opacity: 0,
                    scale: 0.3,
                  }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.5, ease: 'easeOut' }}
                  className="absolute top-1/2 left-1/2 w-1.5 h-1.5 rounded-full bg-red-500 pointer-events-none"
                />
              );
            })}
          </>
        )}
      </AnimatePresence>
    </button>
  );
}
