"use client";

import { useState } from "react";
import { ShoppingCart } from "lucide-react";
import { Button } from "@/components/ui/button";

const CART_KEY = "305g_cart";

type CartProduct = {
  id: string;
  name: string;
  slug: string;
  price: number;
  thumbnail?: string | null;
};

type CartItem = CartProduct & { quantity: number };

export function AddToCartButton({ product }: { product: CartProduct }) {
  const [added, setAdded] = useState(false);

  function add() {
    try {
      const raw = localStorage.getItem(CART_KEY);
      const cart: CartItem[] = raw ? JSON.parse(raw) : [];
      const existing = cart.find((item) => item.id === product.id);
      if (existing) {
        existing.quantity += 1;
      } else {
        cart.push({ ...product, quantity: 1 });
      }
      localStorage.setItem(CART_KEY, JSON.stringify(cart));
      setAdded(true);
      window.dispatchEvent(new Event("305g-cart-updated"));
      setTimeout(() => setAdded(false), 1800);
    } catch {
      setAdded(false);
    }
  }

  return (
    <Button type="button" size="lg" onClick={add}>
      <ShoppingCart className="h-4 w-4" />
      {added ? "Ditambahkan" : "Tambah ke Keranjang"}
    </Button>
  );
}

export { CART_KEY };
export type { CartItem, CartProduct };
