-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
879 lines (771 loc) · 31.1 KB
/
script.js
File metadata and controls
879 lines (771 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
/* ============================================================
MAISON — E-Commerce JavaScript
State Management, Rendering, LocalStorage, Interactions
============================================================ */
'use strict';
// ─────────────────────────────────────────────
// 1. PRODUCT DATA
// ─────────────────────────────────────────────
const PRODUCTS = [
{
id: 1,
name: 'Travertine Side Table',
category: 'furniture',
price: 485,
emoji: '🪨',
rating: 4.8,
popularity: 95,
stock: 4,
description: 'Hand-carved Italian travertine with brushed brass legs. Each piece carries the natural variation of the stone — no two tables are identical. A quiet anchor for any room.',
badge: 'new',
},
{
id: 2,
name: 'Rattan Arc Floor Lamp',
category: 'lighting',
price: 320,
emoji: '🌿',
rating: 4.6,
popularity: 88,
stock: 7,
description: 'Woven natural rattan shade with a matte black powder-coated arc. Casts a warm, diffused light ideal for reading nooks and living rooms alike.',
badge: null,
},
{
id: 3,
name: 'Linen Cloud Throw',
category: 'textiles',
price: 128,
emoji: '☁️',
rating: 4.9,
popularity: 99,
stock: 2,
description: 'Pre-washed Belgian linen in a stone-washed finish. Breathable year-round, endlessly beautiful. The kind of throw that gets better with every wash.',
badge: null,
},
{
id: 4,
name: 'Stoneware Ritual Vase',
category: 'ceramics',
price: 96,
emoji: '🏺',
rating: 4.7,
popularity: 82,
stock: 11,
description: 'Thrown on the wheel by independent ceramicists in Jaipur. Matte ash glaze with subtle iron oxide flecks. Pairs effortlessly with dried botanicals.',
badge: null,
},
{
id: 5,
name: 'Oak & Cane Lounge Chair',
category: 'furniture',
price: 760,
emoji: '🪑',
rating: 4.5,
popularity: 78,
stock: 3,
description: 'Solid white oak frame with hand-woven natural cane back and seat. Ergonomically shaped for long evenings with a good book.',
badge: 'new',
},
{
id: 6,
name: 'Handblown Glass Pendant',
category: 'lighting',
price: 210,
emoji: '💡',
rating: 4.6,
popularity: 85,
stock: 6,
description: 'Mouth-blown borosilicate glass with an amber tint. Each pendant is unique, shaped by breath and gravity. Cloth cord in natural linen.',
badge: null,
},
{
id: 7,
name: 'Merino Boucle Cushion',
category: 'textiles',
price: 74,
emoji: '🟫',
rating: 4.8,
popularity: 93,
stock: 14,
description: 'Textured boucle in a warm oatmeal tone. Filled with down-alternative. The perfect weight — neither too full nor too flat.',
badge: null,
},
{
id: 8,
name: 'Matcha Glaze Tea Set',
category: 'ceramics',
price: 144,
emoji: '🍵',
rating: 4.9,
popularity: 91,
stock: 5,
description: 'A teapot and two cups in a layered matcha green glaze. Microwave and dishwasher safe. Designed for the meditative ritual of a morning cup.',
badge: null,
},
{
id: 9,
name: 'Marble Bookends',
category: 'accents',
price: 88,
emoji: '📚',
rating: 4.4,
popularity: 72,
stock: 9,
description: 'Solid white Carrara marble with a polished face and raw back edge. Heavy enough to hold your largest volumes, elegant enough to be the subject of the shelf.',
badge: null,
},
{
id: 10,
name: 'Walnut Serving Board',
category: 'accents',
price: 115,
emoji: '🟤',
rating: 4.7,
popularity: 86,
stock: 8,
description: 'End-grain American black walnut. Oiled with food-safe mineral oil. Beautiful enough to leave on the counter; functional enough for everyday use.',
badge: null,
},
{
id: 11,
name: 'Handwoven Jute Rug',
category: 'textiles',
price: 290,
emoji: '🟡',
rating: 4.5,
popularity: 80,
stock: 0,
description: 'Flatwoven natural jute in a herringbone pattern. 180 × 270 cm. Adds texture and warmth to any room without competing with your furniture.',
badge: null,
},
{
id: 12,
name: 'Aged Brass Candleholder',
category: 'accents',
price: 62,
emoji: '🕯️',
rating: 4.6,
popularity: 77,
stock: 12,
description: 'Cast brass with a living patina finish — the surface deepens with age and handling. Holds standard-diameter pillar candles. Sold as a set of two.',
badge: null,
},
];
// ─────────────────────────────────────────────
// 2. STATE
// ─────────────────────────────────────────────
let cart = loadFromStorage('maison_cart') || []; // [{ productId, qty }]
let wishlist = loadFromStorage('maison_wishlist') || []; // [productId]
let currentPage = 'catalog';
let currentFilter = 'all';
let currentSearch = '';
let currentSort = 'default';
let currentPrice = 'all';
let detailProduct = null;
let detailQty = 1;
let couponApplied = false;
// ─────────────────────────────────────────────
// 3. LOCAL STORAGE HELPERS
// ─────────────────────────────────────────────
function saveToStorage(key, value) {
try { localStorage.setItem(key, JSON.stringify(value)); } catch(e) {}
}
function loadFromStorage(key) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : null;
} catch(e) { return null; }
}
// ─────────────────────────────────────────────
// 4. TOAST NOTIFICATION
// ─────────────────────────────────────────────
let toastTimeout;
function showToast(message) {
const el = document.getElementById('toast');
el.textContent = message;
el.classList.add('show');
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => el.classList.remove('show'), 2800);
}
// ─────────────────────────────────────────────
// 5. THEME
// ─────────────────────────────────────────────
function initTheme() {
const saved = loadFromStorage('maison_theme') || 'light';
setTheme(saved);
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
document.getElementById('theme-icon').textContent = theme === 'dark' ? '☀' : '☽';
saveToStorage('maison_theme', theme);
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
setTheme(current === 'dark' ? 'light' : 'dark');
}
// ─────────────────────────────────────────────
// 6. MOBILE NAV
// ─────────────────────────────────────────────
function toggleMobileMenu() {
document.getElementById('site-nav').classList.toggle('open');
}
// ─────────────────────────────────────────────
// 7. PAGE NAVIGATION
// ─────────────────────────────────────────────
function showPage(page) {
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.getElementById(`page-${page}`).classList.add('active');
currentPage = page;
window.scrollTo({ top: 0, behavior: 'smooth' });
document.getElementById('site-nav').classList.remove('open');
// Render appropriate page
if (page === 'catalog') renderProducts();
if (page === 'cart') renderCart();
if (page === 'wishlist') renderWishlist();
if (page === 'checkout') renderCheckout();
}
// ─────────────────────────────────────────────
// 8. CATALOG — FILTER + SORT + RENDER
// ─────────────────────────────────────────────
function getFilteredProducts() {
let items = [...PRODUCTS];
// Category filter
if (currentFilter !== 'all') {
items = items.filter(p => p.category === currentFilter);
}
// Search
if (currentSearch.trim()) {
const q = currentSearch.toLowerCase().trim();
items = items.filter(p =>
p.name.toLowerCase().includes(q) ||
p.category.toLowerCase().includes(q) ||
p.description.toLowerCase().includes(q)
);
}
// Price range
if (currentPrice !== 'all') {
const [min, max] = currentPrice.split('-').map(Number);
items = items.filter(p => p.price >= min && p.price <= max);
}
// Sort
switch (currentSort) {
case 'price-asc': items.sort((a, b) => a.price - b.price); break;
case 'price-desc': items.sort((a, b) => b.price - a.price); break;
case 'popularity': items.sort((a, b) => b.popularity - a.popularity); break;
default: break; // Keep original order (featured)
}
return items;
}
function renderProducts() {
const grid = document.getElementById('product-grid');
const noResults = document.getElementById('no-results');
const countEl = document.getElementById('result-count');
const items = getFilteredProducts();
grid.innerHTML = '';
countEl.textContent = `${items.length} ${items.length === 1 ? 'product' : 'products'}`;
if (items.length === 0) {
noResults.classList.remove('hidden');
grid.style.display = 'none';
} else {
noResults.classList.add('hidden');
grid.style.display = '';
items.forEach((product, i) => {
const card = buildProductCard(product);
card.style.animationDelay = `${i * 0.04}s`;
grid.appendChild(card);
});
}
}
function buildProductCard(product) {
const isWishlisted = wishlist.includes(product.id);
const inCart = cart.find(c => c.productId === product.id);
const outOfStock = product.stock === 0;
// Stock label
let stockLabel = `In stock`;
let stockClass = '';
if (product.stock === 0) { stockLabel = 'Out of stock'; stockClass = 'out'; }
else if (product.stock <= 4) { stockLabel = `Only ${product.stock} left`; stockClass = 'low'; }
// Badge
let badgeHTML = '';
if (product.badge === 'new') badgeHTML = `<span class="product-card-badge badge-new">New</span>`;
if (product.stock > 0 && product.stock <= 4) badgeHTML = `<span class="product-card-badge badge-low">Low Stock</span>`;
if (product.stock === 0) badgeHTML = `<span class="product-card-badge badge-out">Sold Out</span>`;
const stars = '★'.repeat(Math.floor(product.rating)) + (product.rating % 1 >= 0.5 ? '½' : '');
const card = document.createElement('div');
card.className = 'product-card';
card.setAttribute('role', 'listitem');
card.innerHTML = `
<div class="product-card-image" onclick="openDetail(${product.id})">
${badgeHTML}
<span class="img-emoji">${product.emoji}</span>
<button
class="wishlist-toggle ${isWishlisted ? 'active' : ''}"
onclick="event.stopPropagation(); toggleWishlist(${product.id})"
aria-label="${isWishlisted ? 'Remove from wishlist' : 'Add to wishlist'}"
title="${isWishlisted ? 'Remove from wishlist' : 'Add to wishlist'}"
>${isWishlisted ? '♥' : '♡'}</button>
</div>
<div class="product-card-info">
<p class="product-card-category">${product.category}</p>
<h3 class="product-card-name" onclick="openDetail(${product.id})">${product.name}</h3>
<div class="product-card-meta">
<span class="product-card-price">₹${product.price}</span>
<span class="product-card-rating">${stars} ${product.rating}</span>
</div>
<p class="product-card-stock ${stockClass}">${stockLabel}</p>
<div class="card-actions">
<button
class="btn-primary"
onclick="addToCart(${product.id})"
${outOfStock ? 'disabled' : ''}
aria-label="Add ${product.name} to cart"
>${outOfStock ? 'Out of Stock' : inCart ? 'Add Again' : 'Add to Cart'}</button>
</div>
</div>
`;
return card;
}
// ─────────────────────────────────────────────
// 9. FILTER / SEARCH HANDLERS
// ─────────────────────────────────────────────
function filterByCategory(cat) {
currentFilter = cat;
// Sync nav active state
document.querySelectorAll('.site-nav a').forEach(a => a.classList.remove('active'));
renderProducts();
}
function handleSearch(val) {
currentSearch = val;
renderProducts();
}
function applyFilters() {
currentPrice = document.getElementById('price-filter').value;
currentSort = document.getElementById('sort-filter').value;
renderProducts();
}
function clearFilters() {
currentFilter = 'all';
currentSearch = '';
currentPrice = 'all';
currentSort = 'default';
document.getElementById('search-input').value = '';
document.getElementById('price-filter').value = 'all';
document.getElementById('sort-filter').value = 'default';
renderProducts();
}
function scrollToProducts() {
document.getElementById('products-section').scrollIntoView({ behavior: 'smooth' });
}
// ─────────────────────────────────────────────
// 10. PRODUCT DETAIL
// ─────────────────────────────────────────────
function openDetail(productId) {
detailProduct = PRODUCTS.find(p => p.id === productId);
detailQty = 1;
if (!detailProduct) return;
renderDetail();
renderRecommendations();
showPage('detail');
}
function renderDetail() {
const p = detailProduct;
if (!p) return;
const isWishlisted = wishlist.includes(p.id);
const outOfStock = p.stock === 0;
let stockLabel = `${p.stock} in stock`;
let stockClass = 'good';
if (p.stock === 0) { stockLabel = 'Out of stock'; stockClass = 'out'; }
else if (p.stock <= 4) { stockLabel = `Only ${p.stock} left!`; stockClass = 'low'; }
const stars = '★'.repeat(Math.floor(p.rating)) + (p.rating % 1 >= 0.5 ? '½' : '');
document.getElementById('detail-container').innerHTML = `
<div class="detail-image">${p.emoji}</div>
<div class="detail-info">
<p class="detail-category">${p.category}</p>
<h1 class="detail-name">${p.name}</h1>
<p class="detail-rating">${stars} ${p.rating} rating</p>
<p class="detail-price">₹${p.price}</p>
<p class="detail-desc">${p.description}</p>
<p class="detail-stock ${stockClass}">${stockLabel}</p>
<div class="detail-qty" id="detail-qty-row" ${outOfStock ? 'style="display:none"' : ''}>
<button class="qty-btn" onclick="changeDetailQty(-1)" aria-label="Decrease quantity">−</button>
<span class="qty-display" id="detail-qty-display">${detailQty}</span>
<button class="qty-btn" onclick="changeDetailQty(1)" aria-label="Increase quantity">+</button>
</div>
<div class="detail-actions">
<button
class="btn-primary"
${outOfStock ? 'disabled' : ''}
onclick="addToCartQty(${p.id})"
aria-label="Add to cart"
>${outOfStock ? 'Out of Stock' : 'Add to Cart'}</button>
<button
class="detail-wishlist ${isWishlisted ? 'active' : ''}"
id="detail-wishlist-btn"
onclick="toggleWishlist(${p.id}, true)"
aria-label="${isWishlisted ? 'Remove from wishlist' : 'Save to wishlist'}"
>${isWishlisted ? '♥' : '♡'}</button>
</div>
</div>
`;
}
function changeDetailQty(delta) {
if (!detailProduct) return;
detailQty = Math.max(1, Math.min(detailProduct.stock, detailQty + delta));
document.getElementById('detail-qty-display').textContent = detailQty;
}
function addToCartQty(productId) {
for (let i = 0; i < detailQty; i++) addToCart(productId, true);
showToast(`${detailProduct.name} × ${detailQty} added to cart`);
updateBadges();
}
function renderRecommendations() {
const p = detailProduct;
const section = document.getElementById('recommendations-section');
const grid = document.getElementById('recommendations-grid');
const related = PRODUCTS.filter(r => r.category === p.category && r.id !== p.id).slice(0, 4);
if (related.length === 0) { section.style.display = 'none'; return; }
section.style.display = '';
grid.innerHTML = '';
related.forEach((product, i) => {
const card = buildProductCard(product);
card.style.animationDelay = `${i * 0.05}s`;
grid.appendChild(card);
});
}
// ─────────────────────────────────────────────
// 11. CART
// ─────────────────────────────────────────────
function addToCart(productId, silent = false) {
const product = PRODUCTS.find(p => p.id === productId);
if (!product || product.stock === 0) return;
const existing = cart.find(c => c.productId === productId);
const totalInCart = existing ? existing.qty : 0;
if (totalInCart >= product.stock) {
showToast(`Maximum stock reached for "${product.name}"`);
return;
}
if (existing) {
existing.qty++;
} else {
cart.push({ productId, qty: 1 });
}
saveToStorage('maison_cart', cart);
updateBadges();
if (!silent) {
showToast(`"${product.name}" added to cart`);
renderProducts(); // refresh card state
}
}
function removeFromCart(productId) {
cart = cart.filter(c => c.productId !== productId);
saveToStorage('maison_cart', cart);
updateBadges();
renderCart();
showToast('Item removed from cart');
}
function changeCartQty(productId, delta) {
const item = cart.find(c => c.productId === productId);
const product = PRODUCTS.find(p => p.id === productId);
if (!item || !product) return;
const newQty = item.qty + delta;
if (newQty <= 0) { removeFromCart(productId); return; }
if (newQty > product.stock) { showToast('No more stock available'); return; }
item.qty = newQty;
saveToStorage('maison_cart', cart);
updateBadges();
renderCart();
}
function getCartTotal() {
return cart.reduce((sum, item) => {
const p = PRODUCTS.find(p => p.id === item.productId);
return sum + (p ? p.price * item.qty : 0);
}, 0);
}
function renderCart() {
const layout = document.getElementById('cart-layout');
const emptyEl = document.getElementById('cart-empty');
const itemsEl = document.getElementById('cart-items');
const summaryEl= document.getElementById('cart-summary');
if (cart.length === 0) {
layout.style.display = 'none';
emptyEl.classList.remove('hidden');
return;
}
layout.style.display = '';
emptyEl.classList.add('hidden');
// Items
itemsEl.innerHTML = '';
cart.forEach(item => {
const p = PRODUCTS.find(prod => prod.id === item.productId);
if (!p) return;
const div = document.createElement('div');
div.className = 'cart-item';
div.innerHTML = `
<div class="cart-item-img">${p.emoji}</div>
<div>
<p class="cart-item-category">${p.category}</p>
<p class="cart-item-name">${p.name}</p>
<div class="cart-item-controls">
<button class="cart-qty-btn" onclick="changeCartQty(${p.id}, -1)" aria-label="Decrease">−</button>
<span class="cart-qty">${item.qty}</span>
<button class="cart-qty-btn" onclick="changeCartQty(${p.id}, 1)" aria-label="Increase">+</button>
</div>
</div>
<div class="cart-item-price-col">
<p class="cart-item-price">₹${(p.price * item.qty).toLocaleString('en-IN')}</p>
<button class="cart-item-remove" onclick="removeFromCart(${p.id})">Remove</button>
</div>
`;
itemsEl.appendChild(div);
});
// Summary
renderCartSummary(summaryEl);
}
function renderCartSummary(container) {
const subtotal = getCartTotal();
const discount = couponApplied ? Math.round(subtotal * 0.1) : 0;
const shipping = subtotal > 400 ? 0 : 40;
const total = subtotal - discount + shipping;
container.innerHTML = `
<h2>Order Summary</h2>
<div class="summary-line"><span>Subtotal (${cart.reduce((s,i)=>s+i.qty,0)} items)</span><span>₹${subtotal.toLocaleString('en-IN')}</span></div>
<div class="summary-line"><span>Shipping</span><span>${shipping === 0 ? '<span style="color:#27ae60">Free</span>' : '₹'+shipping}</span></div>
${couponApplied ? `<div class="summary-line discount"><span>Coupon (SAVE10)</span><span>−₹${discount.toLocaleString('en-IN')}</span></div>` : ''}
<div class="summary-total"><span>Total</span><span>₹${total.toLocaleString('en-IN')}</span></div>
<div class="coupon-wrap">
<input
class="coupon-input"
id="coupon-input"
type="text"
placeholder="Enter coupon code"
value="${couponApplied ? 'SAVE10' : ''}"
${couponApplied ? 'disabled' : ''}
aria-label="Coupon code"
/>
<button class="coupon-btn" onclick="applyCoupon()">${couponApplied ? 'Applied ✓' : 'Apply'}</button>
</div>
<p class="coupon-msg ${couponApplied ? 'success' : ''}" id="coupon-msg">${couponApplied ? '10% discount applied!' : ''}</p>
<button class="btn-primary btn-full" onclick="showPage('checkout')">Proceed to Checkout</button>
<div style="margin-top:0.75rem;text-align:center">
<button class="btn-ghost" style="font-size:0.7rem" onclick="showPage('catalog')">← Continue Shopping</button>
</div>
`;
}
// ─────────────────────────────────────────────
// 12. COUPON
// ─────────────────────────────────────────────
function applyCoupon() {
const input = document.getElementById('coupon-input');
const msg = document.getElementById('coupon-msg');
if (!input) return;
const code = input.value.trim().toUpperCase();
if (code === 'SAVE10') {
couponApplied = true;
showToast('Coupon "SAVE10" applied — 10% off!');
renderCart();
} else {
msg.textContent = 'Invalid coupon code.';
msg.className = 'coupon-msg error';
input.classList.add('error');
setTimeout(() => { if (msg) { msg.textContent = ''; msg.className = 'coupon-msg'; } input.classList.remove('error'); }, 3000);
}
}
// ─────────────────────────────────────────────
// 13. WISHLIST
// ─────────────────────────────────────────────
function toggleWishlist(productId, fromDetail = false) {
const product = PRODUCTS.find(p => p.id === productId);
if (!product) return;
const idx = wishlist.indexOf(productId);
if (idx > -1) {
wishlist.splice(idx, 1);
showToast(`"${product.name}" removed from wishlist`);
} else {
wishlist.push(productId);
showToast(`"${product.name}" saved to wishlist`);
}
saveToStorage('maison_wishlist', wishlist);
updateBadges();
if (fromDetail) {
const btn = document.getElementById('detail-wishlist-btn');
if (btn) {
const isNow = wishlist.includes(productId);
btn.textContent = isNow ? '♥' : '♡';
btn.classList.toggle('active', isNow);
}
} else {
if (currentPage === 'catalog') renderProducts();
if (currentPage === 'wishlist') renderWishlist();
}
}
function renderWishlist() {
const grid = document.getElementById('wishlist-grid');
const emptyEl = document.getElementById('wishlist-empty');
if (wishlist.length === 0) {
grid.style.display = 'none';
emptyEl.classList.remove('hidden');
return;
}
grid.style.display = '';
emptyEl.classList.add('hidden');
grid.innerHTML = '';
wishlist.forEach((id, i) => {
const product = PRODUCTS.find(p => p.id === id);
if (!product) return;
const card = buildProductCard(product);
card.style.animationDelay = `${i * 0.04}s`;
grid.appendChild(card);
});
}
// ─────────────────────────────────────────────
// 14. CHECKOUT
// ─────────────────────────────────────────────
function renderCheckout() {
const orderItemsEl = document.getElementById('checkout-order-items');
const totalsEl = document.getElementById('checkout-totals');
const subtotal = getCartTotal();
const discount = couponApplied ? Math.round(subtotal * 0.1) : 0;
const shipping = subtotal > 400 ? 0 : 40;
const total = subtotal - discount + shipping;
// Order items
orderItemsEl.innerHTML = '';
cart.forEach(item => {
const p = PRODUCTS.find(prod => prod.id === item.productId);
if (!p) return;
const div = document.createElement('div');
div.className = 'checkout-order-item';
div.innerHTML = `
<div>
<p class="checkout-order-item-name">${p.name}</p>
<p class="checkout-order-item-qty">${p.emoji} × ${item.qty}</p>
</div>
<span class="checkout-order-item-price">₹${(p.price * item.qty).toLocaleString('en-IN')}</span>
`;
orderItemsEl.appendChild(div);
});
// Totals
totalsEl.innerHTML = `
<div class="summary-line" style="margin-top:1rem"><span>Subtotal</span><span>₹${subtotal.toLocaleString('en-IN')}</span></div>
<div class="summary-line"><span>Shipping</span><span>${shipping === 0 ? 'Free' : '₹'+shipping}</span></div>
${couponApplied ? `<div class="summary-line discount"><span>Discount (10%)</span><span>−₹${discount.toLocaleString('en-IN')}</span></div>` : ''}
<div class="summary-total"><span>Total</span><span>₹${total.toLocaleString('en-IN')}</span></div>
`;
}
// Form validation
function validateCheckout() {
const fields = [
{ id: 'fname', label: 'First name', pattern: /.+/ },
{ id: 'lname', label: 'Last name', pattern: /.+/ },
{ id: 'email', label: 'Email', pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
{ id: 'phone', label: 'Phone', pattern: /^[\d\s\+\-\(\)]{7,15}$/ },
{ id: 'address', label: 'Address', pattern: /.{5,}/ },
{ id: 'city', label: 'City', pattern: /.+/ },
{ id: 'pincode', label: 'PIN Code', pattern: /^\d{6}$/ },
];
let valid = true;
fields.forEach(f => {
const el = document.getElementById(f.id);
const errEl = document.getElementById(`${f.id}-error`);
if (!el || !errEl) return;
const val = el.value.trim();
if (!f.pattern.test(val)) {
el.classList.add('error');
errEl.textContent = `Please enter a valid ${f.label.toLowerCase()}.`;
valid = false;
} else {
el.classList.remove('error');
errEl.textContent = '';
}
});
return valid;
}
function handleCheckout(e) {
e.preventDefault();
if (!validateCheckout()) return;
// Simulate order placement
const orderNum = 'MSN-' + Date.now().toString().slice(-8).toUpperCase();
renderConfirmation(orderNum);
showPage('confirmation');
// Clear cart
cart = [];
couponApplied = false;
saveToStorage('maison_cart', cart);
updateBadges();
}
// ─────────────────────────────────────────────
// 15. ORDER CONFIRMATION
// ─────────────────────────────────────────────
function renderConfirmation(orderNum) {
document.getElementById('order-number').textContent = `Order ${orderNum}`;
const itemsEl = document.getElementById('confirmation-items');
itemsEl.innerHTML = '';
// Use the cart before clearing (snapshot)
const cartSnapshot = loadFromStorage('maison_cart') || cart;
cartSnapshot.forEach(item => {
const p = PRODUCTS.find(prod => prod.id === item.productId);
if (!p) return;
const div = document.createElement('div');
div.className = 'checkout-order-item';
div.innerHTML = `
<div>
<p class="checkout-order-item-name">${p.emoji} ${p.name}</p>
<p class="checkout-order-item-qty">Qty: ${item.qty}</p>
</div>
<span class="checkout-order-item-price">₹${(p.price * item.qty).toLocaleString('en-IN')}</span>
`;
itemsEl.appendChild(div);
});
}
function handleNewOrder() {
showPage('catalog');
}
// ─────────────────────────────────────────────
// 16. BADGES
// ─────────────────────────────────────────────
function updateBadges() {
// Cart badge
const cartCount = cart.reduce((s, i) => s + i.qty, 0);
const cartBadge = document.getElementById('cart-badge');
if (cartCount > 0) {
cartBadge.textContent = cartCount > 99 ? '99+' : cartCount;
cartBadge.style.display = 'flex';
} else {
cartBadge.style.display = 'none';
}
// Wishlist badge
const wishlistBadge = document.getElementById('wishlist-badge');
if (wishlist.length > 0) {
wishlistBadge.textContent = wishlist.length > 99 ? '99+' : wishlist.length;
wishlistBadge.style.display = 'flex';
} else {
wishlistBadge.style.display = 'none';
}
}
// ─────────────────────────────────────────────
// 17. PERSISTENT CART BANNER
// ─────────────────────────────────────────────
function checkPersistentCart() {
if (cart.length > 0) {
const count = cart.reduce((s, i) => s + i.qty, 0);
const el = document.getElementById('cart-banner');
document.getElementById('cart-banner-text').textContent =
`Welcome back! You have ${count} item${count > 1 ? 's' : ''} waiting in your cart.`;
el.classList.remove('hidden');
setTimeout(() => el.classList.add('hidden'), 6000);
}
}
function dismissBanner() {
document.getElementById('cart-banner').classList.add('hidden');
}
// ─────────────────────────────────────────────
// 18. INIT
// ─────────────────────────────────────────────
function init() {
initTheme();
updateBadges();
renderProducts();
checkPersistentCart();
}
// Run on DOM ready
document.addEventListener('DOMContentLoaded', init);