'use client';
import { createContext, useContext, useState, useEffect, useCallback } from 'react';

export interface CartItem {
  variantId: string;
  productId: string;
  productName: string;
  quantity: number;
  priceCents: number;
  imageUrl?: string;
  /** Cantidad mínima de compra del producto (F-102). */
  minPurchaseQty?: number;
}

interface CartContextValue {
  items: CartItem[];
  addItem: (item: CartItem) => void;
  removeItem: (variantId: string) => void;
  changeQuantity: (variantId: string, quantity: number) => void;
  clearCart: () => void;
  itemCount: number;
  subtotalCents: number;
}

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

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [items, setItems] = useState<CartItem[]>([]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      try {
        const stored = localStorage.getItem('mdv_cart');
        if (stored) setItems(JSON.parse(stored));
      } catch {}
    }, 0);
    return () => window.clearTimeout(timer);
  }, []);

  const addItem = useCallback((item: CartItem) => {
    setItems((prev) => {
      const existing = prev.find((i) => i.variantId === item.variantId);
      const next = existing
        ? prev.map((i) =>
            i.variantId === item.variantId
              ? {
                  ...i,
                  quantity: i.quantity + item.quantity,
                  minPurchaseQty: Math.max(i.minPurchaseQty ?? 1, item.minPurchaseQty ?? 1),
                }
              : i,
          )
        : [...prev, item];
      localStorage.setItem('mdv_cart', JSON.stringify(next));
      return next;
    });
  }, []);

  const removeItem = useCallback((variantId: string) => {
    setItems((prev) => {
      const next = prev.filter((i) => i.variantId !== variantId);
      localStorage.setItem('mdv_cart', JSON.stringify(next));
      return next;
    });
  }, []);

  const changeQuantity = useCallback((variantId: string, quantity: number) => {
    setItems((prev) => {
      const next =
        quantity <= 0
          ? prev.filter((i) => i.variantId !== variantId)
          : prev.map((i) =>
              i.variantId === variantId
                ? { ...i, quantity: Math.max(quantity, i.minPurchaseQty ?? 1) }
                : i,
            );
      localStorage.setItem('mdv_cart', JSON.stringify(next));
      return next;
    });
  }, []);

  const clearCart = useCallback(() => {
    setItems([]);
    localStorage.removeItem('mdv_cart');
  }, []);

  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0);
  const subtotalCents = items.reduce((sum, i) => sum + i.priceCents * i.quantity, 0);

  return (
    <CartContext.Provider value={{ items, addItem, removeItem, changeQuantity, clearCart, itemCount, subtotalCents }}>
      {children}
    </CartContext.Provider>
  );
}

export function useCart() {
  const ctx = useContext(CartContext);
  if (!ctx) throw new Error('useCart must be used within CartProvider');
  return ctx;
}
