/*
 * listing.js — página de listagem.
 * Lê ?cat=mulher|homem|crianca, injeta título, produtos e atualiza SEO.
 */
(function () {
  'use strict';
  const S = window.STORE;

  const params = new URLSearchParams(location.search);
  let cat = params.get('cat');
  if (!S.categories[cat]) cat = 'mulher';
  const info = S.categories[cat];
  let products = S.byCategory(cat);

  /* ---- SEO dinâmico (title, description, canonical, breadcrumb JSON-LD) ---- */
  function updateSEO() {
    const title = info.label + ' — Maison';
    document.title = title;
    setMeta('description', 'Descubra a coleção ' + info.label + ' da Maison. ' + info.tagline + '. Peças minimalistas de qualidade duradoura.');
    setProp('og:title', title);
    setProp('og:description', info.tagline);
    setCanonical(location.origin + location.pathname + '?cat=' + cat);

    const ld = {
      '@context': 'https://schema.org',
      '@type': 'CollectionPage',
      name: info.label,
      description: info.tagline,
      hasPart: products.map(function (p) {
        return {
          '@type': 'Product', name: p.name, image: p.images[0],
          offers: { '@type': 'Offer', price: p.price.toFixed(2), priceCurrency: 'EUR', availability: 'https://schema.org/InStock' }
        };
      })
    };
    injectLD(ld);
  }
  function setMeta(name, val) {
    let m = document.querySelector('meta[name="' + name + '"]');
    if (!m) { m = document.createElement('meta'); m.setAttribute('name', name); document.head.appendChild(m); }
    m.setAttribute('content', val);
  }
  function setProp(prop, val) {
    let m = document.querySelector('meta[property="' + prop + '"]');
    if (!m) { m = document.createElement('meta'); m.setAttribute('property', prop); document.head.appendChild(m); }
    m.setAttribute('content', val);
  }
  function setCanonical(href) {
    let l = document.querySelector('link[rel="canonical"]');
    if (!l) { l = document.createElement('link'); l.setAttribute('rel', 'canonical'); document.head.appendChild(l); }
    l.setAttribute('href', href);
  }
  function injectLD(obj) {
    let s = document.getElementById('ld-json');
    if (!s) { s = document.createElement('script'); s.type = 'application/ld+json'; s.id = 'ld-json'; document.head.appendChild(s); }
    s.textContent = JSON.stringify(obj);
  }

  /* ---- Render do cabeçalho ---- */
  function renderHead() {
    document.getElementById('cat-title').textContent = info.label;
    document.getElementById('cat-tag').textContent = info.tagline;
    document.getElementById('cat-count').textContent = products.length + ' peças';
  }

  /* ---- Render dos cards ---- */
  function cardHTML(p, i) {
    const swatches = p.colors.map(function (c) {
      return '<i style="background:' + c.hex + '"></i>';
    }).join('');
    const back = p.images[1] || p.images[0];
    // primeira imagem "eager" para LCP rápido; restantes lazy
    const loading = i < 2 ? 'eager' : 'lazy';
    return '' +
      '<a class="card card--' + p.span + '" href="produto.html?id=' + p.id + '" data-transition data-label="' + esc(p.name) + '" data-reveal>' +
      '  <div class="card__media">' +
      '    <span class="card__edi">' + p.editorial + '</span>' +
      '    <img class="front" src="' + p.images[0] + '" alt="' + esc(p.name) + '" width="900" height="1200" loading="' + loading + '" decoding="async">' +
      '    <img class="back" src="' + back + '" alt="" width="900" height="1200" loading="lazy" decoding="async" aria-hidden="true">' +
      '  </div>' +
      '  <div class="card__info">' +
      '    <div><h3>' + esc(p.name) + '</h3><div class="card__swatches">' + swatches + '</div></div>' +
      '    <span class="card__price">' + S.formatPrice(p.price) + '</span>' +
      '  </div>' +
      '</a>';
  }
  function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }

  function renderGrid(list) {
    const grid = document.getElementById('grid');
    grid.innerHTML = list.map(cardHTML).join('');
    if (window.APP) window.APP.initReveal();
  }

  /* ---- Filtro simples de ordenação ---- */
  function initFilters() {
    const bar = document.getElementById('filters');
    if (!bar) return;
    bar.addEventListener('click', function (e) {
      const btn = e.target.closest('button[data-sort]');
      if (!btn) return;
      bar.querySelectorAll('button').forEach(function (b) { b.classList.remove('is-active'); });
      btn.classList.add('is-active');
      const sort = btn.getAttribute('data-sort');
      const base = S.byCategory(cat).slice();
      if (sort === 'price-asc') base.sort(function (a, b) { return a.price - b.price; });
      else if (sort === 'price-desc') base.sort(function (a, b) { return b.price - a.price; });
      products = base;
      renderGrid(products);
    });
  }

  /* ---- Nav de categorias no topo da listagem ---- */
  function markNav() {
    document.querySelectorAll('[data-catnav]').forEach(function (a) {
      a.classList.toggle('is-active', a.getAttribute('data-catnav') === cat);
    });
  }

  updateSEO();
  renderHead();
  renderGrid(products);
  initFilters();
  markNav();
})();
