'use client';

import { useRef, useState } from 'react';
import * as motion from 'framer-motion/m';
import { AnimatePresence } from 'framer-motion';
import { useTranslations } from 'next-intl';
import { ShoppingCart, Check } from 'lucide-react';
import { useCartStore } from '@/store/cartStore';
import { useCartUI } from '@/components/frontend/cart/CartUIContext';

interface AddToCartButtonProduct {
  id: string;
  image: string; // a real <img> src — the grab-and-throw clone flies this
  variantId?: string | null;
}

interface AddToCartButtonProps {
  product: AddToCartButtonProduct;
  quantity?: number;
  className?: string;
  onAdd?: () => void;
}

// Standalone add-to-cart control with the same grab-and-throw animation as
// ProductCard.tsx — both share useCartUI()'s fly()/cartIconRef rather than
// each needing a cartIconRef prop threaded down manually, since the cart
// icon (registered once, in Header.tsx) is the same target for every
// instance anywhere in the tree.
export default function AddToCartButton({
  product,
  quantity = 1,
  className = '',
  onAdd,
}: AddToCartButtonProps) {
  const { addToCart, loading } = useCartStore();
  const { fly } = useCartUI();
  const t = useTranslations('ProductCard');
  const tCart = useTranslations('Cart');
  const [added, setAdded] = useState(false);
  const [isFlying, setIsFlying] = useState(false);
  const [justPicked, setJustPicked] = useState(false);
  const imageRef = useRef<HTMLImageElement>(null);

  const handleAdd = async () => {
    if (isFlying) return; // guard double-fires while a throw is in flight

    setJustPicked(true);
    setTimeout(() => setJustPicked(false), 300);

    if (imageRef.current) {
      setIsFlying(true);
      fly(imageRef.current, product.image, () => setIsFlying(false));
    }

    await addToCart(product.id, product.variantId ?? null, quantity, {
      success: tCart('addedToCart'),
      failed: tCart('addToCartFailed'),
      networkError: tCart('networkError'),
    });
    onAdd?.();

    setAdded(true);
    setTimeout(() => setAdded(false), 1500);
  };

  return (
    <div className="inline-flex items-center gap-3">
      <motion.img
        ref={imageRef}
        src={product.image}
        alt=""
        aria-hidden
        animate={justPicked ? { scale: 0.85, opacity: 0.7 } : { scale: 1, opacity: 1 }}
        transition={{ duration: 0.15 }}
        className="w-10 h-10 rounded-lg object-cover"
      />
      <button
        onClick={handleAdd}
        disabled={loading || isFlying}
        className={`inline-flex items-center justify-center gap-2 px-6 py-3 rounded-lg font-medium transition-all overflow-hidden ${
          added
            ? 'bg-green-500 text-white'
            : 'bg-amber-600 text-white hover:bg-amber-700'
        } disabled:opacity-50 ${className}`}
      >
        <AnimatePresence mode="wait" initial={false}>
          {added ? (
            <motion.span
              key="added"
              initial={{ y: 12, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              exit={{ y: -12, opacity: 0 }}
              transition={{ duration: 0.18 }}
              className="flex items-center gap-2"
            >
              <Check size={18} />
              {t('added')}
            </motion.span>
          ) : (
            <motion.span
              key="idle"
              initial={{ y: 12, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              exit={{ y: -12, opacity: 0 }}
              transition={{ duration: 0.18 }}
              className="flex items-center gap-2"
            >
              <ShoppingCart size={18} />
              {t('addToCart')}
            </motion.span>
          )}
        </AnimatePresence>
      </button>
    </div>
  );
}
