"use client";

import React, { useState } from "react";
import { useCartStore } from "@/hooks/useCartStore";
import { type CartItem } from "@/types/cart";
import { ShoppingCart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { logClientError } from "@/actions/logging";

export interface AddToCartButtonProps {
  product: CartItem;
}

const AddToCartButton: React.FC<AddToCartButtonProps> = ({ product }) => {
  /*
    ⚡ Bolt Optimization: Selective Zustand Selector
    Subscribing only to 'addToCart' to avoid re-renders when other store properties
    (like 'items' or 'isOpen') change.
  */
  const addToCart = useCartStore((state) => state.addToCart);
  const [loading, setLoading] = useState(false);

  const handleAddToCart = async () => {
    setLoading(true);
    try {
      await addToCart({
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: product.quantity,
        image: product.image,
      });
      toast.success(`${product.name} zum Warenkorb hinzugefügt`);
    } catch (error: any) {
      toast.error("Fehler beim Hinzufügen zum Warenkorb");
      console.error(error);
      logClientError("Add to cart error", { 
        productId: product.id,
        error: error.message || String(error),
        stack: error.stack 
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      onClick={handleAddToCart}
      loading={loading}
      className="w-full h-auto py-2.5 text-base font-semibold transition-all active:scale-[0.98]"
    >
      <ShoppingCart size={20} className="mr-2" />
      In den Warenkorb
    </Button>
  );
};

export default AddToCartButton;
