/* product-recent.js — records the current product into localStorage so the * homepage "Recently Viewed" strip can show it. Reads product data from a * JSON blob the product page emits as window.WCM_PRODUCT, or falls back to * scraping the page. Keeps the 12 most recent, newest first, de-duplicated. */ (function(){ var KEY = 'wcm_recent_products'; var MAX = 12; function currentProduct(){ // Preferred: explicit data from the product page if (window.WCM_PRODUCT && window.WCM_PRODUCT.url && window.WCM_PRODUCT.name) { return { url: window.WCM_PRODUCT.url, name: window.WCM_PRODUCT.name, img: window.WCM_PRODUCT.img || '' }; } // Fallback: only act on real product pages (/product/Name/ID) if (!/^\/product\//.test(location.pathname)) return null; var name = ''; var h1 = document.querySelector('h1, .product-name h1, .product-name'); if (h1) name = h1.textContent.replace(/\s+/g,' ').trim(); if (!name) { name = (document.title || '').replace(/\s*\|.*$/,'').trim(); } if (!name) return null; var img = ''; var pimg = document.querySelector('.cloud-zoom img, .large-image img, .product-image img'); if (pimg && pimg.getAttribute('src')) img = pimg.getAttribute('src'); return { url: location.pathname, name: name, img: img }; } var p = currentProduct(); if (!p) return; var list = []; try { list = JSON.parse(localStorage.getItem(KEY) || '[]'); } catch(e){ list = []; } if (!Array.isArray(list)) list = []; // remove any existing entry with the same url, then unshift to front list = list.filter(function(it){ return it && it.url !== p.url; }); list.unshift(p); if (list.length > MAX) list = list.slice(0, MAX); try { localStorage.setItem(KEY, JSON.stringify(list)); } catch(e){} })();