import { hydrateCart, subscribe, getSnapshot, updateQuantity, removeItem, formatPrice, } from "/js/cart.js"; function escapeHtml(s) { return String(s) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """); } /** Cart page: items + totals only (checkout is a separate step). */ export function initCartPage() { const root = document.querySelector("[data-cart-page]"); if (!root) return; hydrateCart(); const list = root.querySelector("[data-cart-lines]"); const totalEl = root.querySelector("[data-cart-total]"); const checkoutBtn = root.querySelector("[data-cart-checkout]"); const emptyEl = root.querySelector("[data-cart-empty]"); const contentEl = root.querySelector("[data-cart-content]"); function render(snap) { const empty = !snap.items.length; if (emptyEl) emptyEl.hidden = !empty; if (contentEl) contentEl.hidden = empty; if (checkoutBtn) { if (empty) checkoutBtn.setAttribute("disabled", ""); else checkoutBtn.removeAttribute("disabled"); } if (!list || !totalEl) return; if (empty) { list.innerHTML = ""; totalEl.textContent = formatPrice(0); return; } list.innerHTML = snap.items .map( (item) => `
${ item.image ? `` : `
` }
${escapeHtml(item.name)}
${formatPrice(item.price)}
${item.quantity}
` ) .join(""); totalEl.textContent = formatPrice(snap.subtotal); list.querySelectorAll(".cart-line").forEach((row) => { const id = row.getAttribute("data-id"); const item = snap.items.find((i) => i.productId === id); if (!item || !id) return; row.querySelector("[data-qty-dec]")?.addEventListener("click", () => updateQuantity(id, item.quantity - 1) ); row.querySelector("[data-qty-inc]")?.addEventListener("click", () => updateQuantity(id, item.quantity + 1) ); row.querySelector("[data-qty-remove]")?.addEventListener("click", () => removeItem(id) ); }); } subscribe(render); render(getSnapshot()); }