-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathscript.js
More file actions
2378 lines (2029 loc) · 70.4 KB
/
script.js
File metadata and controls
2378 lines (2029 loc) · 70.4 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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js';
import {
getAuth,
GoogleAuthProvider,
signInWithPopup,
signOut,
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
updateProfile
} from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js';
import { getAnalytics } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-analytics.js';
import {
getFirestore,
collection,
addDoc,
query,
where,
orderBy,
getDocs,
doc,
getDoc
} from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js';
const firebaseConfig = {
apiKey: "AIzaSyDY3U9hO51ZY6f2RLcdQoxPuJTjQn1lZB8",
authDomain: "quickbasket-dev.firebaseapp.com",
projectId: "quickbasket-dev",
storageBucket: "quickbasket-dev.firebasestorage.app",
messagingSenderId: "529752486191",
appId: "1:529752486191:web:c1b1a04990f159edfff1da",
measurementId: "G-B1HHD54R2D"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
const analytics = getAnalytics(app);
const db = getFirestore(app);
let currentUser = null;
window.firebaseAuth = auth;
window.googleProvider = provider;
window.signInWithPopup = signInWithPopup;
window.signOut = signOut;
window.onAuthStateChanged = onAuthStateChanged;
window.createUserWithEmailAndPassword = createUserWithEmailAndPassword;
window.signInWithEmailAndPassword = signInWithEmailAndPassword;
window.updateProfile = updateProfile;
// Order Storage Functions
async function saveOrderToFirebase(orderData) {
try {
if (!currentUser) {
throw new Error('User must be logged in to save orders');
}
const orderDoc = {
userId: currentUser.uid,
userEmail: currentUser.email,
userName: currentUser.displayName || 'Anonymous',
items: orderData.items,
totalAmount: orderData.totalAmount,
discount: orderData.discount || 0,
finalAmount: orderData.finalAmount,
paymentMethod: orderData.paymentMethod,
orderDate: new Date(),
status: 'completed',
orderId: generateOrderId()
};
const docRef = await addDoc(collection(db, 'orders'), orderDoc);
console.log('Order saved with ID:', docRef.id);
return docRef.id;
} catch (error) {
console.error('Error saving order to Firebase:', error);
throw error;
}
}
async function getUserOrders(userId, limit = 50) {
try {
const ordersRef = collection(db, 'orders');
const q = query(
ordersRef,
where('userId', '==', userId),
orderBy('orderDate', 'desc')
);
const querySnapshot = await getDocs(q);
const orders = [];
querySnapshot.forEach((doc) => {
orders.push({
id: doc.id,
...doc.data(),
orderDate: doc.data().orderDate.toDate() // Convert Firestore timestamp to Date
});
});
return orders.slice(0, limit);
} catch (error) {
console.error('Error fetching user orders:', error);
throw error;
}
}
function generateOrderId() {
const timestamp = Date.now();
const random = Math.random().toString(36).substr(2, 5);
return `QB${timestamp}${random}`.toUpperCase();
}
function formatOrderDate(date) {
return new Intl.DateTimeFormat('en-IN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(date);
}
function calculateOrderTotal(items) {
return items.reduce((total, item) => total + (item.price * item.quantity), 0);
}
onAuthStateChanged(auth, (user) => {
currentUser = user;
if (user) {
updateUIForSignedInUser(user);
renderRecentlyViewed();
} else {
updateUIForSignedOutUser();
renderRecentlyViewed();
}
});
function updateUIForSignedInUser(user) {
const loginView = document.getElementById('loginView');
const profileView = document.getElementById('userProfileView');
const accountText = document.getElementById('accountText');
const userAvatar = document.getElementById('userAvatar');
if (loginView) loginView.style.display = 'none';
if (profileView) profileView.style.display = 'block';
if (userAvatar) {
if (user.photoURL) {
userAvatar.src = user.photoURL;
userAvatar.onerror = function() {
this.src = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.displayName || 'User') + '&background=0D8ABC&color=fff&size=100';
};
} else {
userAvatar.src = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.displayName || user.email) + '&background=0D8ABC&color=fff&size=100';
}
}
document.getElementById('userName').textContent = user.displayName || 'User';
document.getElementById('userEmail').textContent = user.email;
if (accountText) {
accountText.textContent = user.displayName?.split(' ')[0] || 'Account';
}
}
function updateUIForSignedOutUser() {
const loginView = document.getElementById('loginView');
const profileView = document.getElementById('userProfileView');
const accountText = document.getElementById('accountText');
if (loginView) loginView.style.display = 'block';
if (profileView) profileView.style.display = 'none';
if (accountText) {
accountText.textContent = 'Account';
}
}
// Google Sign-In button click handler
document.getElementById('googleSignInBtn').addEventListener('click', async () => {
try {
const result = await signInWithPopup(auth, provider);
const user = result.user;
if (window.showSuccessToast) {
window.showSuccessToast(`Welcome, ${user.displayName}!`);
}
setTimeout(() => {
document.getElementById('userModal').style.display = 'none';
}, 1000);
} catch (error) {
console.error('Error signing in with Google:', error);
if (window.showErrorToast) {
window.showErrorToast('Failed to sign in. Please try again.');
}
}
});
// Sign out button
document.getElementById('signOutBtn').addEventListener('click', async () => {
try {
await signOut(auth);
showSuccessToast('Signed out successfully');
document.getElementById('userModal').style.display = 'none';
} catch (error) {
console.error('Error signing out:', error);
showErrorToast('Failed to sign out. Please try again.');
}
});
function validatePassword(password) {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
const errors = [];
if (password.length < minLength) {
errors.push(`Password must be at least ${minLength} characters long`);
}
if (!hasUpperCase) {
errors.push('Password must contain at least one uppercase letter');
}
if (!hasLowerCase) {
errors.push('Password must contain at least one lowercase letter');
}
if (!hasNumber) {
errors.push('Password must contain at least one number');
}
if (!hasSpecialChar) {
errors.push('Password must contain at least one special character (!@#$%^&*(),.?":{}|<>)');
}
return {
isValid: errors.length === 0,
errors: errors
};
}
function displayPasswordStrength(password) {
const validation = validatePassword(password);
const passwordInput = document.getElementById('signupPassword');
let existingHint = document.querySelector('.password-strength-hint');
if (!existingHint) {
existingHint = document.createElement('div');
existingHint.className = 'password-strength-hint';
passwordInput.parentNode.appendChild(existingHint);
}
if (!password) {
existingHint.innerHTML = '';
existingHint.style.display = 'none';
return;
}
existingHint.style.display = 'block';
if (validation.isValid) {
existingHint.innerHTML = '<span style="color: var(--success);"><i class="fas fa-check-circle"></i> Strong password!</span>';
} else {
existingHint.innerHTML = '<ul style="margin: 5px 0; padding-left: 20px; font-size: 0.85rem; color: var(--danger);">' +
validation.errors.map(err => `<li>${err}</li>`).join('') +
'</ul>';
}
}
// Cart and Wishlist functionality
let cart = [];
let wishlist = []; // Initializing the wishlist array
let cartCount = 0;
let wishlistCount = 0;
let appliedCoupon = null;
// Predefined coupons
const coupons = {
NEW50: {
code: "NEW50",
description: "Flat ₹50 off on all orders",
type: "flat",
value: 50,
minOrder: 0,
},
SALE25: {
code: "SALE25",
description: "25% off on your order",
type: "percentage",
value: 25,
minOrder: 0,
},
FESTIVEDAY: {
code: "FESTIVEDAY",
description: "₹100 off on orders above ₹299",
type: "flat",
value: 100,
minOrder: 299,
},
MEGA40: {
code: "MEGA40",
description: "40% off on orders above ₹500",
type: "percentage",
value: 40,
minOrder: 500,
},
};
let productsData = null;
let currentCategory = "all"; // active category filter from URL or clicks
// Initialize cart from localStorage on startup
function initializeCart() {
const savedCart = window.cartStorage ? window.cartStorage.loadCart() : null;
if (savedCart && Array.isArray(savedCart) && savedCart.length > 0) {
cart = savedCart;
cartCount = cart.reduce((total, item) => total + item.quantity, 0);
const cartCountElement = document.querySelector(".cart-item-count");
if (cartCountElement) {
cartCountElement.textContent = cartCount;
}
console.log(`Loaded ${cart.length} items from localStorage`);
} else {
cart = [];
cartCount = 0;
}
}
// Initialize wishlist from localStorage on startup
function initializeWishlist() {
try {
const savedWishlist = localStorage.getItem("quickbasket_wishlist");
if (savedWishlist) {
wishlist = JSON.parse(savedWishlist);
wishlistCount = wishlist.length;
const wishlistCountElement = document.querySelector(".wishlist-count");
if (wishlistCountElement) {
wishlistCountElement.textContent = wishlistCount;
}
console.log(`Loaded ${wishlist.length} items from wishlist`);
}
} catch (error) {
console.error("Error loading wishlist from localStorage:", error);
wishlist = [];
wishlistCount = 0;
}
}
// Save wishlist to localStorage
function saveWishlist() {
try {
localStorage.setItem("quickbasket_wishlist", JSON.stringify(wishlist));
} catch (error) {
console.error("Error saving wishlist to localStorage:", error);
}
}
// Load products from JSON
async function loadProducts() {
try {
const response = await fetch("./products.json");
productsData = await response.json();
// Combine all products for easy lookup by ID
productsData.allProducts = [
...(productsData.popularProducts || []),
...(productsData.deals || []),
];
renderProducts();
renderRecentlyViewed(); // Initialize recently viewed section
updateWishlistDisplay(); // Call to initialize the count
} catch (error) {
console.error("Error loading products:", error);
showErrorToast("Failed to load products. Please refresh the page.");
}
}
// Sort products based on selected criteria
function sortProducts(products, sortType) {
if (!products || !Array.isArray(products)) return products;
const sortedProducts = [...products]; // Create a copy to avoid mutating original
switch (sortType) {
case 'rating-high':
return sortedProducts.sort((a, b) => (b.rating || 0) - (a.rating || 0));
case 'rating-low':
return sortedProducts.sort((a, b) => (a.rating || 0) - (b.rating || 0));
case 'price-high':
return sortedProducts.sort((a, b) => (b.price || 0) - (a.price || 0));
case 'price-low':
return sortedProducts.sort((a, b) => (a.price || 0) - (b.price || 0));
case 'name-asc':
return sortedProducts.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
case 'name-desc':
return sortedProducts.sort((a, b) => (b.name || '').localeCompare(a.name || ''));
default:
return sortedProducts;
}
}
// Render products dynamically
function renderProducts() {
if (!productsData) return;
const category = (currentCategory || "all").toLowerCase();
const sortType = document.getElementById('sortOption')?.value || 'default';
// Filter helpers
const byCategory = (p) =>
category === "all" || (p.category || "").toLowerCase() === category;
let popular = (productsData.popularProducts || []).filter(byCategory);
let deals = (productsData.deals || []).filter(byCategory);
// Apply sorting
popular = sortProducts(popular, sortType);
deals = sortProducts(deals, sortType);
renderProductSection("popularProducts", popular);
renderProductSection("dealsProducts", deals);
// Update headings to reflect active category
try {
const popularTitle = document.querySelector("h2.section-title#products");
const dealsTitle = Array.from(
document.querySelectorAll("h2.section-title")
).find((h) => h.textContent.trim().startsWith("Today's Best Deals"));
const prettyCat =
category === "all"
? ""
: ` – ${category
.replace("-", " ")
.replace(/\b\w/g, (c) => c.toUpperCase())}`;
if (popularTitle) popularTitle.textContent = `Popular Products${prettyCat}`;
if (dealsTitle) dealsTitle.textContent = `Today's Best Deals${prettyCat}`;
} catch (_) {
// non-fatal UI update
}
}
// Render a specific product section
function renderProductSection(containerId, products) {
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = "";
products.forEach((product) => {
const productCard = createProductCard(product);
container.appendChild(productCard);
});
}
// Category filter initialization and URL helpers
function getCategoryFromURL() {
try {
const params = new URLSearchParams(window.location.search);
const cat = (params.get("category") || "all").toLowerCase();
return cat;
} catch (_) {
return "all";
}
}
function setCategoryInURL(cat) {
const params = new URLSearchParams(window.location.search);
if (!cat || cat === "all") {
params.delete("category");
} else {
params.set("category", cat);
}
const newUrl = `${window.location.pathname}?${params.toString()}`.replace(
/\?$/,
""
);
window.history.pushState({ category: cat || "all" }, "", newUrl);
}
function applyCategoryFromURL() {
currentCategory = getCategoryFromURL();
highlightActiveCategory(currentCategory);
highlightActiveNav(currentCategory);
renderProducts();
}
function highlightActiveCategory(cat) {
document.querySelectorAll(".category-item").forEach((el) => {
const c = (el.getAttribute("data-category") || "").toLowerCase();
if ((cat === "all" && c === "all") || c === cat) {
el.classList.add("active");
} else {
el.classList.remove("active");
}
});
}
function initializeCategoryFiltering() {
document.querySelectorAll(".category-item").forEach((el) => {
el.addEventListener("click", () => {
const cat = (el.getAttribute("data-category") || "all").toLowerCase();
currentCategory = cat;
setCategoryInURL(cat);
highlightActiveCategory(cat);
highlightActiveNav(cat);
// Optional: clear search when category changes
const searchInput = document.querySelector(".search-bar input");
if (searchInput) searchInput.value = "";
renderProducts();
scrollToProducts();
});
});
// Apply initial category from URL
applyCategoryFromURL();
// Handle back/forward navigation
window.addEventListener("popstate", () => {
applyCategoryFromURL();
});
}
function highlightActiveNav(cat) {
document.querySelectorAll(".nav-links a[data-category]").forEach((a) => {
const c = (a.getAttribute("data-category") || "").toLowerCase();
if ((cat === "all" && c === "all") || c === cat) {
a.classList.add("active");
} else {
a.classList.remove("active");
}
});
}
function initializeNavFiltering() {
document.querySelectorAll(".nav-links a[data-category]").forEach((a) => {
a.addEventListener("click", (e) => {
e.preventDefault();
const cat = (a.getAttribute("data-category") || "all").toLowerCase();
currentCategory = cat;
setCategoryInURL(cat);
highlightActiveCategory(cat);
highlightActiveNav(cat);
const searchInput = document.querySelector(".search-bar input");
if (searchInput) searchInput.value = "";
renderProducts();
scrollToProducts();
});
});
}
function scrollToProducts() {
const anchor = document.getElementById("products");
if (anchor && typeof anchor.scrollIntoView === "function") {
anchor.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
/**
* Adds a product to the recently viewed list for the current user.
* @param {object} product
*/
function addToRecentlyViewed(product) {
if (!currentUser) return;
const key = `recentlyViewed_${currentUser.uid}`;
let recentlyViewed = JSON.parse(localStorage.getItem(key) || "[]");
recentlyViewed = recentlyViewed.filter((p) => p.id !== product.id);
recentlyViewed.unshift(product);
if (recentlyViewed.length > 4) {
recentlyViewed = recentlyViewed.slice(0, 4);
}
localStorage.setItem(key, JSON.stringify(recentlyViewed));
}
// Render recently viewed products
function renderRecentlyViewed() {
const section = document.getElementById("recently-viewed");
const container = document.getElementById("recentlyViewedProducts");
if (!section || !container) return;
if (!currentUser) {
section.style.display = "none";
return;
}
const key = `recentlyViewed_${currentUser.uid}`;
const recentlyViewed = JSON.parse(localStorage.getItem(key) || "[]");
if (recentlyViewed.length === 0) {
section.style.display = "none";
return;
}
section.style.display = "block";
container.innerHTML = "";
recentlyViewed.slice(0, 4).forEach((product) => {
const productCard = createProductCard(product);
container.appendChild(productCard);
});
}
// Generate star rating display
function generateStars(rating) {
if (!rating || rating < 1 || rating > 5) return '';
let stars = '';
const fullStars = Math.floor(rating);
const hasHalfStar = rating % 1 >= 0.5;
for (let i = 1; i <= 5; i++) {
if (i <= fullStars) {
stars += '<i class="fas fa-star"></i>';
} else if (i === fullStars + 1 && hasHalfStar) {
stars += '<i class="fas fa-star-half-alt"></i>';
} else {
stars += '<i class="far fa-star"></i>';
}
}
return stars;
}
// Create product card element
function createProductCard(product) {
const productCard = document.createElement("div");
productCard.className = "product-card";
// Check if the product is in the wishlist to set the correct icon
const isInWishlist = wishlist.some((item) => item.id === product.id);
const heartIconClass = isInWishlist ? "fas fa-heart active" : "far fa-heart";
productCard.innerHTML = `
<img src="${product.image}" alt="${product.name}" class="product-image skeleton" onload="this.classList.remove('skeleton')" onerror="this.classList.remove('skeleton')">
<div class="product-info">
<h3 class="product-title">${product.name}</h3>
<div class="product-price">₹${product.price} <span>(₹${product.discount} off)</span></div>
<div class="product-rating">
<div class="stars">${generateStars(product.rating)}</div>
<span class="rating-value">${product.rating || 'N/A'}</span>
</div>
<p>${product.description}</p>
<div class="product-actions">
<button class="add-to-cart" onclick="addToCart('${product.name}', ${product.price}, '${product.image}', ${product.id})">
<i class="fas fa-plus"></i> Add to Cart
</button>
<button class="wishlist" onclick="toggleWishlist(${product.id}, event)">
<i class="${heartIconClass}"></i>
</button>
</div>
</div>
`;
productCard.addEventListener("click", (e) => {
if (e.target.closest(".add-to-cart") || e.target.closest(".wishlist")) return;
openProductDetail(product);
});
return productCard;
}
// Search functionality
function initializeSearch() {
const searchInput = document.querySelector(".search-bar input");
const searchButton = document.querySelector(".search-bar button");
if (!searchInput) return;
function performSearch() {
const searchTerm = searchInput.value.toLowerCase().trim();
if (!productsData) return;
// When search term is empty, render by current category
if (searchTerm === "") {
renderProducts();
return;
}
const category = (currentCategory || "all").toLowerCase();
const inCategory = (p) =>
category === "all" || (p.category || "").toLowerCase() === category;
const matches = (p) =>
p.name.toLowerCase().includes(searchTerm) ||
p.description.toLowerCase().includes(searchTerm) ||
(p.category || "").toLowerCase().includes(searchTerm);
const filteredPopular = (productsData.popularProducts || []).filter(
(p) => inCategory(p) && matches(p)
);
const filteredDeals = (productsData.deals || []).filter(
(p) => inCategory(p) && matches(p)
);
renderProductSection("popularProducts", filteredPopular);
renderProductSection("dealsProducts", filteredDeals);
const totalResults = filteredPopular.length + filteredDeals.length;
if (totalResults === 0) {
const popularContainer = document.getElementById("popularProducts");
const dealsContainer = document.getElementById("dealsProducts");
if (popularContainer) {
popularContainer.innerHTML =
'<p style="text-align: center; padding: 20px; color: #999;">No products found</p>';
}
if (dealsContainer) {
dealsContainer.innerHTML =
'<p style="text-align: center; padding: 20px; color: #999;">No products found</p>';
}
}
}
searchInput.addEventListener("input", performSearch);
searchButton.addEventListener("click", performSearch);
searchInput.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault();
performSearch();
}
});
}
// Initialize sorting functionality
function initializeSorting() {
const sortDropdown = document.getElementById('sortOption');
if (sortDropdown) {
sortDropdown.addEventListener('change', function() {
renderProducts();
});
}
}
// Initialize products and cart when page loads
document.addEventListener("DOMContentLoaded", function () {
loadProducts();
initializeCart();
initializeWishlist();
initializeSearch();
initializePincodeChecker();
loadSavedPincode();
initializeCategoryFiltering();
initializeNavFiltering();
initializeSorting();
initializeProductDetailModal();
});
// --- Pincode Delivery Functions ---
/**
* Initialize pincode checker functionality
*/
function initializePincodeChecker() {
const banner = document.getElementById("pincodeBanner");
const changePincodeBtn = document.getElementById("changePincodeBtn");
const pincodeInput = document.getElementById("pincodeInput");
const checkBtn = document.getElementById("checkDeliveryBtn");
// Banner click to open modal
if (banner) {
banner.addEventListener("click", openPincodeModal);
}
// Change pincode button
if (changePincodeBtn) {
changePincodeBtn.addEventListener("click", function (e) {
e.stopPropagation();
openPincodeModal();
});
}
if (!pincodeInput || !checkBtn) return;
// Add click event listener to check button
checkBtn.addEventListener("click", checkDelivery);
// Add input validation and formatting
pincodeInput.addEventListener("input", function (e) {
// Allow only numbers
let value = e.target.value.replace(/\D/g, "");
// Limit to 6 digits
if (value.length > 6) {
value = value.substring(0, 6);
}
e.target.value = value;
// Enable/disable check button
checkBtn.disabled = value.length !== 6;
// Clear previous status when input changes
if (value.length < 6) {
hideDeliveryStatus();
}
});
// Add enter key support
pincodeInput.addEventListener("keypress", function (e) {
if (e.key === "Enter" && pincodeInput.value.length === 6) {
checkDelivery();
}
});
// Add paste event handling
pincodeInput.addEventListener("paste", function (e) {
e.preventDefault();
const paste = (e.clipboardData || window.clipboardData).getData("text");
const numbers = paste.replace(/\D/g, "").substring(0, 6);
pincodeInput.value = numbers;
checkBtn.disabled = numbers.length !== 6;
// Trigger input event to update button state
const inputEvent = new Event("input", { bubbles: true });
pincodeInput.dispatchEvent(inputEvent);
});
}
/**
* Open pincode modal
*/
function openPincodeModal() {
const modal = document.getElementById("pincodeModal");
const pincodeInput = document.getElementById("pincodeInput");
if (modal) {
modal.classList.add("show");
document.body.style.overflow = "hidden";
// Focus on input after animation
setTimeout(() => {
if (pincodeInput) {
pincodeInput.focus();
}
}, 100);
}
}
/**
* Close pincode modal
*/
function closePincodeModal() {
const modal = document.getElementById("pincodeModal");
const pincodeInput = document.getElementById("pincodeInput");
if (modal) {
modal.classList.remove("show");
document.body.style.overflow = "";
// Clear input and status
if (pincodeInput) {
pincodeInput.value = "";
}
hideDeliveryStatus();
}
}
/**
* Validate Indian pincode format
* @param {string} pincode - 6 digit pincode
* @returns {boolean} - true if valid format
*/
function validatePincode(pincode) {
if (!pincode || typeof pincode !== "string") {
return false;
}
// Remove any spaces or special characters
const cleanPincode = pincode.replace(/\D/g, "");
// Check if it's exactly 6 digits
if (cleanPincode.length !== 6) {
return false;
}
// Indian pincodes start from 1 and go up to 8 (first digit)
const firstDigit = parseInt(cleanPincode.charAt(0));
if (firstDigit < 1 || firstDigit > 8) {
return false;
}
return true;
}
/**
* Check delivery availability for given pincode
*/
async function checkDelivery() {
const pincodeInput = document.getElementById("pincodeInput");
const checkBtn = document.getElementById("checkDeliveryBtn");
if (!pincodeInput) {
console.error("Pincode input element not found");
return;
}
const pincode = pincodeInput.value.trim();
if (!validatePincode(pincode)) {
showDeliveryStatus("error", "Please enter a valid 6-digit Indian pincode");
return;
}
if (checkBtn) {
checkBtn.disabled = true;
checkBtn.innerHTML = '<span class="delivery-spinner"></span>Checking...';
}
showDeliveryStatus("checking", "Checking delivery availability...");
try {
const deliveryInfo = await checkPincodeDelivery(pincode);
if (deliveryInfo.available) {
showDeliveryStatus(
"available",
`🎉 Great! We deliver to ${deliveryInfo.city}, ${deliveryInfo.state}.\nExpected delivery: ${deliveryInfo.deliveryTime}`
);
setTimeout(() => {
savePincode(pincode, deliveryInfo);
closePincodeModal();
}, 2000);
} else {
showDeliveryStatus(
"not-available",
`😔 Sorry, we don't deliver to this location.\n${
deliveryInfo.reason || ""
}`
);
}
} catch (error) {
console.error("Error checking delivery:", error);
showDeliveryStatus("error", "Something went wrong. Please try again.");
} finally {
if (checkBtn) {
checkBtn.disabled = false;
checkBtn.innerHTML = '<i class="fas fa-search"></i>Check';
}
}
}
/**
* Check if delivery is available for a specific pincode using Postal Pincode API
* @param {string} pincode - 6 digit pincode
* @returns {Promise<object>} - delivery information
*/
async function checkPincodeDelivery(pincode) {
try {
const res = await fetch(`https://api.postalpincode.in/pincode/${pincode}`);
const data = await res.json();
if (!data || data[0].Status !== "Success" || !data[0].PostOffice) {
return {
city: null,
state: null,
available: false,
reason: "Invalid or unsupported pincode",
};
}
// Take the top result (first PostOffice)
const office = data[0].PostOffice[0];
return {
city: office.District || office.Name,
state: office.State,
available: true, // all pincodes are serviceable
deliveryTime: "45-60 minutes",
};
} catch (err) {
console.error("Error fetching pincode:", err);
return {
city: null,
state: null,
available: false,
reason: "Service temporarily unavailable",
};
}
}
/**
* Show delivery status message
* @param {string} type - Status type (available, not-available, checking, error)
* @param {string} message - Status message
*/
function showDeliveryStatus(type, message) {
const statusDiv = document.getElementById("deliveryStatus");
if (!statusDiv) return;
statusDiv.className = `delivery-status ${type}`;
if (type === "checking") {
statusDiv.innerHTML = `<span class="delivery-spinner"></span>${message}`;
} else {
statusDiv.textContent = message;
}
statusDiv.style.display = "block";
}
/**
* Hide delivery status
*/
function hideDeliveryStatus() {
const statusDiv = document.getElementById("deliveryStatus");
if (statusDiv) {