-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3486 lines (3213 loc) · 130 KB
/
script.js
File metadata and controls
3486 lines (3213 loc) · 130 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
/* =============================================================
QUINTESSENCE — script.js v4
New: Hero Carousel · Shopping Cart · Product Search ·
Stock Management · Shareable Links · CSV Export
============================================================= */
const SUPABASE_URL = "https://yqvvqzstbukcqoqbtfrd.supabase.co";
const SUPABASE_ANON =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlxdnZxenN0YnVrY3FvcWJ0ZnJkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzE5Mjc2MzgsImV4cCI6MjA4NzUwMzYzOH0.JjZfo4FHHV-YOQh0BTDlYLX0beXZUWzg77j402YB6SM";
/*
---------------------------------------------------------------
SUPABASE SQL SETUP (run once in Supabase SQL editor):
---------------------------------------------------------------
-- Add is_in_stock column to products (run if upgrading):
ALTER TABLE products ADD COLUMN IF NOT EXISTS is_in_stock BOOLEAN DEFAULT true;
CREATE TABLE IF NOT EXISTS products (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
price NUMERIC NOT NULL,
description TEXT,
image_url TEXT,
video_url TEXT,
is_best_seller BOOLEAN DEFAULT false,
is_in_stock BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT timezone('utc', now())
);
CREATE TABLE IF NOT EXISTS videos (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
title TEXT NOT NULL,
video_url TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT timezone('utc', now())
);
CREATE TABLE IF NOT EXISTS subscribers (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT timezone('utc', now())
);
CREATE TABLE IF NOT EXISTS reviews (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
name TEXT NOT NULL,
city TEXT,
review TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT timezone('utc', now())
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
ALTER TABLE videos ENABLE ROW LEVEL SECURITY;
ALTER TABLE subscribers ENABLE ROW LEVEL SECURITY;
ALTER TABLE reviews ENABLE ROW LEVEL SECURITY;
ALTER TABLE settings ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Public read products" ON products FOR SELECT USING (true);
CREATE POLICY "Public read videos" ON videos FOR SELECT USING (true);
CREATE POLICY "Public insert subscribe" ON subscribers FOR INSERT WITH CHECK (true);
CREATE POLICY "Admin write products" ON products FOR ALL USING (auth.role() = 'authenticated');
CREATE POLICY "Admin write videos" ON videos FOR ALL USING (auth.role() = 'authenticated');
CREATE POLICY "Admin read subscribers" ON subscribers FOR SELECT USING (auth.role() = 'authenticated');
CREATE POLICY "Public insert reviews" ON reviews FOR INSERT WITH CHECK (true);
CREATE POLICY "Public read reviews" ON reviews FOR SELECT USING (true);
CREATE POLICY "Admin delete reviews" ON reviews FOR DELETE USING (auth.role() = 'authenticated');
CREATE POLICY "Public read settings" ON settings FOR SELECT USING (true);
CREATE POLICY "Admin write settings" ON settings FOR ALL USING (auth.role() = 'authenticated');
Storage buckets to create:
"products" (Public ON) and "videos" (Public ON)
Admin user:
Authentication → Users → Add User
---------------------------------------------------------------
*/
document.addEventListener("DOMContentLoaded", () => {
// Always start at top of page on load/refresh
if ("scrollRestoration" in history) history.scrollRestoration = "manual";
window.scrollTo(0, 0);
// ── Supabase init ──────────────────────────────────────────
let db = null;
try {
const { createClient } = supabase;
db = createClient(SUPABASE_URL, SUPABASE_ANON);
} catch (e) {
console.warn("Supabase not initialised:", e.message);
}
// ── State ──────────────────────────────────────────────────
let allProducts = []; // all products from DB
let cart = []; // { product, qty }
let currentProduct = null; // product open in modal
let whatsappNumber = "2348132386987";
// ═══════════════════════════════════════════════════════════
// TOAST
// ═══════════════════════════════════════════════════════════
function showToast(msg, type = "success") {
const t = document.getElementById("toast");
t.textContent = msg;
t.className = `toast show ${type}`;
clearTimeout(t._timer);
t._timer = setTimeout(() => t.classList.remove("show"), 3500);
}
// ═══════════════════════════════════════════════════════════
// NAVBAR
// ═══════════════════════════════════════════════════════════
window.addEventListener(
"scroll",
() => {
document
.getElementById("navbar")
.classList.toggle("scrolled", window.scrollY > 60);
},
{ passive: true },
);
const hamburger = document.getElementById("hamburger");
const mobileMenu = document.getElementById("mobileMenu");
hamburger.addEventListener("click", () =>
mobileMenu.classList.toggle("open"),
);
mobileMenu
.querySelectorAll("a")
.forEach((l) =>
l.addEventListener("click", () => mobileMenu.classList.remove("open")),
);
// ═══════════════════════════════════════════════════════════
// HERO CAROUSEL
// ═══════════════════════════════════════════════════════════
const slides = document.querySelectorAll(".hero-slide");
const dots = document.querySelectorAll(".carousel-dot");
let currentSlide = 0;
let carouselTimer = null;
// Lazy-load hero slide background images
// Each .hero-slide should use:
// data-bg="asset-base-name" (no extension) and optional data-gradient="linear-gradient(...)"
const HERO_CAROUSEL_INTERVAL_MS = 9500;
function pickExistingAsset(baseName) {
return new Promise((resolve) => {
if (!baseName) return resolve(null);
const exts = ["jpg", "png", "webp"];
let i = 0;
const tryNext = () => {
if (i >= exts.length) return resolve(null);
const relPath = `assets/${baseName}.${exts[i++]}`;
const img = new Image();
img.onload = () => resolve(relPath);
img.onerror = () => tryNext();
// Trigger load (works on file:// and http(s)://)
img.src = relPath;
};
tryNext();
});
}
// Compute a simple average color from the slide background image so the card/overlay can blend.
const _slideThemeCache = new Map();
async function computeSlideTheme(assetPath) {
if (!assetPath) return null;
if (_slideThemeCache.has(assetPath)) return _slideThemeCache.get(assetPath);
const themePromise = new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
try {
const c = document.createElement("canvas");
const ctx = c.getContext("2d", { willReadFrequently: true });
const W = 32,
H = 32;
c.width = W;
c.height = H;
ctx.drawImage(img, 0, 0, W, H);
const data = ctx.getImageData(0, 0, W, H).data;
let r = 0,
g = 0,
b = 0,
n = 0;
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3];
if (a < 40) continue; // ignore near-transparent pixels
r += data[i];
g += data[i + 1];
b += data[i + 2];
n++;
}
if (!n) return resolve(null);
r = Math.round(r / n);
g = Math.round(g / n);
b = Math.round(b / n);
// Perceived luminance to decide text contrast
const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
const isDark = luminance < 0.55;
resolve({ r, g, b, isDark });
} catch (e) {
resolve(null);
}
};
img.onerror = () => resolve(null);
img.src = assetPath;
});
_slideThemeCache.set(assetPath, themePromise);
return themePromise;
}
function applySlideTheme(slide, theme) {
if (!slide || !theme) return;
const overlay = slide.querySelector(".hero-overlay");
const card = slide.querySelector(".overlay");
if (!overlay || !card) return;
// Blend the backdrop and the message card using the image's average color.
overlay.style.background = `rgba(${theme.r}, ${theme.g}, ${theme.b}, 0.45)`;
// Use a tinted glass card for uniform look across slides.
card.style.background = `rgba(${theme.r}, ${theme.g}, ${theme.b}, 0.72)`;
card.style.backdropFilter = "blur(10px)";
card.style.webkitBackdropFilter = "blur(10px)";
// Ensure readable text
if (theme.isDark) {
card.classList.add("overlay-dark");
} else {
card.classList.remove("overlay-dark");
}
}
async function ensureSlideBackground(slide) {
if (!slide || slide.dataset.bgLoaded === "1") return;
const base = slide.dataset.bg;
if (!base) return;
const gradient = slide.dataset.gradient;
const asset = await pickExistingAsset(base);
if (!asset) return;
slide.style.backgroundImage = gradient
? `${gradient}, url('${asset}')`
: `url('${asset}')`;
// Make the card/overlay blend with the slide image for a uniform look
const theme = await computeSlideTheme(asset);
applySlideTheme(slide, theme);
slide.dataset.bgLoaded = "1";
}
function preloadCarouselImages(index) {
if (!slides.length) return;
void ensureSlideBackground(slides[index]);
void ensureSlideBackground(slides[(index + 1) % slides.length]);
}
// Load the first slide immediately, then prime the next one
preloadCarouselImages(0);
function goToSlide(n) {
const prevIdx = currentSlide;
const nextIdx = (n + slides.length) % slides.length;
if (prevIdx === nextIdx) return;
// Mark leaving slide — CSS keeps it visible briefly at low opacity
slides[prevIdx].classList.remove("active");
slides[prevIdx].classList.add("leaving");
dots[prevIdx] && dots[prevIdx].classList.remove("active");
// Bring in next slide
currentSlide = nextIdx;
slides[currentSlide].classList.add("active");
dots[currentSlide] && dots[currentSlide].classList.add("active");
preloadCarouselImages(currentSlide);
// Clean up leaving class after transition finishes
setTimeout(() => slides[prevIdx].classList.remove("leaving"), 1400);
}
function startCarousel() {
carouselTimer = setInterval(
() => goToSlide(currentSlide + 1),
HERO_CAROUSEL_INTERVAL_MS,
);
}
function resetCarousel() {
clearInterval(carouselTimer);
startCarousel();
}
const heroPrev = document.getElementById("carouselPrev");
const heroNext = document.getElementById("carouselNext");
heroPrev.addEventListener("click", () => {
goToSlide(currentSlide - 1);
resetCarousel();
showHeroArrows();
});
heroNext.addEventListener("click", () => {
goToSlide(currentSlide + 1);
resetCarousel();
showHeroArrows();
});
// Smart arrow visibility: fade out after idle, reappear on hover/touch
let heroArrowTimer = null;
function showHeroArrows() {
heroPrev.style.opacity = "1";
heroPrev.style.visibility = "visible";
heroNext.style.opacity = "1";
heroNext.style.visibility = "visible";
clearTimeout(heroArrowTimer);
heroArrowTimer = setTimeout(fadeHeroArrows, 2800);
}
function fadeHeroArrows() {
heroPrev.style.opacity = "0";
heroPrev.style.visibility = "hidden";
heroNext.style.opacity = "0";
heroNext.style.visibility = "hidden";
}
// Start hidden, appear on hero hover
fadeHeroArrows();
const heroSection = document.querySelector(".hero");
if (heroSection) {
heroSection.addEventListener("mouseenter", showHeroArrows);
heroSection.addEventListener("mouseleave", () => {
clearTimeout(heroArrowTimer);
heroArrowTimer = setTimeout(fadeHeroArrows, 800);
});
heroSection.addEventListener("touchstart", showHeroArrows, {
passive: true,
});
}
dots.forEach((dot) =>
dot.addEventListener("click", () => {
goToSlide(+dot.dataset.index);
resetCarousel();
}),
);
// Swipe support for hero carousel
let touchStartX = 0;
document.getElementById("heroCarousel").addEventListener(
"touchstart",
(e) => {
touchStartX = e.touches[0].clientX;
},
{ passive: true },
);
document.getElementById("heroCarousel").addEventListener(
"touchend",
(e) => {
const dx = e.changedTouches[0].clientX - touchStartX;
if (Math.abs(dx) > 50) {
goToSlide(currentSlide + (dx < 0 ? 1 : -1));
resetCarousel();
}
},
{ passive: true },
);
if (slides.length > 1) startCarousel();
// ═══════════════════════════════════════════════════════════
// CAROUSEL ARROW HELPER — hide/show based on scroll position
// ═══════════════════════════════════════════════════════════
function syncArrows(carousel, prevBtn, nextBtn) {
const THRESHOLD = 8; // px tolerance for floating point
const atStart = carousel.scrollLeft <= THRESHOLD;
const atEnd =
carousel.scrollLeft + carousel.clientWidth >=
carousel.scrollWidth - THRESHOLD;
prevBtn.style.visibility = atStart ? "hidden" : "visible";
prevBtn.style.opacity = atStart ? "0" : "1";
nextBtn.style.visibility = atEnd ? "hidden" : "visible";
nextBtn.style.opacity = atEnd ? "0" : "1";
}
function initCarousel(carouselId, prevId, nextId, step) {
const carousel = document.getElementById(carouselId);
const prevBtn = document.getElementById(prevId);
const nextBtn = document.getElementById(nextId);
if (!carousel || !prevBtn || !nextBtn) return;
prevBtn.addEventListener("click", () => {
carousel.scrollBy({ left: -step, behavior: "smooth" });
});
nextBtn.addEventListener("click", () => {
carousel.scrollBy({ left: step, behavior: "smooth" });
});
// Update arrows on scroll (throttled with requestAnimationFrame)
let ticking = false;
carousel.addEventListener(
"scroll",
() => {
if (!ticking) {
requestAnimationFrame(() => {
syncArrows(carousel, prevBtn, nextBtn);
ticking = false;
});
ticking = true;
}
},
{ passive: true },
);
// Initial state — prev hidden at start, check if next needed
syncArrows(carousel, prevBtn, nextBtn);
// Re-sync after images load (content may shift)
window.addEventListener("load", () =>
syncArrows(carousel, prevBtn, nextBtn),
);
return { carousel, prevBtn, nextBtn };
}
// Best Sellers carousel
const bsCarousel = document.getElementById("bestSellersCarousel");
initCarousel("bestSellersCarousel", "bsPrev", "bsNext", 240);
// Products carousel
const prodCarousel = document.getElementById("productGrid");
initCarousel("productGrid", "prodPrev", "prodNext", 220);
// Testimonials carousel
initCarousel("testimonialGrid", "tPrev", "tNext", 300);
// ── Swipe dots — mobile pagination indicators ───────────────
function initSwipeDots(carouselId, dotsId) {
const carousel = document.getElementById(carouselId);
const wrap = document.getElementById(dotsId);
if (!carousel || !wrap) return;
function cardWidth() {
const first = carousel.querySelector(
"[class*='card'], [class*='seller-card'], .testimonial-card",
);
if (!first) return carousel.clientWidth;
const style = getComputedStyle(carousel);
const gap = parseFloat(style.gap) || 0;
return first.offsetWidth + gap;
}
function buildDots() {
// Only build on mobile
if (window.innerWidth > 768) {
wrap.innerHTML = "";
return;
}
const cw = cardWidth();
const total = Math.max(1, Math.round(carousel.scrollWidth / cw));
// Rebuild only if count changed
if (wrap.children.length === total) return;
wrap.innerHTML = "";
for (let i = 0; i < total; i++) {
const d = document.createElement("button");
d.className = "swipe-dot" + (i === 0 ? " active" : "");
d.setAttribute("aria-label", `Go to item ${i + 1}`);
d.addEventListener("click", () => {
carousel.scrollTo({ left: cw * i, behavior: "smooth" });
});
wrap.appendChild(d);
}
}
function updateActive() {
const dots = wrap.querySelectorAll(".swipe-dot");
if (!dots.length) return;
const cw = cardWidth();
const idx = Math.min(
Math.round(carousel.scrollLeft / cw),
dots.length - 1,
);
dots.forEach((d, i) => d.classList.toggle("active", i === idx));
}
buildDots();
carousel.addEventListener("scroll", updateActive, { passive: true });
window.addEventListener("resize", buildDots);
}
initSwipeDots("productGrid", "prodDots");
initSwipeDots("bestSellersCarousel", "bsDots");
initSwipeDots("testimonialGrid", "tDots");
// Re-sync product arrows whenever products are re-rendered (filter/search)
const _origSyncProd = () => {
const p = document.getElementById("productGrid");
const pv = document.getElementById("prodPrev");
const nx = document.getElementById("prodNext");
if (p && pv && nx) setTimeout(() => syncArrows(p, pv, nx), 100);
};
// ═══════════════════════════════════════════════════════════
// SCROLL REVEAL
// ═══════════════════════════════════════════════════════════
const revealObs = new IntersectionObserver(
(entries) => {
entries.forEach((e) => {
if (e.isIntersecting) e.target.classList.add("visible");
});
},
{ threshold: 0.08 },
);
document
.querySelectorAll("section:not(.faq-section), .testimonial-card, .why-item")
.forEach((el) => {
el.classList.add("reveal");
revealObs.observe(el);
});
// ═══════════════════════════════════════════════════════════
// FAQ ACCORDION
// ═══════════════════════════════════════════════════════════
document.querySelectorAll(".faq-question").forEach((btn) => {
btn.addEventListener("click", () => {
const item = btn.parentElement;
const isOpen = item.classList.contains("open");
document
.querySelectorAll(".faq-item")
.forEach((i) => i.classList.remove("open"));
if (!isOpen) item.classList.add("open");
});
});
// ── Cart persistence ───────────────────────────────────────
function saveCart() {
try {
localStorage.setItem("quint_cart", JSON.stringify(cart));
} catch (e) {}
}
function loadCart() {
try {
const saved = localStorage.getItem("quint_cart");
if (saved) {
cart = JSON.parse(saved);
updateCartBadge();
renderCart();
}
} catch (e) {
cart = [];
}
}
// ═══════════════════════════════════════════════════════════
// SHOPPING CART (US-16, US-17)
// ═══════════════════════════════════════════════════════════
function cartCount() {
return cart.reduce((n, i) => n + i.qty, 0);
}
function cartGrandTotal() {
return cart.reduce((n, i) => n + Number(i.product.price) * i.qty, 0);
}
function updateCartBadge() {
const count = cartCount();
const badge = document.getElementById("cartBadge");
badge.textContent = count;
badge.style.display = count > 0 ? "flex" : "none";
}
function renderCart() {
const empty = document.getElementById("cartEmpty");
const items = document.getElementById("cartItems");
const footer = document.getElementById("cartFooter");
const total = document.getElementById("cartTotal");
if (!cart.length) {
empty.style.display = "block";
items.innerHTML = "";
footer.style.display = "none";
return;
}
empty.style.display = "none";
footer.style.display = "block";
total.textContent = `₦${cartGrandTotal().toLocaleString()}`;
items.innerHTML = cart
.map(
(item, idx) => `
<div class="cart-item" data-idx="${idx}">
<img class="cart-item-img" src="${item.product.image_url || "assets/quint_img_allstar.jpg"}" alt="${item.product.name}" onerror="this.src='assets/quint_img_allstar.jpg'"/>
<div class="cart-item-info">
<div class="cart-item-name">${item.product.name}</div>
<div class="cart-item-cat">${item.product.category}</div>
<div class="cart-item-price">₦${(Number(item.product.price) * item.qty).toLocaleString()}</div>
<div class="cart-item-qty">
<button class="qty-btn qty-minus" data-idx="${idx}">−</button>
<span class="qty-num">${item.qty}</span>
<button class="qty-btn qty-plus" data-idx="${idx}">+</button>
</div>
</div>
<button class="cart-item-remove" data-idx="${idx}" aria-label="Remove">✕</button>
</div>`,
)
.join("");
items
.querySelectorAll(".qty-minus")
.forEach((b) =>
b.addEventListener("click", () => changeQty(+b.dataset.idx, -1)),
);
items
.querySelectorAll(".qty-plus")
.forEach((b) =>
b.addEventListener("click", () => changeQty(+b.dataset.idx, 1)),
);
items
.querySelectorAll(".cart-item-remove")
.forEach((b) =>
b.addEventListener("click", () => removeFromCart(+b.dataset.idx)),
);
}
function addToCart(product) {
const existing = cart.find((i) => i.product.id === product.id);
if (existing) {
existing.qty++;
showToast(`${product.name} — qty updated 🛒`);
} else {
cart.push({ product, qty: 1 });
showToast(`${product.name} added to cart 🛒`);
}
updateCartBadge();
renderCart();
saveCart();
}
function changeQty(idx, delta) {
cart[idx].qty += delta;
if (cart[idx].qty <= 0) cart.splice(idx, 1);
updateCartBadge();
renderCart();
saveCart();
}
function removeFromCart(idx) {
cart.splice(idx, 1);
updateCartBadge();
renderCart();
saveCart();
}
// Cart drawer open/close
const cartDrawer = document.getElementById("cartDrawer");
const cartOverlay = document.getElementById("cartOverlay");
function openCart() {
cartDrawer.classList.add("open");
cartOverlay.classList.add("open");
document.body.style.overflow = "hidden";
}
function closeCart() {
cartDrawer.classList.remove("open");
cartOverlay.classList.remove("open");
document.body.style.overflow = "";
}
document.getElementById("cartToggleBtn").addEventListener("click", openCart);
document.getElementById("cartCloseBtn").addEventListener("click", closeCart);
cartOverlay.addEventListener("click", closeCart);
document.getElementById("cartClearBtn").addEventListener("click", () => {
cart = [];
updateCartBadge();
renderCart();
saveCart();
showToast("Cart cleared");
});
// ═══════════════════════════════════════════════════════════
// CHECKOUT FLOW
// ═══════════════════════════════════════════════════════════
function openCheckout() {
const summary = document.getElementById("checkoutSummary");
summary.innerHTML = cart
.map(
(i) =>
`<div class="checkout-line">
<span class="checkout-line-name">${i.product.name} <span class="checkout-line-qty">×${i.qty}</span></span>
<span class="checkout-line-price">₦${(Number(i.product.price) * i.qty).toLocaleString()}</span>
</div>`,
)
.join("");
document.getElementById("checkoutTotal").textContent =
`₦${cartGrandTotal().toLocaleString()}`;
document.getElementById("checkoutError").textContent = "";
// Instantly hide cart (bypass CSS transitions) so it doesn't cover/dim checkout
cartDrawer.classList.remove("open");
cartOverlay.classList.remove("open");
cartOverlay.style.transition = "none";
cartOverlay.style.opacity = "0";
cartOverlay.style.pointerEvents = "none";
cartDrawer.style.transition = "none";
cartDrawer.style.transform = "translateX(110%)";
// Restore transitions after a tick so future cart opens animate normally
requestAnimationFrame(() => {
cartOverlay.style.transition = "";
cartOverlay.style.opacity = "";
cartOverlay.style.pointerEvents = "";
cartDrawer.style.transition = "";
cartDrawer.style.transform = "";
});
document.getElementById("checkoutModal").style.display = "flex";
document.body.style.overflow = "hidden";
}
function closeCheckout() {
document.getElementById("checkoutModal").style.display = "none";
document.body.style.overflow = "";
}
document
.getElementById("cartCheckoutBtn")
.addEventListener("click", openCheckout);
document
.getElementById("checkoutClose")
.addEventListener("click", closeCheckout);
document.getElementById("checkoutModal").addEventListener("click", (e) => {
if (e.target === document.getElementById("checkoutModal")) closeCheckout();
});
document
.getElementById("checkoutSubmitBtn")
.addEventListener("click", async () => {
const name = document.getElementById("checkoutName").value.trim();
const phone = document.getElementById("checkoutPhone").value.trim();
const errEl = document.getElementById("checkoutError");
if (!name) {
errEl.textContent = "Please enter your full name.";
return;
}
if (!phone) {
errEl.textContent = "Please enter your phone number.";
return;
}
errEl.textContent = "";
const btn = document.getElementById("checkoutSubmitBtn");
btn.disabled = true;
btn.textContent = "Saving order…";
const ref = "QNT-" + Date.now().toString(36).toUpperCase();
const items = cart.map((i) => ({
id: i.product.id,
name: i.product.name,
qty: i.qty,
price: Number(i.product.price),
}));
const total = cartGrandTotal();
if (db) {
try {
await db
.from("orders")
.insert([
{
ref,
customer_name: name,
customer_phone: phone,
items: JSON.stringify(items),
total,
status: "Pending",
},
]);
} catch (e) {
/* non-blocking */
}
}
const lines = items
.map(
(i) =>
`• ${i.name} (×${i.qty}) — ₦${(i.price * i.qty).toLocaleString()}`,
)
.join("\n");
const msg = `Hello! I'd like to place an order 🛍️\n\n*Ref: ${ref}*\nName: ${name}\nPhone: ${phone}\n\n${lines}\n\n*Total: ₦${total.toLocaleString()}*\n\nPlease share payment details. Thank you!`;
const waUrl = `https://wa.me/${whatsappNumber}?text=${encodeURIComponent(msg)}`;
cart = [];
saveCart();
updateCartBadge();
renderCart();
closeCheckout();
closeCart();
btn.disabled = false;
btn.innerHTML = `<i data-lucide="message-circle"></i> Place Order via WhatsApp`;
if (window.lucide) lucide.createIcons();
showToast(`Order ${ref} placed! Opening WhatsApp… 🎉`);
setTimeout(() => window.open(waUrl, "_blank"), 600);
});
// ═══════════════════════════════════════════════════════════
// ADMIN — ORDERS
// ═══════════════════════════════════════════════════════════
async function loadAdminOrders() {
const adminMain = document.querySelector(".admin-main");
const scrollTop = adminMain ? adminMain.scrollTop : 0;
const tbody = document.getElementById("ordersTableBody");
if (!tbody) return;
tbody.innerHTML =
'<tr><td colspan="8" class="loading-cell">Loading…</td></tr>';
if (!db) {
tbody.innerHTML =
'<tr><td colspan="8" class="loading-cell">Not connected.</td></tr>';
return;
}
const { data, error } = await db
.from("orders")
.select("*")
.order("created_at", { ascending: false });
if (error) {
const msg =
error.message && error.message.toLowerCase().includes("relation")
? "Orders table not set up yet. Run the SQL from the setup guide."
: error.message;
tbody.innerHTML = `<tr><td colspan="8" class="error-cell">${msg}</td></tr>`;
return;
}
const badge = document.getElementById("orderCount");
if (badge)
badge.textContent = `${(data || []).length} order${(data || []).length !== 1 ? "s" : ""}`;
if (!data || !data.length) {
tbody.innerHTML =
'<tr><td colspan="8" class="loading-cell">No orders yet.</td></tr>';
return;
}
const STATUS_OPTS = [
"Pending",
"Confirmed",
"Dispatched",
"Delivered",
"Cancelled",
];
tbody.innerHTML = data
.map((o) => {
let itemsSummary = "";
try {
const arr =
typeof o.items === "string" ? JSON.parse(o.items) : o.items || [];
itemsSummary = arr.map((i) => `${i.name} ×${i.qty}`).join(", ");
} catch (e) {
itemsSummary = String(o.items || "");
}
const statusOpts = STATUS_OPTS.map(
(s) =>
`<option value="${s}" ${o.status === s ? "selected" : ""}>${s}</option>`,
).join("");
return `<tr>
<td data-label="Ref"><span class="order-ref">${o.ref || "—"}</span></td>
<td data-label="Customer"><strong>${o.customer_name || "—"}</strong></td>
<td data-label="Phone"><a href="https://wa.me/${(o.customer_phone || "").replace(/\D/g, "")}" target="_blank" class="order-phone-link">${o.customer_phone || "—"}</a></td>
<td data-label="Items" class="order-items-cell">${itemsSummary}</td>
<td data-label="Total">₦${Number(o.total || 0).toLocaleString()}</td>
<td data-label="Status"><select class="order-status-select" data-id="${o.id}">${statusOpts}</select></td>
<td data-label="Date">${new Date(o.created_at).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}</td>
<td data-label="Actions"><button class="action-btn delete-btn order-delete-btn" data-id="${o.id}">🗑️</button></td>
</tr>`;
})
.join("");
tbody.querySelectorAll(".order-status-select").forEach((sel) => {
sel.addEventListener("change", async () => {
await db
.from("orders")
.update({ status: sel.value })
.eq("id", sel.dataset.id);
showToast(`Order updated to ${sel.value}`);
});
});
tbody.querySelectorAll(".order-delete-btn").forEach((btn) => {
btn.addEventListener("click", async () => {
if (!confirm("Delete this order?")) return;
await db.from("orders").delete().eq("id", btn.dataset.id);
showToast("Order deleted.");
loadAdminOrders();
});
});
if (adminMain)
requestAnimationFrame(() => {
adminMain.scrollTop = scrollTop;
});
}
// ═══════════════════════════════════════════════════════════
// ANALYTICS DASHBOARD
// ═══════════════════════════════════════════════════════════
async function renderAnalytics() {
if (!db) return;
const safeQuery = async (fn) => {
try {
const r = await fn();
return r.data || [];
} catch (e) {
return [];
}
};
const [prods, subs, revs, ords, vids] = await Promise.all([
safeQuery(() => db.from("products").select("*")),
safeQuery(() => db.from("subscribers").select("created_at")),
safeQuery(() => db.from("reviews").select("rating")),
safeQuery(() => db.from("orders").select("status,total,created_at")),
safeQuery(() => db.from("videos").select("id")),
]);
const totalRevenue = ords
.filter((o) => o.status !== "Cancelled")
.reduce((s, o) => s + Number(o.total || 0), 0);
const statCards = [
{ icon: "package", label: "Total Products", value: prods.length },
{
icon: "eye",
label: "Visible",
value: prods.filter((p) => !p.is_hidden).length,
},
{
icon: "check-circle",
label: "In Stock",
value: prods.filter((p) => p.is_in_stock !== false).length,
},
{
icon: "star",
label: "Best Sellers",
value: prods.filter((p) => p.is_best_seller).length,
},
{ icon: "video", label: "Videos", value: vids.length },
{ icon: "users", label: "Subscribers", value: subs.length },
{ icon: "message-square", label: "Reviews", value: revs.length },
{ icon: "shopping-bag", label: "Total Orders", value: ords.length },
{
icon: "banknote",
label: "Est. Revenue",
value: `₦${totalRevenue.toLocaleString()}`,
},
{
icon: "clock",
label: "Pending",
value: ords.filter((o) => o.status === "Pending").length,
},
{
icon: "truck",
label: "Dispatched",
value: ords.filter((o) => o.status === "Dispatched").length,
},
{
icon: "package-check",
label: "Delivered",
value: ords.filter((o) => o.status === "Delivered").length,
},
];
const grid = document.getElementById("analyticsGrid");
if (grid)
grid.innerHTML = statCards
.map(
(c) => `
<div class="analytics-stat-card">
<div class="analytics-stat-icon"><i data-lucide="${c.icon}"></i></div>
<div class="analytics-stat-value">${c.value}</div>
<div class="analytics-stat-label">${c.label}</div>
</div>`,
)
.join("");
if (window.lucide) lucide.createIcons();
function renderBarChart(id, data) {
const el = document.getElementById(id);
if (!el) return;
if (!data.length) {
el.innerHTML = '<p class="chart-empty">No data yet.</p>';
return;
}
const max = Math.max(...data.map((d) => d.value), 1);
el.innerHTML = data
.map(
(d) => `
<div class="bar-row">
<span class="bar-label" title="${d.label}">${d.label}</span>
<div class="bar-track"><div class="bar-fill" style="width:${Math.round((d.value / max) * 100)}%"></div></div>
<span class="bar-value">${d.value}</span>
</div>`,
)
.join("");
}
const catMap = {};
prods.forEach((p) => {