(function () { 'use strict'; const customerEl = document.querySelector('[data-customer-id]'); const customerId = customerEl ? customerEl.dataset.customerId : 'guest'; const STORAGE_KEY = `favoritos:${customerId}`; const LOGIN_URL = '/account/login'; // ---------- Storage ---------- function getFavoritos() { try { const raw = localStorage.getItem(STORAGE_KEY); const list = raw ? JSON.parse(raw) : []; return Array.isArray(list) ? list : []; } catch (e) { return []; } } function setFavoritos(list) { localStorage.setItem(STORAGE_KEY, JSON.stringify(list)); window.dispatchEvent(new CustomEvent('favoritos:change', { detail: { list } })); } function toggleFavorito(handle) { const list = getFavoritos(); const idx = list.indexOf(handle); if (idx >= 0) { list.splice(idx, 1); } else { list.push(handle); } setFavoritos(list); return idx < 0; // true = adicionou, false = removeu } // ---------- Botão de favoritar (cards/PDP) ---------- function bindFavoritoButtons(root) { const scope = root || document; const list = getFavoritos(); scope.querySelectorAll('[data-favorito-toggle]').forEach((btn) => { if (btn.dataset.bound === '1') return; btn.dataset.bound = '1'; const handle = btn.dataset.productHandle; const isFav = list.includes(handle); btn.setAttribute('aria-pressed', isFav ? 'true' : 'false'); btn.setAttribute('aria-label', isFav ? 'Remover dos favoritos' : 'Adicionar aos favoritos'); btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); // Sem login → manda pro login mantendo a URL atual if (customerId === 'guest') { const returnUrl = encodeURIComponent(window.location.pathname + window.location.search); window.location.href = `${LOGIN_URL}?return_url=${returnUrl}`; return; } const added = toggleFavorito(handle); btn.setAttribute('aria-pressed', added ? 'true' : 'false'); btn.setAttribute('aria-label', added ? 'Remover dos favoritos' : 'Adicionar aos favoritos'); }); }); } // Mantém botões sincronizados entre abas / cards window.addEventListener('favoritos:change', (e) => { const list = e.detail.list; document.querySelectorAll('[data-favorito-toggle]').forEach((btn) => { const handle = btn.dataset.productHandle; const isFav = list.includes(handle); btn.setAttribute('aria-pressed', isFav ? 'true' : 'false'); }); }); // ---------- Página /pages/favoritos ---------- function formatPrice(cents) { return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: window.Shopify && window.Shopify.currency ? window.Shopify.currency.active : 'BRL' }); } async function fetchProduto(handle) { try { const res = await fetch(`/products/${handle}.js`); if (!res.ok) return null; return await res.json(); } catch (e) { return null; } } async function renderPaginaFavoritos() { const grid = document.getElementById('favoritos-grid'); const empty = document.getElementById('favoritos-empty'); if (!grid) return; const list = getFavoritos(); if (list.length === 0) { grid.innerHTML = ''; if (empty) empty.hidden = false; return; } if (empty) empty.hidden = true; grid.innerHTML = '
'; const produtos = await Promise.all(list.map(fetchProduto)); const validos = produtos.filter(Boolean); // Remove handles que sumiram (produto deletado etc) const handlesValidos = validos.map((p) => p.handle); if (handlesValidos.length !== list.length) { setFavoritos(handlesValidos); } grid.innerHTML = ''; if (validos.length === 0) { if (empty) empty.hidden = false; return; } validos.forEach((p) => { const img = p.featured_image || (p.images && p.images[0]) || ''; const card = document.createElement('article'); card.className = 'favorito-card'; card.innerHTML = `
${p.title}
`; grid.appendChild(card); }); grid.querySelectorAll('[data-remove]').forEach((btn) => { btn.addEventListener('click', () => { toggleFavorito(btn.dataset.remove); renderPaginaFavoritos(); }); }); } // ---------- Init ---------- function init() { bindFavoritoButtons(); renderPaginaFavoritos(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } // Para temas que carregam produtos via AJAX (filtros, paginação infinita etc): // dispare `window.dispatchEvent(new Event('favoritos:rebind'))` depois de inserir novos cards. window.addEventListener('favoritos:rebind', () => bindFavoritoButtons()); })();


