/*
 * product.js — página de produto único.
 * Lê ?id=..., preenche galeria (slider), opções (cores/tamanhos),
 * relacionados e injeta Product JSON-LD + meta tags para SEO.
 */
(function () {
  'use strict';
  const S = window.STORE;
  const params = new URLSearchParams(location.search);
  const id = params.get('id');
  const p = S.byId(id) || S.products[0];
  const info = S.categories[p.category];

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

  /* ------------------------------ SEO ------------------------------ */
  function updateSEO() {
    document.title = p.name + ' — Maison';
    setMeta('description', p.description.slice(0, 155));
    setProp('og:type', 'product');
    setProp('og:title', p.name + ' — Maison');
    setProp('og:description', p.description.slice(0, 155));
    setProp('og:image', p.images[0]);
    setProp('product:price:amount', p.price.toFixed(2));
    setProp('product:price:currency', 'EUR');
    setCanonical(location.origin + location.pathname + '?id=' + p.id);

    injectLD({
      '@context': 'https://schema.org',
      '@type': 'Product',
      name: p.name,
      image: p.images,
      description: p.description,
      brand: { '@type': 'Brand', name: 'Maison' },
      category: info.label,
      color: p.colors.map(function (c) { return c.name; }).join(', '),
      offers: {
        '@type': 'Offer',
        url: location.href,
        price: p.price.toFixed(2),
        priceCurrency: 'EUR',
        availability: 'https://schema.org/InStock',
        itemCondition: 'https://schema.org/NewCondition'
      }
    });
    // Breadcrumb
    injectLD({
      '@context': 'https://schema.org', '@type': 'BreadcrumbList',
      itemListElement: [
        { '@type': 'ListItem', position: 1, name: 'Início', item: location.origin + '/index.html' },
        { '@type': 'ListItem', position: 2, name: info.label, item: location.origin + '/produtos.html?cat=' + p.category },
        { '@type': 'ListItem', position: 3, name: p.name }
      ]
    }, 'ld-breadcrumb');
  }
  function setMeta(n, v) { let m = document.querySelector('meta[name="' + n + '"]'); if (!m) { m = document.createElement('meta'); m.name = n; document.head.appendChild(m); } m.content = v; }
  function setProp(pr, v) { let m = document.querySelector('meta[property="' + pr + '"]'); if (!m) { m = document.createElement('meta'); m.setAttribute('property', pr); document.head.appendChild(m); } m.content = v; }
  function setCanonical(h) { let l = document.querySelector('link[rel="canonical"]'); if (!l) { l = document.createElement('link'); l.rel = 'canonical'; document.head.appendChild(l); } l.href = h; }
  function injectLD(o, elId) { const key = elId || 'ld-product'; let s = document.getElementById(key); if (!s) { s = document.createElement('script'); s.type = 'application/ld+json'; s.id = key; document.head.appendChild(s); } s.textContent = JSON.stringify(o); }

  /* --------------------------- Galeria ---------------------------- */
  function renderGallery() {
    const track = document.getElementById('g-track');
    track.innerHTML = p.images.map(function (src, i) {
      const loading = i === 0 ? 'eager' : 'lazy';
      const prio = i === 0 ? ' fetchpriority="high"' : '';
      return '<img src="' + src + '" alt="' + esc(p.name) + ' — imagem ' + (i + 1) + '" width="900" height="1200" loading="' + loading + '" decoding="async"' + prio + '>';
    }).join('');

    const dots = document.getElementById('g-dots');
    dots.innerHTML = p.images.map(function (_, i) {
      return '<button type="button" data-go="' + i + '" aria-label="Ver imagem ' + (i + 1) + '"></button>';
    }).join('');

    let idx = 0;
    const total = p.images.length;
    const counter = document.getElementById('g-count');
    function go(n) {
      idx = (n + total) % total;
      track.style.transform = 'translateX(' + (-idx * 100) + '%)';
      counter.textContent = String(idx + 1).padStart(2, '0') + ' / ' + String(total).padStart(2, '0');
      dots.querySelectorAll('button').forEach(function (b, i) { b.classList.toggle('is-active', i === idx); });
    }
    document.getElementById('g-prev').addEventListener('click', function () { go(idx - 1); });
    document.getElementById('g-next').addEventListener('click', function () { go(idx + 1); });
    dots.addEventListener('click', function (e) { const b = e.target.closest('[data-go]'); if (b) go(+b.getAttribute('data-go')); });
    // teclado
    document.addEventListener('keydown', function (e) {
      if (e.key === 'ArrowLeft') go(idx - 1);
      if (e.key === 'ArrowRight') go(idx + 1);
    });
    // swipe (touch)
    let x0 = null;
    track.addEventListener('touchstart', function (e) { x0 = e.touches[0].clientX; }, { passive: true });
    track.addEventListener('touchend', function (e) {
      if (x0 === null) return;
      const dx = e.changedTouches[0].clientX - x0;
      if (Math.abs(dx) > 40) go(idx + (dx < 0 ? 1 : -1));
      x0 = null;
    });
    go(0);
  }

  /* --------------------------- Detalhes --------------------------- */
  function renderDetails() {
    document.getElementById('p-crumb').innerHTML =
      '<a href="index.html" data-transition data-label="Maison">Início</a> / ' +
      '<a href="produtos.html?cat=' + p.category + '" data-transition data-label="' + esc(info.label) + '">' + esc(info.label) + '</a> / <span>' + esc(p.name) + '</span>';
    document.getElementById('p-name').textContent = p.name;
    document.getElementById('p-price').textContent = S.formatPrice(p.price);
    document.getElementById('p-desc').textContent = p.description;
    document.getElementById('p-editorial-num').textContent = p.editorial;

    // Cores
    const colorRow = document.getElementById('p-colors');
    colorRow.innerHTML = p.colors.map(function (c, i) {
      return '<button type="button" class="swatch" data-color="' + esc(c.name) + '" style="background:' + c.hex + '" aria-pressed="' + (i === 0) + '" aria-label="Cor ' + esc(c.name) + '" title="' + esc(c.name) + '"></button>';
    }).join('');
    const colorName = document.getElementById('p-color-name');
    colorName.textContent = p.colors[0].name;
    colorRow.addEventListener('click', function (e) {
      const b = e.target.closest('.swatch'); if (!b) return;
      colorRow.querySelectorAll('.swatch').forEach(function (s) { s.setAttribute('aria-pressed', 'false'); });
      b.setAttribute('aria-pressed', 'true');
      colorName.textContent = b.getAttribute('data-color');
    });

    // Tamanhos
    const sizeRow = document.getElementById('p-sizes');
    sizeRow.innerHTML = p.sizes.map(function (s) {
      return '<button type="button" class="size" data-size="' + esc(s) + '" aria-pressed="false">' + esc(s) + '</button>';
    }).join('');
    const addBtn = document.getElementById('p-add');
    sizeRow.addEventListener('click', function (e) {
      const b = e.target.closest('.size'); if (!b) return;
      sizeRow.querySelectorAll('.size').forEach(function (s) { s.setAttribute('aria-pressed', 'false'); });
      b.setAttribute('aria-pressed', 'true');
      addBtn.disabled = false;
      addBtn.textContent = 'Adicionar ao cesto — ' + b.getAttribute('data-size');
    });

    addBtn.addEventListener('click', function () {
      const size = sizeRow.querySelector('.size[aria-pressed="true"]');
      if (!size) return;
      const color = colorRow.querySelector('.swatch[aria-pressed="true"]');
      const colorName = color ? color.getAttribute('data-color') : p.colors[0].name;
      window.CART.add(p.id, colorName, size.getAttribute('data-size'), 1);
      addBtn.textContent = 'Adicionado ao cesto ✓';
      window.setTimeout(function () {
        addBtn.textContent = 'Adicionar ao cesto — ' + size.getAttribute('data-size');
      }, 1600);
    });
  }

  /* -------------------------- Relacionados ------------------------ */
  function renderRelated() {
    const rel = S.byCategory(p.category).filter(function (x) { return x.id !== p.id; }).slice(0, 4);
    const grid = document.getElementById('related-grid');
    grid.innerHTML = rel.map(function (r) {
      return '' +
        '<a class="card" href="produto.html?id=' + r.id + '" data-transition data-label="' + esc(r.name) + '" data-reveal>' +
        '<div class="card__media"><img class="front" src="' + r.images[0] + '" alt="' + esc(r.name) + '" width="900" height="1200" loading="lazy" decoding="async">' +
        '<img class="back" src="' + (r.images[1] || r.images[0]) + '" alt="" aria-hidden="true" width="900" height="1200" loading="lazy" decoding="async"></div>' +
        '<div class="card__info"><h3>' + esc(r.name) + '</h3><span class="card__price">' + S.formatPrice(r.price) + '</span></div></a>';
    }).join('');
    if (window.APP) window.APP.initReveal();
  }

  updateSEO();
  renderGallery();
  renderDetails();
  renderRelated();
})();
