/*
 * cart.js — carrinho persistente (localStorage), partilhado por todas as páginas.
 * API global window.CART. Emite o evento 'cart:change' sempre que muda,
 * para os badges/contadores se atualizarem em qualquer página aberta.
 */
(function () {
  'use strict';
  const KEY = 'maison_cart_v1';
  const S = window.STORE;

  function read() {
    try { return JSON.parse(localStorage.getItem(KEY)) || []; }
    catch (e) { return []; }
  }
  function write(items) {
    localStorage.setItem(KEY, JSON.stringify(items));
    document.dispatchEvent(new CustomEvent('cart:change', { detail: { items: items } }));
    renderBadge();
  }
  function lineKey(id, color, size) { return id + '|' + color + '|' + size; }

  const CART = {
    items: read,

    /** Adiciona (ou incrementa se a mesma variante já existir) */
    add: function (id, color, size, qty) {
      qty = qty || 1;
      const items = read();
      const key = lineKey(id, color, size);
      const found = items.find(function (i) { return i.key === key; });
      if (found) found.qty += qty;
      else items.push({ key: key, id: id, color: color, size: size, qty: qty });
      write(items);
      return CART.count();
    },

    setQty: function (key, qty) {
      const items = read();
      const it = items.find(function (i) { return i.key === key; });
      if (!it) return;
      it.qty = Math.max(1, qty);
      write(items);
    },

    remove: function (key) {
      write(read().filter(function (i) { return i.key !== key; }));
    },

    clear: function () { write([]); },

    count: function () {
      return read().reduce(function (n, i) { return n + i.qty; }, 0);
    },

    /** Devolve as linhas "hidratadas" com dados do produto (nome, preço, imagem) */
    detailed: function () {
      return read().map(function (i) {
        const p = S ? S.byId(i.id) : null;
        if (!p) return null;
        return {
          key: i.key, id: i.id, color: i.color, size: i.size, qty: i.qty,
          name: p.name, price: p.price, image: p.images[0], category: p.category,
          lineTotal: p.price * i.qty
        };
      }).filter(Boolean);
    },

    subtotal: function () {
      return CART.detailed().reduce(function (s, l) { return s + l.lineTotal; }, 0);
    },

    /** Portes: grátis acima de 50€, senão 3,95€ (0 se cesto vazio) */
    shipping: function () {
      const sub = CART.subtotal();
      if (sub === 0) return 0;
      return sub >= 50 ? 0 : 3.95;
    },

    total: function () { return CART.subtotal() + CART.shipping(); }
  };

  function renderBadge() {
    const n = CART.count();
    document.querySelectorAll('[data-cart-count]').forEach(function (el) {
      el.textContent = n;
      el.classList.toggle('has-items', n > 0);
    });
  }

  window.CART = CART;
  document.addEventListener('DOMContentLoaded', renderBadge);
  // Sincroniza entre separadores do browser
  window.addEventListener('storage', function (e) { if (e.key === KEY) renderBadge(); });
})();
