"use client";

import { createContext, useContext, useEffect, useMemo, useState } from "react";
import type { CartItem, Product } from "@/lib/commerce";

type CartContextValue = {
  items: CartItem[];
  count: number;
  subtotal: number;
  favorites: string[];
  compare: string[];
  addItem: (product: Product, quantity?: number) => void;
  removeItem: (productId: string) => void;
  setQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;
  toggleFavorite: (productId: string) => void;
  toggleCompare: (productId: string) => void;
};

const CartContext = createContext<CartContextValue | null>(null);

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [items, setItems] = useState<CartItem[]>([]);
  const [favorites, setFavorites] = useState<string[]>([]);
  const [compare, setCompare] = useState<string[]>([]);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    try {
      setItems(JSON.parse(localStorage.getItem("barzinmarket-cart") || localStorage.getItem("sanjik-cart") || "[]"));
      setFavorites(JSON.parse(localStorage.getItem("barzinmarket-favorites") || localStorage.getItem("sanjik-favorites") || "[]"));
      setCompare(JSON.parse(localStorage.getItem("barzinmarket-compare") || localStorage.getItem("sanjik-compare") || "[]"));
    } catch {
      setItems([]);
    }
    setHydrated(true);
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    localStorage.setItem("barzinmarket-cart", JSON.stringify(items));
    localStorage.setItem("barzinmarket-favorites", JSON.stringify(favorites));
    localStorage.setItem("barzinmarket-compare", JSON.stringify(compare));
  }, [items, favorites, compare, hydrated]);

  const value = useMemo<CartContextValue>(() => ({
    items,
    count: items.reduce((sum, item) => sum + item.quantity, 0),
    subtotal: items.reduce((sum, item) => sum + item.product.salePrice * item.quantity, 0),
    favorites,
    compare,
    addItem(product, quantity = 1) {
      setItems((current) => {
        const found = current.find((item) => item.product.id === product.id);
        if (found) return current.map((item) => item.product.id === product.id ? { ...item, quantity: Math.min(product.stock || 99, item.quantity + quantity) } : item);
        return [...current, { product, quantity: Math.max(1, quantity) }];
      });
    },
    removeItem(productId) { setItems((current) => current.filter((item) => item.product.id !== productId)); },
    setQuantity(productId, quantity) {
      if (quantity <= 0) return setItems((current) => current.filter((item) => item.product.id !== productId));
      setItems((current) => current.map((item) => item.product.id === productId ? { ...item, quantity: Math.min(item.product.stock || 99, quantity) } : item));
    },
    clearCart() { setItems([]); },
    toggleFavorite(productId) { setFavorites((current) => current.includes(productId) ? current.filter((id) => id !== productId) : [...current, productId]); },
    toggleCompare(productId) { setCompare((current) => current.includes(productId) ? current.filter((id) => id !== productId) : current.length >= 4 ? current : [...current, productId]); },
  }), [items, favorites, compare, hydrated]);

  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

export function useCart() {
  const value = useContext(CartContext);
  if (!value) throw new Error("useCart must be used inside CartProvider");
  return value;
}
