import React, { createContext, useContext, useState, useEffect } from 'react';
import { calculatePromoTotal } from '../utils/pricing';

const ShopContext = createContext();

export const useShop = () => {
  const context = useContext(ShopContext);
  if (!context) throw new Error('useShop debe usarse dentro de un ShopProvider');
  return context;
};

export const ShopProvider = ({ children }) => {
  // carts es un objeto: { 'companyId1': [items...], 'companyId2': [items...] }
  const [carts, setCarts] = useState({});
  const [activeCompanyId, setActiveCompanyId] = useState(null);
  const [isCartOpen, setIsCartOpen] = useState(false);

  // Cargar carritos del almacenamiento local al iniciar
  useEffect(() => {
    const savedCarts = localStorage.getItem('menumaster-carts');
    if (savedCarts) {
      try {
        setCarts(JSON.parse(savedCarts));
      } catch (e) {
        console.error("Error parseando carritos:", e);
      }
    }
  }, []);

  // Guardar carritos cada vez que cambien
  useEffect(() => {
    localStorage.setItem('menumaster-carts', JSON.stringify(carts));
  }, [carts]);

  // Obtener el carrito de la empresa activa actual
  const cart = activeCompanyId ? (carts[activeCompanyId] || []) : [];

  // --- ACCIONES DEL CARRITO ---

  const addToCart = (product, quantity, modifiers = [], note = '') => {
    if (!activeCompanyId) {
      console.warn("No se puede agregar al carrito: No hay empresa activa seleccionada en el contexto.");
      return;
    }

    setCarts(prevCarts => {
      const currentCart = prevCarts[activeCompanyId] || [];

      // Buscamos si ya existe EXACTAMENTE el mismo producto (mismo ID + mismos modificadores + misma nota)
      const existingIndex = currentCart.findIndex(item =>
        item.id === product.id &&
        JSON.stringify(item.modifiers) === JSON.stringify(modifiers) &&
        item.note === note
      );

      let newCart;
      if (existingIndex >= 0) {
        // Si existe, actualizamos cantidad
        newCart = [...currentCart];
        newCart[existingIndex].quantity += quantity;
        newCart[existingIndex].note = note;
        if (product.promoApplied) {
          newCart[existingIndex].promoApplied = product.promoApplied;
        }
      } else {
        // Si no, agregamos nuevo item
        newCart = [...currentCart, { ...product, quantity, modifiers, note }];
      }

      return {
        ...prevCarts,
        [activeCompanyId]: newCart
      };
    });

    // Smart Cart: Abrir automáticamente al agregar
    setIsCartOpen(true);
  };

  const removeFromCart = (index) => {
    if (!activeCompanyId) return;
    setCarts(prevCarts => ({
      ...prevCarts,
      [activeCompanyId]: (prevCarts[activeCompanyId] || []).filter((_, i) => i !== index)
    }));
  };

  const clearCart = () => {
    if (!activeCompanyId) return;
    setCarts(prevCarts => ({
      ...prevCarts,
      [activeCompanyId]: []
    }));
  };

  const updateQuantity = (index, delta) => {
    if (!activeCompanyId) return;
    setCarts(prevCarts => {
      const currentCart = [...(prevCarts[activeCompanyId] || [])];
      if (currentCart[index]) {
        currentCart[index].quantity = Math.max(1, currentCart[index].quantity + delta);
      }
      return {
        ...prevCarts,
        [activeCompanyId]: currentCart
      };
    });
  };

  // --- CÁLCULO INTELIGENTE DEL TOTAL ---
  const cartTotal = cart.reduce((acc, item) => {
    const price = Number(item.price) || 0;
    const qty = Number(item.quantity) || 0;
    const itemBaseTotal = calculatePromoTotal(price, qty, item.promoApplied);
    const modifiersTotal = (item.modifiers || []).reduce((sum, mod) => sum + (Number(mod.price) || 0), 0) * qty;
    return acc + itemBaseTotal + modifiersTotal;
  }, 0);

  const cartCount = cart.reduce((acc, item) => acc + item.quantity, 0);

  return (
    <ShopContext.Provider value={{
      cart,
      activeCompanyId,
      setActiveCompanyId, // StorefrontPage debe llamar esto al cargar
      addToCart,
      removeFromCart,
      clearCart,
      updateQuantity,
      isCartOpen,
      setIsCartOpen,
      cartTotal,
      cartCount
    }}>
      {children}
    </ShopContext.Provider>
  );
};