'use client'; import { useEffect, useState, useCallback } from 'react'; import { getCartItems, addProductToCart, removeProductFromCart, clearCart, increaseQuantity, decreaseQuantity, updateQuantity, getProductQuantity, isProductInCart, CART_CHANGE_EVENT, type CartItem, } from '../services/cart'; export function useCart() { const [cartItems, setCartItems] = useState(null); // Load cart lần đầu useEffect(() => { setCartItems(getCartItems()); }, []); // Listen to cart changes from ANY source useEffect(() => { const handleCartChange = () => { setCartItems(getCartItems()); }; // Listen to custom event window.addEventListener(CART_CHANGE_EVENT, handleCartChange); // Also listen to storage event (for changes from other tabs) window.addEventListener('storage', (e) => { if (e.key === 'cart_products') { handleCartChange(); } }); return () => { window.removeEventListener(CART_CHANGE_EVENT, handleCartChange); window.removeEventListener('storage', handleCartChange); }; }, []); const refresh = useCallback(() => { setCartItems(getCartItems()); }, []); const addToCart = useCallback((productId: number, quantity: number = 1) => { const result = addProductToCart(productId, quantity); // Không cần refresh() nữa vì event listener sẽ tự động update return result; }, []); const removeFromCart = useCallback((productId: number) => { removeProductFromCart(productId); // Không cần refresh() }, []); const increase = useCallback((productId: number, amount: number = 1) => { const success = increaseQuantity(productId, amount); // Không cần refresh() return success; }, []); const decrease = useCallback((productId: number, amount: number = 1) => { const success = decreaseQuantity(productId, amount); if (!success) { console.log('Số lượng tối thiểu: 1'); } // Không cần refresh() return success; }, []); const updateQty = useCallback((productId: number, cartQuantity: number) => { const success = updateQuantity(productId, cartQuantity); if (!success) { console.log('Số lượng phải lớn hơn hoặc bằng 1'); } // Không cần refresh() return success; }, []); const clear = useCallback(() => { clearCart(); // Không cần setCartItems([]) nữa, event sẽ tự động update }, []); const isInCart = useCallback( (productId: number) => cartItems?.some(item => item.id === productId) ?? false, [cartItems] ); const getQuantity = useCallback( (productId: number) => { return cartItems?.find(item => item.id === productId)?.cartQuantity ?? 0; }, [cartItems] ); const totalItems = cartItems?.reduce((sum, item) => sum + item.cartQuantity, 0) ?? 0; return { cartItems: cartItems ?? [], cartCount: cartItems?.length ?? 0, totalItems, loading: cartItems === null, addToCart, removeFromCart, increaseQuantity: increase, decreaseQuantity: decrease, updateQuantity: updateQty, clear, isInCart, getQuantity, refresh, }; }