"use client";
import React, { useContext, useState, useEffect } from "react";
import Link from "next/link";
import { Menu, ShoppingBag, UserRound } from "lucide-react";
import authAxios, { backendUrl } from "@/utils/axios";
import { IoMdClose } from "react-icons/io";
import Image from "next/image";
import SearchComponent from "../search/searchComponent";
import ProductContext from "@/app/contexts/productContext";
import MainContext from "@/app/contexts/mainContext";
import { useCurrency } from "@/app/contexts/currencyContext";
import CurrencySelect from "../dynamic-navbar/currencySelect";
const Navbar = () => {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [isScrolled, setIsScrolled] = useState(false);
const { category } = useContext(ProductContext);
const { token, user } = useContext(MainContext);
const [cartItemCount, setCartItemCount] = useState(0);
const {
selectedCurrency,
setSelectedCurrency,
SUPPORTED_CURRENCIES,
error,
setUserCountry,
userCountry
} = useCurrency();
const toggleSidebar = () => setIsSidebarOpen(!isSidebarOpen);
useEffect(() => {
const handleScroll = () => {
const isMobile = window.innerWidth < 768;
setIsScrolled(isMobile || window.scrollY > 60);
};
handleScroll();
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
window.removeEventListener("resize", handleScroll);
};
}, []);
// Set user's country from profile if available
useEffect(() => {
if (user && user.country && !userCountry) {
setUserCountry(user.country);
}
}, [user, setUserCountry, userCountry]);
const getCart = async () => {
try {
const response = await authAxios.get("/orders/cart/");
const cartData = response.data;
// Calculate total items in cart
if (cartData && cartData.length > 0 && cartData[0].items) {
const totalItems = cartData[0].items.reduce(
(sum, item) => sum + item.quantity,
0
);
setCartItemCount(totalItems);
} else {
setCartItemCount(0);
}
} catch (error) {
console.error("Error fetching cart:", error);
setCartItemCount(0);
}
};
// Fetch cart data when component mounts and when token changes
useEffect(() => {
if (token) {
getCart();
} else {
setCartItemCount(0);
}
}, [token]);
// Set up an interval to periodically check for cart updates
useEffect(() => {
if (token) {
// Initial fetch
getCart();
// Set up interval to check for updates every 3 seconds
const intervalId = setInterval(getCart, 3000);
// Clean up interval on component unmount
return () => clearInterval(intervalId);
}
}, [token]);
const categoryItems = category
? category.map((category) => ({
label: category.category_name,
url: `/category/${category.id}`,
}))
: []; // Fallback to an empty array if category is undefined
const consultation = {
label: "Rudraksha consultation",
url: "/products/premium-rudraksha-consultation-astrology",
};
const visibleItems = [...categoryItems.slice(0, 4), consultation];
return (
<>