export type CartItem = {
  productId: string;
  name: string;
  description?: string;
  quantity: number;
  unit: string;
  unitPrice: number;
  vendorId?: string;
  vendorName?: string;
};

const KEY = "pelagia_cart";

export function getCart(): CartItem[] {
  if (typeof window === "undefined") return [];
  try { return JSON.parse(localStorage.getItem(KEY) ?? "[]"); } catch { return []; }
}

export function saveCart(items: CartItem[]) {
  if (typeof window === "undefined") return;
  localStorage.setItem(KEY, JSON.stringify(items));
}

export function addToCart(item: CartItem) {
  const cart = getCart();
  const existing = cart.findIndex((c) => c.productId === item.productId && c.vendorId === item.vendorId);
  if (existing >= 0) {
    cart[existing].quantity += item.quantity;
  } else {
    cart.push(item);
  }
  saveCart(cart);
  window.dispatchEvent(new Event("cart-updated"));
}

export function removeFromCart(productId: string, vendorId?: string) {
  saveCart(getCart().filter((c) => !(c.productId === productId && c.vendorId === vendorId)));
  window.dispatchEvent(new Event("cart-updated"));
}

export function clearCart() {
  saveCart([]);
  window.dispatchEvent(new Event("cart-updated"));
}
