// Cart context — shared state in window.cart store
const CART_KEY = 'sirahana.cart';

function loadCart(){
  try { return JSON.parse(localStorage.getItem(CART_KEY) || '[]'); } catch(e){ return []; }
}
function saveCart(items){
  try { localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch(e){}
}

function useCart(){
  const [items, setItems] = React.useState(loadCart());
  React.useEffect(()=>{
    const sync = () => setItems(loadCart());
    window.addEventListener('cart:sync', sync);
    return () => window.removeEventListener('cart:sync', sync);
  }, []);
  const update = (next) => {
    saveCart(next);
    setItems(next);
    window.dispatchEvent(new Event('cart:sync'));
  };
  const add = (item) => {
    const cur = loadCart();
    cur.push({...item, lineId: Date.now() + Math.random()});
    update(cur);
  };
  const remove = (lineId) => update(loadCart().filter(i => i.lineId !== lineId));
  const setQty = (lineId, qty) => update(loadCart().map(i => i.lineId===lineId ? {...i, qty: Math.max(1, qty)} : i));
  const clear  = () => update([]);
  const count  = items.reduce((s,i)=>s+(i.qty||1), 0);
  const subtotal = items.reduce((s,i)=>s+(i.price||0)*(i.qty||1), 0);
  return { items, add, remove, setQty, clear, count, subtotal };
}

window.useCart = useCart;
