// App JS moved from index.html // Global variables let cart = []; let products = []; const CART_KEY = 'blue_mobile_cart_v1'; // Load products from products.json async function loadProducts() { const loading = document.getElementById('loading'); const container = document.getElementById('productsContainer'); loading.style.display = 'block'; try { // Fetch local JSON file (simulate API response) const res = await fetch('./products.json', {cache: 'no-store'}); const json = await res.json(); // Support both plain array and API-style response { status, data: { products: [...] } } if (Array.isArray(json)) { products = json; } else if (json && json.data && Array.isArray(json.data.products)) { products = json.data.products; // optional: use metadata for logging or pagination UI later console.info('Products loaded from API-style response', {total: json.data.total || products.length, meta: json.meta || null}); } else if (json && Array.isArray(json.products)) { products = json.products; // another possible shape } else { throw new Error('Unexpected products.json format'); } // Optional small delay for UX await new Promise(resolve => setTimeout(resolve, 500)); loading.style.display = 'none'; displayProducts(); // Load cart from localStorage if present const saved = localStorage.getItem(CART_KEY); if (saved) { try { cart = JSON.parse(saved) || []; } catch (e) { cart = []; } updateCartDisplay(); } } catch (err) { loading.style.display = 'none'; container.innerHTML = '
เกิดข้อผิดพลาดในการโหลดสินค้า
'; console.error(err); } } function displayProducts() { const container = document.getElementById('productsContainer'); container.innerHTML = ''; products.forEach(product => { const discountPercent = Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100); // Prefer local preprocessed WebP images when available; otherwise build WebP URLs for remote images const isLocal = !!product.image; let webpSmall, webpLarge; if (isLocal) { const imgBase = product.image; // e.g. images/product-1 webpSmall = `${imgBase}-400.webp`; webpLarge = `${imgBase}-800.webp`; } else { // Build responsive WebP URLs (Unsplash supports fm=webp) const imgBase = product.image; webpSmall = imgBase.replace(/(\?)/, '&') + '&w=400&fm=webp'; webpLarge = imgBase.replace(/(\?)/, '&') + '&w=800&fm=webp'; } const productCard = `${product.description}
ตะกร้าสินค้าว่างเปล่า
'; checkoutBtn.disabled = true; } else { cartItems.innerHTML = cart.map(item => `