File size: 25,736 Bytes
c9ba648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b60160
c9ba648
 
3b60160
 
 
c9ba648
3b60160
c9ba648
 
3b60160
 
 
 
 
 
 
 
 
 
c9ba648
 
 
3b60160
c9ba648
 
 
 
 
 
3b60160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ba648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53b07b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ba648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53b07b2
c9ba648
 
 
 
 
 
53b07b2
 
 
 
 
 
 
 
 
 
 
 
 
c9ba648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b60160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53b07b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*=============== SEARCH ===============*/
const searchButton = document.getElementById("search-button"),
  searchClose = document.getElementById("search-close"),
  searchContent = document.getElementById("search-content");

/*===== SEARCH SHOW =====*/
/* Validate if constant exists */
if (searchButton) {
  searchButton.addEventListener("click", () => {
    searchContent.classList.add("show-search");
  });
}

/*===== SEARCH HIDDEN =====*/
/* Validate if constant exists */
if (searchClose) {
  searchClose.addEventListener("click", () => {
    searchContent.classList.remove("show-search");
  });
}

/*=============== SHOPPING BAG ===============*/
const bagButton = document.getElementById("bag-button"),
  bagClose = document.getElementById("bag-close"),
  bagContent = document.getElementById("bag-content");

/*===== CART SHOW =====*/
/* Validate if constant exists */
if (bagButton) {
  bagButton.addEventListener("click", () => {
    bagContent.classList.add("show-bag");
  });
}

/*===== CART HIDDEN =====*/
/* Validate if constant exists */
if (bagClose) {
  bagClose.addEventListener("click", () => {
    bagContent.classList.remove("show-bag");
  });
}

/*=============== LOGIN ===============*/
/*=============== LOGIN & USER MENU ===============*/
const loginButton = document.getElementById("login-button"),
  loginClose = document.getElementById("login-close"),
  loginContent = document.getElementById("login-content"),
  userMenuClose = document.getElementById("user-menu-close"),
  userMenuContent = document.getElementById("user-menu-content");

/*===== HANDLE LOGIN BUTTON CLICK =====*/
if (loginButton) {
  loginButton.addEventListener("click", () => {
    // Kiểm tra trạng thái đăng nhập
    const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";

    if (isLoggedIn) {
      // Đã đăng nhập -> hiển thị user menu
      showUserMenu();
    } else {
      // Chưa đăng nhập -> hiển thị form đăng nhập
      loginContent.classList.add("show-login");
    }
  });
}

/*===== LOGIN FORM HIDDEN =====*/
if (loginClose) {
  loginClose.addEventListener("click", () => {
    loginContent.classList.remove("show-login");
  });
}

/*===== USER MENU HIDDEN =====*/
if (userMenuClose) {
  userMenuClose.addEventListener("click", () => {
    userMenuContent.classList.remove("show-user-menu");
  });
}

/*=============== LOGIN FORM HANDLER ===============*/
document.addEventListener("DOMContentLoaded", function () {
  const loginForm = document.querySelector(".login__form");

  if (loginForm) {
    loginForm.addEventListener("submit", handleLogin);
  }
});

function handleLogin(event) {
  // Ngăn form submit mặc định (reload trang)
  event.preventDefault();

  // Lấy giá trị từ input
  const emailInput = document.getElementById("login-email");
  const passwordInput = document.getElementById("login-pass");

  const email = emailInput.value.trim();
  const password = passwordInput.value.trim();

  // Kiểm tra thông tin đăng nhập
  validateLogin(email, password);
}

function validateLogin(email, password) {
  // Thông tin đăng nhập đúng
  const VALID_EMAIL = "dothulieu12@gmail.com";
  const VALID_PASSWORD = "lieu123";

  // Kiểm tra email và password có trống không
  if (!email || !password) {
    showLoginMessage("Vui lòng nhập đầy đủ email và mật khẩu!", "error");
    return;
  }

  // Kiểm tra thông tin đăng nhập
  if (email === VALID_EMAIL && password === VALID_PASSWORD) {
    showLoginMessage(
      "Đăng nhập thành công! Chào mừng bạn đến với ThuLieu Store!",
      "success"
    );
    // Đóng modal sau khi đăng nhập thành công
    setTimeout(() => {
      closeLoginModal();
      clearLoginForm();
    }, 2000);
  } else {
    showLoginMessage(
      "Email hoặc mật khẩu không đúng. Vui lòng thử lại!",
      "error"
    );
  }
}

function showLoginMessage(message, type) {
  // Tạo element thông báo
  const messageDiv = document.createElement("div");
  messageDiv.className = `login__message login__message--${type}`;
  messageDiv.textContent = message;

  // Tìm form để chèn thông báo
  const loginForm = document.querySelector(".login__form");
  const loginTitle = document.querySelector(".login__title");

  // Xóa thông báo cũ nếu có
  const existingMessage = loginForm.querySelector(".login__message");
  if (existingMessage) {
    existingMessage.remove();
  }

  // Chèn thông báo sau title
  loginTitle.insertAdjacentElement("afterend", messageDiv);

  // Tự động ẩn thông báo sau 5 giây
  setTimeout(() => {
    if (messageDiv.parentNode) {
      messageDiv.remove();
    }
  }, 5000);
}

function closeLoginModal() {
  const loginContent = document.getElementById("login-content");
  if (loginContent) {
    loginContent.classList.remove("show-login");
  }
}

function clearLoginForm() {
  const emailInput = document.getElementById("login-email");
  const passwordInput = document.getElementById("login-pass");

  if (emailInput) emailInput.value = "";
  if (passwordInput) passwordInput.value = "";

  // Xóa thông báo
  const messageDiv = document.querySelector(".login__message");
  if (messageDiv) {
    messageDiv.remove();
  }
}

function validateLogin(email, password) {
  const VALID_EMAIL = "dothulieu12@gmail.com";
  const VALID_PASSWORD = "lieu123";

  // Hiển thị loading
  showLoginMessage("Đang xử lý...", "loading");

  // Giả lập thời gian xử lý
  setTimeout(() => {
    if (!email || !password) {
      showLoginMessage("Vui lòng nhập đầy đủ email và mật khẩu!", "error");
      return;
    }

    if (email === VALID_EMAIL && password === VALID_PASSWORD) {
      // Lưu trạng thái đăng nhập
      localStorage.setItem("isLoggedIn", "true");
      localStorage.setItem("userEmail", email);

      showLoginMessage(
        "Đăng nhập thành công! Chào mừng bạn đến với ThuLieu Store!",
        "success"
      );
      setTimeout(() => {
        closeLoginModal();
        clearLoginForm();
        updateUIAfterLogin();
      }, 2000);
    } else {
      showLoginMessage(
        "Email hoặc mật khẩu không đúng. Vui lòng thử lại!",
        "error"
      );
    }
  }, 1000);
}

function updateUIAfterLogin() {
  // Thay đổi icon đăng nhập thành icon user đã đăng nhập
  const loginButton = document.getElementById("login-button");
  if (loginButton) {
    loginButton.classList.remove("ri-user-line");
    loginButton.classList.add("ri-user-3-fill");
    loginButton.title = "Thông tin tài khoản";

    // Thêm class để đánh dấu đã đăng nhập
    loginButton.classList.add("logged-in");
  }
}

/*=============== ADD SHADOW HEADER ===============*/
const shadowHeader = () => {
  const header = document.getElementById("header");
  // When the scroll is greater than 50 viewport height, add the shadow-header class to the header tag
  this.scrollY >= 50
    ? header.classList.add("shadow-header")
    : header.classList.remove("shadow-header");
};
window.addEventListener("scroll", shadowHeader);

/*=============== HOME SWIPER ===============*/
let swiperHome = new Swiper(".home__swiper", {
  loop: true,
  spaceBetween: -24,
  grabCursor: true,
  slidesPerView: "auto",
  centeredSlides: "auto",

  autoplay: {
    delay: 3000,
    disableOnInteraction: false,
  },

  breakpoints: {
    1220: {
      spaceBetween: -32,
    },
  },
});

/*=============== FEATURED SWIPER ===============*/
// Khởi tạo swiper cho tất cả các category
document.addEventListener("DOMContentLoaded", function () {
  // Tìm tất cả các swiper trong featured
  const featuredSwipers = document.querySelectorAll(".featured__swiper");

  featuredSwipers.forEach((swiperElement, index) => {
    new Swiper(swiperElement, {
      loop: true,
      spaceBetween: 16,
      grabCursor: true,
      slidesPerView: "auto",
      centeredSlides: "auto",

      navigation: {
        nextEl: swiperElement.querySelector(".swiper-button-next"),
        prevEl: swiperElement.querySelector(".swiper-button-prev"),
      },

      breakpoints: {
        1150: {
          slidesPerView: 4,
          centeredSlides: false,
        },
      },

      // Thêm class unique cho mỗi swiper
      on: {
        init: function () {
          swiperElement.classList.add(`featured-swiper-${index + 1}`);
        },
      },
    });
  });
});

/*=============== FEATURED ADD TO CART ===============*/
document.addEventListener("DOMContentLoaded", function () {
  const addToCartButtons = document.querySelectorAll(".featured__card .button");
  const clearCartButton = document.getElementById("clearCart");
  const checkoutButton = document.getElementById("checkOut");

  addToCartButtons.forEach((button) => {
    button.addEventListener("click", addToCartHandler);
  });

  clearCartButton.addEventListener("click", clearCartHandler);
  checkoutButton.addEventListener("click", checkoutHandler);

  updateCartUI();
});

function addToCartHandler(event) {
  const featuredCard = event.target.closest(".featured__card");

  const productName = featuredCard.querySelector(".featured__title").innerText;
  const productPrice =
    parseFloat(
      featuredCard.querySelector(".featured__discount").dataset.price
    ) || 0;

  alert(`Đã thêm vào giỏ hàng: ${productName}`);

  addToCart(productName, productPrice);

  updateCartUI();
}

function addToCart(productName, productPrice) {
  let cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];

  cartItems.push({ name: productName, price: productPrice });

  localStorage.setItem("cartItems", JSON.stringify(cartItems));
}

function updateCartUI() {
  const cartItemsContainer = document.getElementById("cartItemsContainer");
  const cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];

  cartItemsContainer.innerHTML = "";

  cartItems.forEach((item) => {
    const cartItemElement = document.createElement("div");
    cartItemElement.innerText = `${item.name} - ${item.price} VND`;
    cartItemsContainer.appendChild(cartItemElement);
  });

  const totalAmount = calculateTotalAmount(cartItems);
  displayTotalAmount(totalAmount);
}

function calculateTotalAmount(cartItems) {
  return cartItems.reduce((total, item) => total + item.price, 0);
}

function displayTotalAmount(amount) {
  let totalAmountContainer = document.getElementById("totalAmountContainer");

  if (!totalAmountContainer) {
    totalAmountContainer = document.createElement("div");
    totalAmountContainer.id = "totalAmountContainer";
    const bagForm = document.querySelector(".bag__form");
    bagForm.appendChild(totalAmountContainer);
  }

  totalAmountContainer.innerText = `Tổng cộng: ${amount} VND`;
}

function clearCartHandler() {
  localStorage.removeItem("cartItems");

  updateCartUI();
}

function checkoutHandler() {
  alert("Đã thanh toán thành công!");

  resetCart();

  updateCartUI();
}

function resetCart() {
  localStorage.removeItem("cartItems");
}

/*=============== NEW SWIPER ===============*/
let swiperNew = new Swiper(".new__swiper", {
  loop: false,
  spaceBetween: 16,
  slidesPerView: "auto",

  breakpoints: {
    1150: {
      slidesPerView: 3,
    },
  },
});

/*=============== TESTIMONIAL SWIPER ===============*/
let swiperTestimonial = new Swiper(".testimonial__swiper", {
  loop: true,
  spaceBetween: 16,
  grabCursor: true,
  slidesPerView: "auto",
  centeredSlides: "auto",

  breakpoints: {
    1150: {
      slidesPerView: 3,
      centeredSlides: false,
    },
  },
});

/*=============== SHOW SCROLL UP ===============*/
const scrollUp = () => {
  const scrollUp = document.getElementById("scroll-up");
  // When the scroll is higher than 350 viewport height, add the show-scroll class to the a tag with the scrollup class
  this.scrollY >= 350
    ? scrollUp.classList.add("show-scroll")
    : scrollUp.classList.remove("show-scroll");
};
window.addEventListener("scroll", scrollUp);

/*=============== SCROLL SECTIONS ACTIVE LINK ===============*/
const sections = document.querySelectorAll("section[id]");

const scrollActive = () => {
  const scrollDown = window.scrollY;

  sections.forEach((current) => {
    const sectionHeight = current.offsetHeight,
      sectionTop = current.offsetTop - 58,
      sectionId = current.getAttribute("id"),
      sectionsClass = document.querySelector(
        ".nav__menu a[href*=" + sectionId + "]"
      );

    if (scrollDown > sectionTop && scrollDown <= sectionTop + sectionHeight) {
      sectionsClass.classList.add("active-link");
    } else {
      sectionsClass.classList.remove("active-link");
    }
  });
};
window.addEventListener("scroll", scrollActive);

/*=============== DARK LIGHT THEME ===============*/
const themeButton = document.getElementById("theme-button");
const darkTheme = "dark-theme";
const iconTheme = "ri-sun-line";

// Previously selected topic (if user selected)
const selectedTheme = localStorage.getItem("selected-theme");
const selectedIcon = localStorage.getItem("selected-icon");

// We obtain the current theme that the interface has by validating the dark-theme class
const getCurrentTheme = () =>
  document.body.classList.contains(darkTheme) ? "dark" : "light";
const getCurrentIcon = () =>
  themeButton.classList.contains(iconTheme) ? "ri-moon-line" : "ri-sun-line";

// We validate if the user previously chose a topic
if (selectedTheme) {
  // If the validation is fulfilled, we ask what the issue was to know if we activated or deactivated the dark
  document.body.classList[selectedTheme === "dark" ? "add" : "remove"](
    darkTheme
  );
  themeButton.classList[selectedIcon === "ri-moon-line" ? "add" : "remove"](
    iconTheme
  );
}

// Activate / deactivate the theme manually with the button
themeButton.addEventListener("click", () => {
  // Add or remove the dark / icon theme
  document.body.classList.toggle(darkTheme);
  themeButton.classList.toggle(iconTheme);
  // We save the theme and the current icon that the user chose
  localStorage.setItem("selected-theme", getCurrentTheme());
  localStorage.setItem("selected-icon", getCurrentIcon());
});

/*=============== SCROLL REVEAL ANIMATION ===============*/
const sr = ScrollReveal({
  origin: "top",
  distance: "60px",
  duration: 2500,
  delay: 400,
});

sr.reveal(`.home__data, .new__container, 

           .join__data, .testimonial__container, .footer`);
sr.reveal(`.home__images`, { delay: 600 });
sr.reveal(`.services__card`, { interval: 100 });
sr.reveal(`.discount__data`, { origin: "left" });
sr.reveal(`.discount__images`, { origin: "right" });

// Thêm animation cho category headers
sr.reveal(`.featured__category-header`, {
  interval: 200,
  distance: "30px",
  duration: 1000,
});

// Animation cho featured containers
sr.reveal(`.featured__container`, {
  interval: 300,
  delay: 200,
});

/*=============== OPEN DETAIL TAB ===============*/
function openDetailPage() {
  // Đường dẫn tới trang detail.html
  var detailPageURL = "product_detail.html";

  // Mở tab mới
  window.open(detailPageURL, "_blank");
}

/*================ CART ========================*/
/*=============== FEATURED ADD TO CART ===============*/
document.addEventListener("DOMContentLoaded", function () {
  const addToCartButtons = document.querySelectorAll(".featured__card .button");
  const clearCartButton = document.getElementById("clearCart");
  const checkoutButton = document.getElementById("checkOut");

  addToCartButtons.forEach((button) => {
    button.addEventListener("click", addToCartHandler);
  });

  clearCartButton.addEventListener("click", clearCartHandler);
  checkoutButton.addEventListener("click", checkoutHandler);

  updateCartUI();
});

function addToCartHandler(event) {
  const featuredCard = event.target.closest(".featured__card");

  const productName = featuredCard.querySelector(".featured__title").innerText;
  const productPrice =
    parseFloat(
      featuredCard.querySelector(".featured__discount").dataset.price
    ) || 0;

  alert(`Đã thêm vào giỏ hàng: ${productName}`);

  addToCart(productName, productPrice);

  updateCartUI();
}

function addToCart(productName, productPrice) {
  let cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];

  cartItems.push({ name: productName, price: productPrice });

  localStorage.setItem("cartItems", JSON.stringify(cartItems));
}

function updateCartUI() {
  const cartItemsContainer = document.getElementById("cartItemsContainer");
  const cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];

  cartItemsContainer.innerHTML = "";

  cartItems.forEach((item) => {
    const cartItemElement = document.createElement("div");
    cartItemElement.innerText = `${item.name} - ${item.price} VND`;
    cartItemsContainer.appendChild(cartItemElement);
  });

  const totalAmount = calculateTotalAmount(cartItems);
  displayTotalAmount(totalAmount);
}

function calculateTotalAmount(cartItems) {
  return cartItems.reduce((total, item) => total + item.price, 0);
}

function displayTotalAmount(amount) {
  let totalAmountContainer = document.getElementById("totalAmountContainer");

  if (!totalAmountContainer) {
    totalAmountContainer = document.createElement("div");
    totalAmountContainer.id = "totalAmountContainer";
    const bagForm = document.querySelector(".bag__form");
    bagForm.appendChild(totalAmountContainer);
  }

  totalAmountContainer.innerText = `Tổng cộng: ${amount} VND`;
}

function clearCartHandler() {
  localStorage.removeItem("cartItems");

  updateCartUI();
}

function checkoutHandler() {
  alert("Đã thanh toán thành công!");

  resetCart();

  updateCartUI();
}

function resetCart() {
  localStorage.removeItem("cartItems");
}

/*=============== USER MENU FUNCTIONS ===============*/
function showUserMenu() {
  // Cập nhật thông tin user
  updateUserMenuInfo();

  // Hiển thị menu
  userMenuContent.classList.add("show-user-menu");
}

function updateUserMenuInfo() {
  const userEmail = localStorage.getItem("userEmail") || "email@example.com";
  const userName = extractNameFromEmail(userEmail);

  // Cập nhật tên và email
  const userNameElement = document.getElementById("user-name");
  const userEmailElement = document.getElementById("user-email");

  if (userNameElement) {
    userNameElement.textContent = userName;
  }

  if (userEmailElement) {
    userEmailElement.textContent = userEmail;
  }
}

function extractNameFromEmail(email) {
  // Lấy phần trước @ và format thành tên
  const name = email.split("@")[0];

  // Xử lý các trường hợp đặc biệt
  if (name === "dothulieu12") {
    return "Thu Liêu";
  }

  // Format tên từ email
  return name.charAt(0).toUpperCase() + name.slice(1).replace(/[0-9]/g, "");
}

/*=============== LOGOUT FUNCTIONALITY ===============*/
document.addEventListener("DOMContentLoaded", function () {
  // Kiểm tra trạng thái đăng nhập khi tải trang
  checkLoginStatus();

  // Xử lý sự kiện đăng xuất
  const logoutButton = document.getElementById("logout-button");
  if (logoutButton) {
    logoutButton.addEventListener("click", handleLogout);
  }

  // Xử lý các nút khác trong user menu
  const viewProfileButton = document.getElementById("view-profile");
  const viewOrdersButton = document.getElementById("view-orders");

  if (viewProfileButton) {
    viewProfileButton.addEventListener("click", () => {
      alert("Chức năng thông tin cá nhân đang được phát triển!");
    });
  }

  if (viewOrdersButton) {
    viewOrdersButton.addEventListener("click", () => {
      alert("Chức năng đơn hàng đang được phát triển!");
    });
  }
});

function checkLoginStatus() {
  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";

  if (isLoggedIn) {
    updateUIAfterLogin();
  }
}

function handleLogout() {
  // Hiển thị xác nhận đăng xuất
  const confirmLogout = confirm("Bạn có chắc chắn muốn đăng xuất?");

  if (confirmLogout) {
    // Xóa thông tin đăng nhập
    localStorage.removeItem("isLoggedIn");
    localStorage.removeItem("userEmail");

    // Đóng user menu
    userMenuContent.classList.remove("show-user-menu");

    // Cập nhật UI về trạng thái chưa đăng nhập
    updateUIAfterLogout();

    // Hiển thị thông báo
    showLogoutMessage();
  }
}

function updateUIAfterLogout() {
  const loginButton = document.getElementById("login-button");
  if (loginButton) {
    loginButton.classList.remove("ri-user-3-fill", "logged-in");
    loginButton.classList.add("ri-user-line");
    loginButton.title = "Đăng nhập";
  }
}

function showLogoutMessage() {
  // Tạo thông báo đăng xuất
  const messageDiv = document.createElement("div");
  messageDiv.className = "logout-message";
  messageDiv.innerHTML = `

        <div class="logout-message__content">

            <i class="ri-check-line"></i>

            <span>Đăng xuất thành công!</span>

        </div>

    `;

  document.body.appendChild(messageDiv);

  // Hiển thị animation
  setTimeout(() => {
    messageDiv.classList.add("show");
  }, 100);

  // Tự động ẩn sau 3 giây
  setTimeout(() => {
    messageDiv.classList.remove("show");
    setTimeout(() => {
      if (messageDiv.parentNode) {
        messageDiv.remove();
      }
    }, 300);
  }, 3000);
}

/*=============== PRODUCT DETAIL FUNCTIONALITY ===============*/
document.addEventListener("DOMContentLoaded", function () {
  // Gallery functionality
  const galleryThumbs = document.querySelectorAll(".gallery-thumb");
  const mainImage = document.querySelector(".product-detail__image-main img");

  if (galleryThumbs.length > 0 && mainImage) {
    galleryThumbs.forEach((thumb) => {
      thumb.addEventListener("click", function () {
        // Remove active class from all thumbnails
        galleryThumbs.forEach((t) => t.classList.remove("active"));

        // Add active class to clicked thumbnail
        this.classList.add("active");

        // Change main image
        mainImage.src = this.src;
        mainImage.alt = this.alt;
      });
    });
  }

  // Quantity controls
  const qtyMinus = document.querySelector(".qty-minus");
  const qtyPlus = document.querySelector(".qty-plus");
  const qtyInput = document.querySelector(".qty-input");

  if (qtyMinus && qtyPlus && qtyInput) {
    qtyMinus.addEventListener("click", function () {
      let currentValue = parseInt(qtyInput.value);
      if (currentValue > 1) {
        qtyInput.value = currentValue - 1;
      }
    });

    qtyPlus.addEventListener("click", function () {
      let currentValue = parseInt(qtyInput.value);
      qtyInput.value = currentValue + 1;
    });

    qtyInput.addEventListener("change", function () {
      if (this.value < 1) {
        this.value = 1;
      }
    });
  }

  // Add to cart functionality
  const addCartBtn = document.querySelector(".btn-add-cart");
  const buyNowBtn = document.querySelector(".btn-buy-now");
  const wishlistBtn = document.querySelector(".btn-wishlist");

  if (addCartBtn) {
    addCartBtn.addEventListener("click", function () {
      const quantity = qtyInput ? qtyInput.value : 1;
      alert(`Đã thêm ${quantity} sản phẩm vào giỏ hàng!`);
    });
  }

  if (buyNowBtn) {
    buyNowBtn.addEventListener("click", function () {
      const quantity = qtyInput ? qtyInput.value : 1;
      alert(`Mua ngay ${quantity} sản phẩm!`);
    });
  }

  if (wishlistBtn) {
    wishlistBtn.addEventListener("click", function () {
      const icon = this.querySelector("i");
      if (icon.classList.contains("ri-heart-line")) {
        icon.classList.remove("ri-heart-line");
        icon.classList.add("ri-heart-fill");
        this.style.color = "var(--first-color)";
        alert("Đã thêm vào danh sách yêu thích!");
      } else {
        icon.classList.remove("ri-heart-fill");
        icon.classList.add("ri-heart-line");
        this.style.color = "";
        alert("Đã xóa khỏi danh sách yêu thích!");
      }
    });
  }
});

/*=============== CATEGORY SCROLL ANIMATION ===============*/
document.addEventListener("DOMContentLoaded", function () {
  // Intersection Observer cho category headers
  const categoryHeaders = document.querySelectorAll(
    ".featured__category-header"
  );

  const observerOptions = {
    threshold: 0.3,
    rootMargin: "0px 0px -50px 0px",
  };

  const categoryObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.style.animation = "fadeInUp 0.8s ease forwards";
      }
    });
  }, observerOptions);

  categoryHeaders.forEach((header) => {
    header.style.opacity = "0";
    header.style.transform = "translateY(30px)";
    categoryObserver.observe(header);
  });
});