/*
 * cart-page.js — renderiza e gere a página do cesto (carrinho.html).
 */
(function () {
  'use strict';
  const S = window.STORE, CART = window.CART;
  const linesEl = document.getElementById('cart-lines');

  function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }

  function lineHTML(l) {
    return '' +
      '<article class="line" data-key="' + esc(l.key) + '">' +
      '  <a class="line__media" href="produto.html?id=' + l.id + '" data-transition data-label="' + esc(l.name) + '">' +
      '    <img src="' + l.image + '" alt="' + esc(l.name) + '" width="300" height="400" loading="lazy" decoding="async">' +
      '  </a>' +
      '  <div class="line__body">' +
      '    <div class="line__top">' +
      '      <h3><a href="produto.html?id=' + l.id + '" data-transition data-label="' + esc(l.name) + '">' + esc(l.name) + '</a></h3>' +
      '      <button class="line__remove" type="button" data-remove aria-label="Remover ' + esc(l.name) + '">Remover</button>' +
      '    </div>' +
      '    <p class="line__variant">' + esc(l.color) + ' · Tam. ' + esc(l.size) + '</p>' +
      '    <div class="line__foot">' +
      '      <div class="qty" role="group" aria-label="Quantidade">' +
      '        <button type="button" data-dec aria-label="Diminuir">−</button>' +
      '        <span data-qty>' + l.qty + '</span>' +
      '        <button type="button" data-inc aria-label="Aumentar">+</button>' +
      '      </div>' +
      '      <span class="line__price">' + S.formatPrice(l.lineTotal) + '</span>' +
      '    </div>' +
      '  </div>' +
      '</article>';
  }

  function emptyHTML() {
    return '' +
      '<div class="cart-empty">' +
      '  <p class="display">O cesto está vazio.</p>' +
      '  <p>Ainda não adicionou nada. Explore as coleções e volte quando quiser.</p>' +
      '  <a class="add" href="produtos.html?cat=mulher" data-transition data-label="Mulher" style="display:inline-block;width:auto;padding:1rem 2rem;">Ver coleção</a>' +
      '</div>';
  }

  function renderSummary() {
    const sub = CART.subtotal(), ship = CART.shipping(), total = CART.total();
    document.getElementById('s-sub').textContent = S.formatPrice(sub);
    document.getElementById('s-ship').textContent = ship === 0 ? (sub === 0 ? '—' : 'Grátis') : S.formatPrice(ship);
    document.getElementById('s-total').textContent = S.formatPrice(total);
    const note = document.getElementById('s-freeship');
    if (sub > 0 && sub < 50) note.textContent = 'Faltam ' + S.formatPrice(50 - sub) + ' para portes grátis.';
    else if (sub >= 50) note.textContent = 'Tem portes grátis ✓';
    else note.textContent = '';

    const btn = document.getElementById('go-checkout');
    const empty = CART.count() === 0;
    btn.classList.toggle('is-disabled', empty);
    if (empty) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
  }

  function render() {
    const lines = CART.detailed();
    linesEl.innerHTML = lines.length ? lines.map(lineHTML).join('') : emptyHTML();
    renderSummary();
  }

  linesEl.addEventListener('click', function (e) {
    const art = e.target.closest('.line'); if (!art) return;
    const key = art.getAttribute('data-key');
    const cur = CART.detailed().find(function (l) { return l.key === key; });
    if (!cur) return;
    if (e.target.closest('[data-remove]')) CART.remove(key);
    else if (e.target.closest('[data-inc]')) CART.setQty(key, cur.qty + 1);
    else if (e.target.closest('[data-dec]')) CART.setQty(key, cur.qty - 1);
  });

  // Bloqueia checkout se vazio
  document.getElementById('go-checkout').addEventListener('click', function (e) {
    if (CART.count() === 0) e.preventDefault();
  });

  document.addEventListener('cart:change', render);
  render();
})();
