import { useState, useEffect, useRef } from "react";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import Box from "@mui/material/Box";
import Header from "../Header";
import SearchIcon from "@mui/icons-material/Search";
import LocalMallIcon from '@mui/icons-material/LocalMall';
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import logoSrc from "../../assets/images/amberlogo.png";
import { styled } from '@mui/material/styles';
import { MenuItem, Select, FormControl, Badge, Typography } from '@mui/material';
import MobileNav from "./components/MobileNav";
import SideCart from "../SideCart/SideCart";
import MenuIcon from "@mui/icons-material/Menu";
import SearchProduct from "../SearchProduct"
import CategoryIcon from '@mui/icons-material/Category';
import HomeIcon from '@mui/icons-material/Home';
import BrushIcon from '@mui/icons-material/Brush';
import LoyaltyIcon from '@mui/icons-material/Loyalty';
import Grid from '@mui/material/Grid2';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts } from "../../redux/slices/productSlice";
import ProductService from "../../services/ProductService";

import { Swiper, SwiperSlide } from 'swiper/react';
import { Scrollbar, A11y, Navigation } from 'swiper/modules';

import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';

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

const LanguageSelect = styled(Select)(({ theme }) => ({
  backgroundColor: 'black',
  color: 'white',
  border: '1px solid black',
  fontSize: 12,
  '& .MuiSelect-icon': {
    color: 'white',
  },
  '&:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
  '& .MuiMenuItem-root': {
    backgroundColor: 'black',
    color: 'white',
  },
  '& .MuiMenuItem-root:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
}));

const LanguageSelectItem = styled(MenuItem)(() => ({
  backgroundColor: 'black',
  color: 'white',
  '&:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
}));

const COLLECTION_PRIORITY_BY_TYPE = {
  apparel: [
    "EID'S TIME FOR LOVE COLLECTION",
    "ND X MARII FOR AMBER",
    "MIRAGE COLLECTION",
    "SOMEWHERE SOMEHOW SOMEONE",
    "OASIS ABAYA COLLECTION",
    "RAYA ROMANTICS COLLECTION 2025",
    "CASUAL WEAR",
    "AINA ABDUL MERCHANDISE",
    "ATMA SARI",
    "FLOWER POWER",
    "AMBER SCARVES FLOWER POWER SERIES",
  ],
};

const normalizeTitle = (value = "") => value.trim().toUpperCase();

const getProductTypeMenuLabel = (productType = "") => {
  return normalizeTitle(productType) === "BEAUTY" ? "Essentials" : productType;
};

const NAV_MENU_STRUCTURE = [
  {
    productType: "Apparel",
    label: "APPAREL",
    groups: [
      {
        label: "Casual",
        children: [
          { label: "ND X Marii for Amber", titles: ["ND X MARII FOR AMBER"] },
          { label: "Somewhere Somehow Someone", titles: ["SOMEWHERE SOMEHOW SOMEONE"] },
          { label: "Flower Power", titles: ["FLOWER POWER"] },
        ],
      },
      {
        label: "Traditional",
        children: [
          { label: "Eid's Time For Love", titles: ["EID'S TIME FOR LOVE"] },
          { label: "Raya Romantics", titles: ["RAYA ROMANTICS COLLECTION 2025"] },
          { label: "Atma Sari", titles: ["ATMA SARI"] },
          { label: "Oasis abaya collection", titles: ["OASIS ABAYA COLLECTION", "MIRAGE COLLECTION"] },
        ],
      },
    ],
  },
  {
    productType: "BEAUTY",
    label: "Essentials",
    children: [
      { label: "Cosmetics", titles: ["COSMETICS"] },
      { label: "Hand & Body Lotion", titles: ["HAND & BODY LOTION"] },
    ],
  },
];

const sortCollectionsByPriority = (collection = [], productType = "") => {
  const typeKey = (productType || "").trim().toLowerCase();
  const priorityList = COLLECTION_PRIORITY_BY_TYPE[typeKey] || [];
  const priorityMap = new Map(
    priorityList.map((title, index) => [normalizeTitle(title), index])
  );

  return [...collection].sort((a, b) => {
    const aTitle = normalizeTitle(a?.title || "");
    const bTitle = normalizeTitle(b?.title || "");
    const aPriority = priorityMap.has(aTitle)
      ? priorityMap.get(aTitle)
      : Number.MAX_SAFE_INTEGER;
    const bPriority = priorityMap.has(bTitle)
      ? priorityMap.get(bTitle)
      : Number.MAX_SAFE_INTEGER;

    if (aPriority !== bPriority) {
      return aPriority - bPriority;
    }

    const aUpdatedAt = a?.updatedAt ? Date.parse(a.updatedAt) : 0;
    const bUpdatedAt = b?.updatedAt ? Date.parse(b.updatedAt) : 0;

    if (aUpdatedAt !== bUpdatedAt) {
      return bUpdatedAt - aUpdatedAt;
    }

    return aTitle.localeCompare(bTitle);
  });
};

function mapProductTypesWithCollections(products) {
  // Create a Map to group collections by productType
  const productTypeMap = new Map();

  products.forEach(product => {
    const { productType, collections } = product;

    // If productType already exists, merge its collections
    if (productTypeMap.has(productType)) {
      const existingCollections = productTypeMap.get(productType);
      const newCollections = collections.map(collection => collection);
      productTypeMap.set(productType, [...new Set([...existingCollections, ...newCollections])]);
    } else {
      // Add a new productType with its collections
      productTypeMap.set(productType, collections.map(collection => collection));
    }
  });

  // Convert the Map into the desired array structure
  return Array.from(productTypeMap, ([productType, collection]) => ({ productType, collection }));
}

function getUniqueCollections(data) {
  return data.map(item => {
    // Use a Map to store unique collection titles with their corresponding image
    const uniqueCollectionsMap = new Map();
    item.collection.forEach(({ title, image, updatedAt }) => {
      if (!uniqueCollectionsMap.has(title)) {
        uniqueCollectionsMap.set(title, { title, image, updatedAt });
      }
    });

    // Convert the Map back to an array
    return {
      productType: item.productType,
      collection: sortCollectionsByPriority(
        Array.from(uniqueCollectionsMap.values()),
        item.productType
      )
    };
  });
}

const Navbar = () => {

  const swiperRef = useRef(null); // Create a ref for the Swiper instance
  const childTransitionTimerRef = useRef(null);
  const [showHeader, setShowHeader] = useState(true);
  const [showSearch, setShowSearch] = useState(false);
  const [isAtTop, setIsAtTop] = useState(false);
  const [isProductPage, setIsProductPage] = useState(false);
  const [lastScrollPos, setLastScrollPos] = useState(0);
  const [language, setLanguage] = useState('English');
  const dispatch = useDispatch();

  const cart = useSelector((state) => state.cart.cart)
  const products = useSelector((state) => state.products.products.data)
  const [cartAmount, setCartAmount] = useState(0);

  const [openSideMenu, setOpenSideMenu] = useState(false);
  const [openSideCart, setOpenSideCart] = useState(false);
  const [navItem, setNavItem] = useState([]);
  const [navItemCompanyInfo, setNavItemCompanyInfo] = useState([]);
  const [activeMenu, setActiveMenu] = useState(null);
  const [activeGroup, setActiveGroup] = useState(null);

  const [displayCollection, setDisplayCollection] = useState({
    productType: null,
    list: []
  })

  useEffect(() => {

    dispatch(fetchProducts())
    if (window.location.pathname === "/") setIsAtTop(true);

    const handleScroll = () => {
      if (window.location.pathname === "/") setIsAtTop(window.scrollY < 20);
    };

    window.addEventListener("scroll", handleScroll);

    // Cleanup on component unmount
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };

  }, [])

  useEffect(() => {

    if (!cart?.lines?.nodes) return // don't need to do anything if we have no cart data

    setCartAmount(calculateTotalQuantity(cart?.lines?.nodes))

  }, [cart])

  useEffect(() => {

    //Navbar item are based on products type, thus get all the item and then we should be good
    if (products.length > 0) {

      let navItemData = mapProductTypesWithCollections(products)
      navItemData = getUniqueCollections(navItemData)
      navItemData = navItemData.filter(({ productType }) => normalizeTitle(productType) !== "HOME")

      setNavItem(navItemData)

      // extra info for the navbar
      setNavItemCompanyInfo([]);
      /*
      setNavItemCompanyInfo([{
        name:"DELIVERY INFORMATION",
        link:"/delivery_info"
      },
      {
        name:"SALE TERMS & CONDITIONS",
        link:"/sale_terms_and_condition"
      },
      {
        name:"RETURNS & REFUNDS",
        link:"/return_and_exchange"
      },
      {
        name:"CONTACT US",
        link:"/contact_us"
      }]);
      */

    }

  }, [products])

  const handleChange = (event) => {
    setLanguage(event.target.value);
  };

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollPos = window.scrollY;

      if (currentScrollPos > lastScrollPos && currentScrollPos > 50) setShowHeader(false)
      else setShowHeader(true)

      setLastScrollPos(currentScrollPos);
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [lastScrollPos]);

  const renderCollectionDisplay = (colletion) => {

    return (
      <SwiperSlide>
        <Box
          className="animate__animated animate__fadeIn animate__fast"
          sx={{
            backgroundImage: `url(${colletion?.image?.url})`,
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
            backgroundPosition: "center center",
            height: "100%",
            paddingTop: "85%",
            position: "relative",
            cursor: "pointer",
            transition: "transform 0.3s ease",
          }}
          onClick={() => {
            sessionStorage.setItem('amber-select-collection', JSON.stringify(colletion))
            sessionStorage.setItem('amber-select-product-type', displayCollection.productType)
            window.location.href = `/products`;
          }}
        ></Box>
        <Typography
          variant="body1"
          sx={{
            mt:1,
            color: "black",
            fontWeight: "100",
            fontSize: {
              xs: "0.73rem",
              sm: "0.73rem",
              md: "0.875rem",
            },
          }}
        >
          {colletion?.title?.toUpperCase()}
        </Typography>
      </SwiperSlide>
    )

  }

  const swipeToLeft = () => {
    if (swiperRef.current) {
      swiperRef.current.slidePrev(); // Move to the previous slide
    }
  };

  const swipeToRight = () => {
    if (swiperRef.current) {
      swiperRef.current.slideNext(); // Move to the previous slide
    }
  };

  const displayCollectionList = (collection = [], productType) => {

    const sortedCollection = sortCollectionsByPriority(collection, productType);

    setDisplayCollection([])
    setTimeout(() => {
      setDisplayCollection({
        productType,
        list: sortedCollection
      })
    }, 100);
  }

  const hideCollectionList = () => {
    setDisplayCollection([])
  }

  const handleGroupMouseEnter = (groupLabel) => {
    if (activeGroup === groupLabel) return;

    if (childTransitionTimerRef.current) {
      clearTimeout(childTransitionTimerRef.current);
    }

    setActiveGroup(null);
    childTransitionTimerRef.current = setTimeout(() => {
      setActiveGroup(groupLabel);
    }, 40);
  }

  const navigateToMenuItem = (productType, item = null) => {
    sessionStorage.setItem('amber-select-product-type', productType)
    sessionStorage.removeItem('amber-select-collection')
    sessionStorage.removeItem('amber-select-collections')

    if (item) {
      sessionStorage.setItem('amber-select-collection', JSON.stringify({
        title: item.label,
        image: null
      }))
      sessionStorage.setItem('amber-select-collections', JSON.stringify(item.titles || []))
    }

    window.location.href = `/products`;
  }

  return (
    <>
      <AppBar position="fixed"
        sx={{
          zIndex: 998,
          backgroundColor: (isAtTop) ? "rgba(0, 0, 0, 0)" : "rgba(255, 255, 255, 0.3)",
          backdropFilter: (isAtTop) ? "none" : "blur(10px)",
          boxShadow: 0,
          transition: "all 0.2s ease-in-out",
          ":hover": {
            backgroundColor: "rgba(255,255,255,1) !important",
            backdropFilter: "none !important",
            '& .navItem': {
              color: "black !important"
            },
            '& .navItem:hover': {
              color: "#95AAC5 !important"
            },
          }
        }}
        onMouseLeave={() => {
          hideCollectionList()
          setActiveMenu(null)
          setActiveGroup(null)
        }}
      >

        {/* Conditionally render the Header */}
        {showHeader && <Header />}

        <Toolbar sx={{
          px: {
            xs: 2,
            md: 6,
            lg: 6
          },
          py: 0.5
        }} disableGutters>

          <Box sx={{ display: "flex", alignItems: "center", width: "100%", position: "relative", justifyContent: "space-between" }}>
            {/* SIDEBAR BUTTON */}
            <Box sx={{
              display: {
                xs: "block",
                md: "block",
                lg: "none"
              }
            }}>

              <IconButton
                onClick={() => setOpenSideMenu(true)}
                className="navItem"
                sx={{
                  backgroundColor: "transparent",
                  color: (isAtTop) ? "white" : "black",
                  "&:hover": {
                    backgroundColor: "rgba(0, 0, 0, 0.1)",
                  },
                }}
              >
                <MenuIcon fontSize="large" />
              </IconButton>

            </Box>

            {/* Left Section: Logo */}
            <Box
              sx={{
                mr: {
                  xs: 0,
                  sm: 0,
                  md: 10,
                  lg: 10,
                  xl: 10
                },
                display: {
                  xs: (isProductPage) ? "flex" : "none",
                  md: (isProductPage) ? "flex" : "none",
                  lg: "flex"
                },
              }}
            >
              <a href="/">
                <img src={logoSrc} alt="Logo"
                  style={{
                    width: 130,
                    height: 20,
                  }} />
              </a>
            </Box>

            {/* Center Section: Nav Items */}
            <Box
              sx={{
                flexGrow: 1,
                display: {
                  xs: "none",
                  md: "none",
                  lg: "flex"
                },
                gap: 2
              }}
            >

              {NAV_MENU_STRUCTURE.map((menu) => (
                <Box
                  key={menu.label}
                  sx={{ position: "relative" }}
                  onMouseEnter={() => {
                    if (childTransitionTimerRef.current) {
                      clearTimeout(childTransitionTimerRef.current);
                    }
                    setActiveMenu(menu.label);
                    setActiveGroup(null);
                  }}
                >
                  <Button
                    sx={{
                      position: "relative",
                      ':hover': {
                        backgroundColor: "rgba(0,0,0,0)",
                      }
                    }}
                    color="inherit"
                    onClick={() => {
                      if (!menu.groups && !menu.children) {
                        navigateToMenuItem(menu.productType)
                      }
                    }}
                  >
                    <Typography variant="body2"
                      className="navItem"
                      sx={{
                        fontSize: {
                          xs: "0.73rem",
                          sm: "0.73rem",
                          md: "0.875rem",
                        },
                        color: (isAtTop) ? "white" : "black",
                        transition: "all 0.3s ease-in-out",
                        ":hover": {
                          color: "#95AAC5 !important"
                        },
                        "&::after": {
                          content: '""',
                          position: "absolute",
                          left: "50%",
                          transform: "translateX(-50%)",
                          bottom: 2,
                          width: activeMenu === menu.label ? "70%" : "0%",
                          height: "2px",
                          backgroundColor: "#95AAC5",
                          transition: "width 0.3s ease-in-out",
                        },
                        ":hover::after": {
                          width: "70%",
                        },
                      }}>{menu.label}</Typography>
                  </Button>

                  {(
                    <>
                      <Box
                        sx={{
                          position: "absolute",
                          top: "100%",
                          left: 0,
                          width: menu.groups ? (activeGroup ? 560 : 260) : 260,
                          height: 28,
                          zIndex: 1000,
                          backgroundColor: "transparent",
                          visibility: activeMenu === menu.label ? "visible" : "hidden",
                          pointerEvents: activeMenu === menu.label ? "auto" : "none",
                        }}
                      />
                      <Box
                        sx={{
                          position: "absolute",
                          top: 60,
                          left: 0,
                          width: menu.groups ? (activeGroup ? 560 : 260) : 260,
                          backgroundColor: "#FFF",
                          color: "#000",
                          border: "1px solid rgba(0,0,0,0.08)",
                          borderTop: 0,
                          boxShadow: "0 2px 6px rgba(0,0,0,0.12)",
                          display: "flex",
                          minHeight: "auto",
                          zIndex: 1001,
                          overflow: "hidden",
                          opacity: activeMenu === menu.label ? 1 : 0,
                          visibility: activeMenu === menu.label ? "visible" : "hidden",
                          pointerEvents: activeMenu === menu.label ? "auto" : "none",
                          clipPath: activeMenu === menu.label ? "polygon(0 0, 100% 0, 100% 100%, 0 100%)" : "polygon(0 0, 100% 0, 100% 0, 0 0)",
                          transition: activeGroup ? "clip-path .45s ease-in-out, visibility .45s ease-in-out, opacity .45s ease-in-out, width .55s ease-in-out" : "clip-path .45s ease-in-out, visibility .45s ease-in-out, opacity .45s ease-in-out",
                        }}
                      >
                      {menu.groups ? (
                        <>
                          <Box sx={{ width: 260, pb: 1.5, borderRight: "1px solid rgba(0,0,0,0.12)" }}>
                            {menu.groups.map((group) => (
                              <Button
                                key={group.label}
                                fullWidth
                                onMouseEnter={() => handleGroupMouseEnter(group.label)}
                                sx={{
                                  justifyContent: "space-between",
                                  color: activeGroup === group.label ? "#95AAC5" : "#000",
                                  textTransform: "none",
                                  fontSize: "0.875rem",
                                  py: 1.5,
                                  px: 3,
                                  '&:hover': {
                                    backgroundColor: "transparent",
                                    color: "#95AAC5",
                                  }
                                }}
                              >
                                {group.label?.toUpperCase()}
                                <KeyboardArrowRightIcon sx={{ fontSize: 20 }} />
                              </Button>
                            ))}
                          </Box>

                          {activeGroup && (
                            <Box key={activeGroup} sx={{
                              pb: 1.5,
                              px: 3,
                              width: 300,
                              clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)",
                              overflow: "hidden",
                              position: "relative",
                              animation: "childCardReveal .55s ease-in-out",
                              "@keyframes childCardReveal": {
                                "0%": {
                                  clipPath: "polygon(0 0, 0 0, 0 100%, 0 100%)",
                                },
                                "100%": {
                                  clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)",
                                },
                              },
                            }}>
                              {menu.groups
                                .find((group) => group.label === activeGroup)
                                ?.children.map((item) => (
                                  <Button
                                    key={item.label}
                                    fullWidth
                                    onClick={() => navigateToMenuItem(menu.productType, item)}
                                    sx={{
                                      justifyContent: "flex-start",
                                      color: "#000",
                                      textTransform: "none",
                                      fontSize: "0.875rem",
                                      py: 1.1,
                                      px: 0,
                                      '&:hover': {
                                        backgroundColor: "transparent",
                                        color: "#95AAC5",
                                      }
                                    }}
                                  >
                                    {item.label?.toUpperCase()}
                                  </Button>
                                ))}
                            </Box>
                          )}
                        </>
                      ) : (
                        <Box sx={{ pb: 1.5, px: 3, width: 260 }}>
                          {menu.children.map((item) => (
                            <Button
                              key={item.label}
                              fullWidth
                              onClick={() => navigateToMenuItem(menu.productType, item)}
                              sx={{
                                justifyContent: "flex-start",
                                color: "#000",
                                textTransform: "none",
                                fontSize: "0.875rem",
                                py: 1.1,
                                px: 0,
                                '&:hover': {
                                  backgroundColor: "transparent",
                                  color: "#95AAC5",
                                }
                              }}
                            >
                              {item.label?.toUpperCase()}
                            </Button>
                          ))}
                        </Box>
                      )}
                      </Box>
                    </>
                  )}
                </Box>
              ))}

              {/*
              {navItem.map(({ productType, collection }) => (<Button
                sx={{
                  position: "relative",
                  ':hover': {
                    backgroundColor: "rgba(0,0,0,0)",
                  }
                }}
                color="inherit"
                onClick={() => {
                  sessionStorage.setItem('amber-select-product-type', productType)
                  sessionStorage.removeItem('amber-select-collection')
                  window.location.href = `/products`;
                }}
                onMouseEnter={() => {
                  displayCollectionList(collection, productType)
                }}
              >
                <Typography variant="body2"
                  className="navItem"
                  sx={{
                    fontSize: {
                      xs: "0.73rem",
                      sm: "0.73rem",
                      md: "0.875rem",
                    },
                    color: (isAtTop) ? "white" : "black",
                    transition: "all 0.3s ease-in-out",
                    ":hover": {
                      color: "#95AAC5 !important"
                    },
                    "&::after": {
                      content: '""',
                      position: "absolute",
                      left: "50%",
                      transform: "translateX(-50%)",
                      bottom: 2,
                      width: "0%",
                      height: "2px",
                      backgroundColor: "#95AAC5",
                      transition: "width 0.3s ease-in-out",
                    },
                    ":hover::after": {
                      width: "50%",
                    },
                  }}>{getProductTypeMenuLabel(productType)}</Typography>
              </Button>))}

              {navItemCompanyInfo.map(({ name, link }) => (<Button
                sx={{
                  position: "relative",
                  ':hover': {
                    backgroundColor: "rgba(0,0,0,0)",
                  }
                }}
                color="inherit"
                onClick={() => {
                  window.location.href = `${link}`;
                }}
              >
                <Typography variant="body2"
                  className="navItem"
                  sx={{
                    fontSize: {
                      xs: "0.73rem",
                      sm: "0.73rem",
                      md: "0.875rem",
                    },
                    color: (isAtTop) ? "white" : "black",
                    transition: "all 0.3s ease-in-out",
                    ":hover": {
                      color: "#95AAC5 !important"
                    },
                    "&::after": {
                      content: '""',
                      position: "absolute",
                      left: "50%",
                      transform: "translateX(-50%)",
                      bottom: 2,
                      width: "0%",
                      height: "2px",
                      backgroundColor: "#95AAC5",
                      transition: "width 0.3s ease-in-out",
                    },
                    ":hover::after": {
                      width: "70%",
                    },
                  }}>{name}</Typography>
              </Button>))}
              */}



            </Box>

            {/* Right Section: Search and Profile */}
            <Box sx={{ display: "flex", alignItems: "center", gap: 1.2 }}>

              {/* <FormControl
                sx={{
                  display: {
                    xs: "none",
                    lg: "block"
                  }
                }}
              >
                <LanguageSelect
                  value={language}
                  onChange={handleChange}
                  label=""
                  MenuProps={{
                    PaperProps: {
                      style: {
                        backgroundColor: 'black',
                        color: 'white'
                      },
                    },
                  }}
                >
                  <LanguageSelectItem value="English">English</LanguageSelectItem>
                  <LanguageSelectItem value="Malay">Malay</LanguageSelectItem>
                  <LanguageSelectItem value="Chinese">Chinese</LanguageSelectItem>
                </LanguageSelect>
              </FormControl> */}

              <IconButton onClick={() => { setShowSearch(true) }}>
                <SearchIcon className="navItem" style={{
                  transition: "all 0.3s ease-in-out",
                  color: (isAtTop) ? "white" : "black",
                }} />
              </IconButton>

              <Badge
                sx={{ cursor: "pointer" }}
                onClick={() => { setOpenSideCart(true) }}
                badgeContent={cartAmount} color="primary">
                <LocalMallIcon className="navItem" style={{
                  transition: "all 0.3s ease-in-out",
                  color: (isAtTop) ? "white" : "black",
                }} />
              </Badge>
              {/* <IconButton color="inherit">
                <AccountCircleIcon sx={{ color: "white" }} />
              </IconButton> */}
            </Box>
          </Box>
        </Toolbar>

        {/* On Hover Collection */}
        <Box className="animate__animated animate__fadeIn" sx={{ backgroundColor: "white", position: "relative", py: 5, display: (displayCollection?.list?.length > 0) ? "block" : "none" }}>
          <ChevronLeftIcon
            style={{
              cursor: "pointer",
              color: "black",
              position: "absolute",
              top: "50%",
              fontSize: 50,
              left: 40,
              transform: "translateY(-50%)",
            }}
            onClick={swipeToLeft}
          />

          <Box sx={{ px: 20 }}>
            <Swiper
              modules={[Navigation, Scrollbar, A11y]}
              spaceBetween={20}
              slidesPerView={4}
              pagination={{ clickable: true }}
              scrollbar={{ draggable: true }}
              onSwiper={(swiper) => (swiperRef.current = swiper)}
            >
              {displayCollection?.list?.map((colletion) => {
                return renderCollectionDisplay(colletion)
              })}

            </Swiper>
          </Box>

          <KeyboardArrowRightIcon
            style={{
              cursor: "pointer",
              color: "black",
              fontSize: 50,
              position: "absolute",
              top: "50%",
              right: 40,
              transform: "translateY(-50%)",
            }}
            onClick={swipeToRight}
          />
        </Box>

      </AppBar>
      {showSearch && <SearchProduct onClose={() => { setShowSearch(false) }} />}

      <MobileNav open={openSideMenu} menu={NAV_MENU_STRUCTURE} infomenu={navItemCompanyInfo} onClose={() => { setOpenSideMenu(false) }} />
      <SideCart open={openSideCart} onClose={() => { setOpenSideCart(false) }} />

    </>
  );
};

export default Navbar;
