// store.jsx — Estat real del carret (cistella) i de la comanda.
//
// Substitueix les dades "pintades" del prototip per un carret de veritat:
// afegir, canviar quantitat, treure i buidar, amb persistència a localStorage.
// S'exposa via context de React i el hook useCart().

const CartContext = React.createContext(null);
const CART_KEY = 'ke_cart_v1';

function loadCart() {
  try {
    const raw = JSON.parse(localStorage.getItem(CART_KEY));
    return Array.isArray(raw) ? raw : [];
  } catch (e) {
    return [];
  }
}

// Pas d'increment segons la unitat: el peix a pes va de mig en mig quilo.
function stepFor(unit) {
  return unit === 'kg' ? 0.5 : 1;
}
function defaultQty(unit) {
  return unit === 'kg' ? 1 : 1;
}

function cartReducer(state, action) {
  switch (action.type) {
    case 'add': {
      const it = action.item;
      const idx = state.findIndex((x) => x.id === it.id && x.cut === it.cut);
      if (idx >= 0) {
        const next = state.slice();
        next[idx] = { ...next[idx], qty: +(next[idx].qty + it.qty).toFixed(2), note: it.note || next[idx].note };
        return next;
      }
      return [...state, it];
    }
    case 'setQty': {
      return state
        .map((x) => (x.id === action.id && x.cut === action.cut ? { ...x, qty: +action.qty.toFixed(2) } : x))
        .filter((x) => x.qty > 0);
    }
    case 'remove':
      return state.filter((x) => !(x.id === action.id && x.cut === action.cut));
    case 'clear':
      return [];
    default:
      return state;
  }
}

function CartProvider({ children }) {
  const [items, dispatch] = React.useReducer(cartReducer, null, loadCart);

  React.useEffect(() => {
    try { localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch (e) {}
  }, [items]);

  const value = React.useMemo(() => {
    const count = items.length;
    const subtotal = items.reduce((s, it) => s + (it.price || 0) * (it.qty || 0), 0);
    return {
      items,
      count,
      subtotal,
      add(product, opts = {}) {
        const unit = product.unit || 'kg';
        dispatch({
          type: 'add',
          item: {
            id: product.id,
            name: product.n || product.name,
            price: product.price || 0,
            unit,
            qty: opts.qty != null ? opts.qty : defaultQty(unit),
            image: product.p || product.image || '',
            cut: opts.cut || (product.cuts && product.cuts[0]) || '',
            note: opts.note || '',
          },
        });
      },
      inc(it) { dispatch({ type: 'setQty', id: it.id, cut: it.cut, qty: it.qty + stepFor(it.unit) }); },
      dec(it) { dispatch({ type: 'setQty', id: it.id, cut: it.cut, qty: Math.max(0, it.qty - stepFor(it.unit)) }); },
      setQty(it, qty) { dispatch({ type: 'setQty', id: it.id, cut: it.cut, qty: Math.max(0, qty) }); },
      remove(it) { dispatch({ type: 'remove', id: it.id, cut: it.cut }); },
      clear() { dispatch({ type: 'clear' }); },
    };
  }, [items]);

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

function useCart() {
  return React.useContext(CartContext);
}

// Format d'una quantitat per mostrar: "1,5 kg" o "2 ud".
function fmtQty(qty, unit) {
  const n = Number(qty).toFixed(unit === 'kg' ? 1 : 0).replace('.', ',');
  return n + ' ' + (unit || 'ud');
}

Object.assign(window, { CartProvider, useCart, fmtQty, cartStepFor: stepFor });
