'use client';
import {AnimatePresence, motion} from 'framer-motion';
import {CURSOR_EXCLUSION, DispatchCursor} from 'haspr-cursor';
import {Col, Container, Row} from 'react-bootstrap';
import React, {useEffect, useRef, useState} from 'react';
import Button from '@/components/ui/button';
import {CustomLink} from '@/components/ui/customlink';
import {Img} from '@/components/ui/img';
import Link from 'next/link';
import {ScrollToPlugin} from 'gsap/dist/ScrollToPlugin';
import {gsap} from 'gsap';
import parse from 'html-react-parser';
import styled from 'styled-components';
import useContainerOffset from '@/components/hooks/useContainerOffset';
import useDeviceTypeTab from '@/components/hooks/useDeviceTypeTab';
import {usePathname} from 'next/navigation';
// Menu data now comes from global context
import {useShowSetting} from '@/core/context/ShowSettingProvider';
import dcTheme from "@/styles/dc-theme";

gsap.registerPlugin(ScrollToPlugin);

const HeaderContainer = styled.header`
    ${dcTheme.components.header.base}
    ${dcTheme.grid.media.tablet} {
        padding: ${dcTheme.numericScale.spacing["20px"]} ${dcTheme.numericScale.spacing[0]};
    }

    ${dcTheme.grid.media.tablet} {
        min-height: ${dcTheme.numericScale.height.unset};
    }

    &.menu-open {
        transform: ${dcTheme.transforms.none} !important;
        background: ${dcTheme.colors.transparent} !important;
    }

    &.color {
        .menu-text {
            color: ${dcTheme.colors.theme.white.base} !important;
        }

        .menu-lines span {
            background: ${dcTheme.colors.theme.white.base} !important;
        }

        .dc-btn {
            color: ${dcTheme.colors.theme.white.base} !important;

            span {
                color: ${dcTheme.colors.theme.white.base} !important;
            }
        }
    }
`;

const HeaderContent = styled.div`
    ${dcTheme.layouts.fullCentered};
    ${dcTheme.layouts.flexBetween};

    ${dcTheme.grid.media.tablet} {
        // flex-direction: ${dcTheme.flex.rowReverse};
    }
`;

const LogoWrapper = styled.div`
    width: ${dcTheme.numericScale.width["1/3"]};
    ${dcTheme.layouts.flexCenter};
    display: ${dcTheme.display.flex};
    align-items: ${dcTheme.flexAlignment.align.center};
    justify-content: ${dcTheme.flexAlignment.justify.start};
    ${dcTheme.grid.media.mobile} {
    //width: ${dcTheme.numericScale.width["1/2"]};
    // align-items: ${dcTheme.flexAlignment.align.start};
    // justify-content: ${dcTheme.flexAlignment.justify.start};
}
`;

const Logo = styled.div`
    display: ${dcTheme.display.flex};
    align-items: ${dcTheme.flexAlignment.align.center};
    height: ${dcTheme.numericScale.height.full};

    img {
        width: ${dcTheme.numericScale.width["45px"]};
        object-fit: ${dcTheme.numericScale.objectFit.contain};
        filter: brightness(${dcTheme.numericScale.brightness["110"]});
    }

    ${dcTheme.grid.media.mobile} {
        img {
            height: ${dcTheme.numericScale.height["45px"]};
        }
    }
`;

const ContactInfo = styled.div`
    display: ${dcTheme.display.flex};
    align-items: ${dcTheme.flexAlignment.align.center};
    gap: ${dcTheme.numericScale.gap["30px"]};
    width: ${dcTheme.numericScale.width["auto"]};
    justify-content: ${dcTheme.flexAlignment.justify.end};

    ${dcTheme.grid.media.mobile} {
        gap: ${dcTheme.numericScale.gap["15px"]};
        display: ${dcTheme.display.none};
    }
`;

const MenuButton = styled.div`
    display: ${dcTheme.display.flex};
    align-items: ${dcTheme.flexAlignment.align.center};
    justify-content: ${dcTheme.flexAlignment.justify.center};
    gap: ${dcTheme.numericScale.gap["25px"]};
    cursor: ${dcTheme.numericScale.cursor.pointer};
    min-height: ${dcTheme.numericScale.minHeight["60px"]};
    transition: ${dcTheme.numericScale.transitions.mainTransition};

    ${dcTheme.grid.media.tablet} {
        // min-height: ${dcTheme.numericScale.minHeight.unset};
    }

    &:hover {
        transform: ${dcTheme.transforms.translateY['-2px']};
    }

    .menu-lines {
        display: ${dcTheme.display.flex};
        flex-direction: ${dcTheme.flex.col};
        gap: ${dcTheme.numericScale.gap["10px"]};

        span {
            width: ${dcTheme.numericScale.width["45px"]};
            height: ${dcTheme.numericScale.height["1px"]};
            background: ${dcTheme.colors.theme.colorNine.base};
            transition: ${dcTheme.numericScale.transitions.mainTransition};
        }

        &.color {
            span {
                background: ${dcTheme.colors.theme.white.base};
            }
        }
    }

    .close-icon {
        ${dcTheme.components.header.closeIcon};
        &::before,
        &::after {
            ${dcTheme.components.header.closeIconLine};
        }
        &::before {
            transform: ${dcTheme.transforms.rotate['45']};
        }
        &::after {
            transform: ${dcTheme.transforms.rotate['-45']};
        }
    }

    .menu-text {
        color: ${dcTheme.colors.theme.colorNine.base};
        font-weight: ${dcTheme.numericScale.fontWeight.normal};
        font-style: ${dcTheme.numericScale.fontStyles.normal};
        font-size: ${dcTheme.numericScale.fontSize.base};
        line-height: ${dcTheme.numericScale.lineHeight.base};
        letter-spacing: ${dcTheme.numericScale.letterSpacing.tight};
        transition: ${dcTheme.numericScale.transitions.mainTransition};

        &.color {
            color: ${dcTheme.colors.theme.white.base};
        }
    }
`;

const NavigationActions = styled.div`
    display: ${dcTheme.display.inlineFlex};
    align-items: ${dcTheme.flexAlignment.align.center};
    justify-content: ${dcTheme.flexAlignment.justify.end};
    gap: ${dcTheme.numericScale.gap["20px"]};
    width: ${dcTheme.numericScale.width["auto"]};
    ${dcTheme.grid.media.tablet} {
        //gap: ${dcTheme.numericScale.gap["15px"]};
        //width: ${dcTheme.numericScale.width["1/2"]};
        // justify-content: ${dcTheme.flexAlignment.justify.end};
        //align-items: ${dcTheme.flexAlignment.align.end};
    }
`;

const StyledMenuItem = styled.section`
    background-size: ${dcTheme.backgrounds.size.cover} !important;
    background: ${dcTheme.colors.theme.menuBackground} url(${dcTheme.staticUrl.menuBackgroundUrl}) ${dcTheme.backgrounds.position.center};
    background-repeat: ${dcTheme.backgrounds.repeat.noRepeat} !important;
    position: ${dcTheme.position.type.fixed};
    height: ${dcTheme.numericScale.height.full};
    top: ${dcTheme.numericScale.values[0]};
    bottom: ${dcTheme.numericScale.values[0]};
    left: ${dcTheme.numericScale.values[0]};
    width: ${dcTheme.numericScale.width.full};
    z-index: ${dcTheme.numericScale.zIndex["99"]};
    display: ${dcTheme.display.block};
    opacity: ${dcTheme.numericScale.opacity["100"]};

    .fixed-element {
        position: ${dcTheme.position.type.absolute};
        right: ${dcTheme.position.offset["-150"]};
        bottom: ${dcTheme.position.offset["-250"]};
        ${dcTheme.grid.media.mobile} {
            position: ${dcTheme.position.type.absolute};
            right: ${dcTheme.position.offset.custom['-90px']};
            bottom: ${dcTheme.position.offset.custom['-130px']};
            height: ${dcTheme.numericScale.height.custom['500px']};
        }
    }

    .global-image {
        z-index: ${dcTheme.numericScale.zIndex.custom(-1)};
        img {
            mix-blend-mode: $${dcTheme.backgrounds.blendMode.colorDodge};
        }
    }

    .d-flex {
        width: ${dcTheme.numericScale.width.full};
    }

    .menu-items__lists {
        padding: ${dcTheme.numericScale.padding.custom('180px 0 50px 0')};
        ul {
            overflow: ${dcTheme.overflow.hidden};
            width: ${dcTheme.numericScale.width.full};
            padding-left: ${dcTheme.numericScale.values[0]};
            ${dcTheme.grid.media.tablet} {
                padding-left: ${dcTheme.numericScale.padding["15px"]} !important;
            }

            li {
                position: ${dcTheme.position.type.relative};
                display: ${dcTheme.display.flex};
                align-items: ${dcTheme.flexAlignment.align.center};
                margin-bottom: ${dcTheme.numericScale.margin["15px"]};
                ${dcTheme.grid.media.mobile} {
                    margin-bottom: ${dcTheme.numericScale.margin["20px"]};
                }

                span {
                    width: ${dcTheme.numericScale.width["0"]};
                    height: ${dcTheme.numericScale.height.custom['2px']};
                    transform: ${dcTheme.transforms.translateY('-50%')};
                    background-color: ${dcTheme.colors.theme.menuItemBackground};
                    transition: ${dcTheme.numericScale.transitions.mainTransition};
                    margin-right: ${dcTheme.numericScale.margin["10"]};
                }

                a {
                    font-family: ${dcTheme.typography.fonts.primary};
                    font-weight: ${dcTheme.typography.weights.normal};
                    font-style: ${dcTheme.typography.fontStyles.normal};
                    font-size: ${dcTheme.typography.sizes.custom('60px')};
                    line-height: ${dcTheme.typography.lineHeights.base};
                    letter-spacing: ${dcTheme.typography.letterSpacing.tight};
                    color: ${dcTheme.colors.theme.white.base};
                    text-decoration: ${dcTheme.numericScale.textDecoration.none};
                    transition: ${dcTheme.numericScale.transitions.mainTransition};

                    &:after {
                        content: '';
                        width: ${dcTheme.numericScale.values[0]};
                        height: ${dcTheme.numericScale.height.custom('1px')};
                        background: ${dcTheme.colors.menuItem};
                        position: ${dcTheme.position.type.absolute};
                        left: ${dcTheme.numericScale.values[0]};
                        top: ${dcTheme.numericScale.spacing.custom('50%')};
                        transform: ${dcTheme.transforms.translateY('-50%')};
                        transition: ${dcTheme.numericScale.transitions.mainTransition};
                    }

                    ${dcTheme.grid.media.mobile} {
                        font-weight: ${dcTheme.typography.weights.normal};
                        font-style: ${dcTheme.typography.fontStyles.normal};
                        font-size: ${dcTheme.typography.sizes.custom('2.22rem')};
                        line-height: ${dcTheme.typography.lineHeights.base};
                        letter-spacing: ${dcTheme.typography.letterSpacing.tight};
                        &:after {
                            display: ${dcTheme.display.none};
                        }

                        &:hover {
                            a {
                                padding-left: ${dcTheme.numericScale.values[0]};
                                color: ${dcTheme.colors.menuItem};
                            }
                        }
                    }
                }

                &:hover {
                    a {
                        padding-left: ${dcTheme.numericScale.padding["130px"]};
                        color: ${dcTheme.colors.menuItem};

                        &:after {
                            width: ${dcTheme.numericScale.width["80px"]};
                        }

                        ${dcTheme.grid.media.mobile} {
                            padding-left: ${dcTheme.numericScale.values[0]};
                        }
                    }
                }

                &.active {
                    a {
                        padding-left: ${dcTheme.numericScale.padding["130px"]};
                        color: ${dcTheme.colors.menuItem};
                        pointer-events: ${dcTheme.numericScale.cursor.none};

                        &:after {
                            width: ${dcTheme.numericScale.width["80px"]};
                        }

                        ${dcTheme.grid.media.mobile} {
                            padding-left: ${dcTheme.numericScale.values[0]} !important;
                        }
                    }
                }
            }

            .hover-item {
                width: ${dcTheme.numericScale.width.fit};
            }
        }

        ${dcTheme.grid.media.mobile} {
            padding: ${dcTheme.numericScale.padding.custom('120px 0 50px 0')};
        }
    }

    .menu-items__images {
        width: ${dcTheme.numericScale.width.custom('58.33333333%')};

        &__list {
            overflow: ${dcTheme.overflow.hidden};
            height: ${dcTheme.numericScale.height.screen};
            width: ${dcTheme.numericScale.width.full};
            display: ${dcTheme.display.flex};
            gap: ${dcTheme.numericScale.gap["20px"]};
            flex-direction: ${dcTheme.flex.col};

            li {
                position: ${dcTheme.position.type.relative};
                .image-wrapper {
                    position: ${dcTheme.position.type.relative};
                    padding-top: ${dcTheme.imageRatio.menuItemImage};
                    transition: ${dcTheme.numericScale.transitions.mainTransition};
                    opacity: ${dcTheme.numericScale.opacity["30"]};
                    overflow: ${dcTheme.overflow.hidden};

                    /* Masking properties */
                    mask: ${dcTheme.colors.gradients.menuGradient};
                    mask-size:${dcTheme.numericScale.maskSize.custom('0 0')};
                    -webkit-mask-size: ${dcTheme.numericScale.maskSize.custom('0 0')};
                    mask-position: ${dcTheme.backgrounds.position.center};
                    -webkit-mask-position: ${dcTheme.backgrounds.position.center};
                    mask-repeat: ${dcTheme.backgrounds.repeat.noRepeat};
                    -webkit-mask-repeat: ${dcTheme.backgrounds.repeat.noRepeat};
                    transition: ${dcTheme.numericScale.transitions.mainTransition};

                    &.active {
                        opacity: ${dcTheme.numericScale.opacity["100"]};
                        transform: ${dcTheme.transforms.scale(1.05)};
                        mask-size: ${dcTheme.numericScale.maskSize.double};
                        -webkit-mask-size: ${dcTheme.numericScale.maskSize.double};
                    }

                    &:first-child {
                        opacity: ${dcTheme.numericScale.opacity["100"]};
                        mask-size:  ${dcTheme.numericScale.maskSize.double};
                        -webkit-mask-size: ${dcTheme.numericScale.maskSize.double};
                    }

                    /* Hover state for mask reveal */

                    &.mask-reveal {
                        mask-size: ${dcTheme.numericScale.maskSize.custom('180% 180%')};
                        -webkit-mask-size:  ${dcTheme.numericScale.maskSize.custom('180% 180%')};
                        opacity: ${dcTheme.numericScale.opacity["100"]};
                        transform: ${dcTheme.transforms.scale(1.02)};
                    }

                    img {
                        position: ${dcTheme.position.type.absolute};
                        top: ${dcTheme.numericScale.values[0]};
                        left: ${dcTheme.numericScale.values[0]};
                        width: ${dcTheme.numericScale.width.full};
                        height: ${dcTheme.numericScale.height.full};
                        object-fit: ${dcTheme.numericScale.objectFit.cover};
                        will-change: ${dcTheme.numericScale.willChange.transform};
                    }
                }
            }
        }
        .left {
            li {
                transition: ${dcTheme.transforms.none};
            }
        }
        .right {
            transform: ${dcTheme.transforms.rotate(180)};
            img {
                
                transform: ${dcTheme.transforms.rotate(-180)};
                opacity: ${dcTheme.numericScale.opacity["20"]};
            }
        }
        ${dcTheme.grid.media.tablet} {
            display: ${dcTheme.display.none} !important;
        }
    }
`;

// Motion wrapper for the menu overlay
const MotionMenu = motion(StyledMenuItem);

const Header = () => {
    //` The Cursor Action Dispatcher initialized
    const dispatch = DispatchCursor();
    const headerRef = useRef(null);
    const location = usePathname();
    const initialLenis = useShowSetting();

    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [scrollPosition, setScrollPosition] = useState(0);

    const offset = useContainerOffset('.container');
    const routers = usePathname();
    const isTab = useDeviceTypeTab();

    // Enhanced toggle menu with scroll management
    const toggleMenu = () => {
        if (!isMenuOpen) {
            // Opening menu - disable scroll
            setScrollPosition(window.pageYOffset);
            document.body.style.width = dcTheme.numericScale.width.full;
            document.body.style.overflowY = dcTheme.overflow.hidden;

            // Prevent scroll class changes during menu
            window.preventScrollClassChange = true;

            setIsMenuOpen(true);
        } else {
            // Closing menu - enable scrolls
            document.body.style.position = '';
            document.body.style.top = '';
            document.body.style.width = '';
            document.body.style.overflowY = '';

            // Restore scroll position
            window.scrollTo(0, scrollPosition);

            // Re-enable scroll class changes after a delay
            setTimeout(() => {
                window.preventScrollClassChange = false;
            }, 100);

            setIsMenuOpen(false);
        }
    };

    // Framer Motion variants: masked reveal + smooth content stagger
    const overlayVariants = {
        initial: {clipPath: dcTheme.numericScale.clipPath.insetBottomHidden, opacity: dcTheme.numericScale.opacity["70"]},
        animate: {
            clipPath: dcTheme.numericScale.clipPath.inset0,
            opacity: 1,
            transition: {duration: dcTheme.numericScale.opacity["80"], ease: dcTheme.numericScale.transitions.defaultEase},
        },
        exit: {
            clipPath: dcTheme.numericScale.clipPath.insetBottomHidden,
            opacity: dcTheme.numericScale.opacity["60"],
            transition: {
                duration: dcTheme.numericScale.duration["75"],
                ease: dcTheme.numericScale.transitions.defaultEase,
                onComplete: () => {
                    // Ensure scroll is re-enabled after exit animation
                    document.body.style.position = '';
                    document.body.style.top = '';
                    document.body.style.width = '';
                    document.body.style.overflowY = '';
                    window.preventScrollClassChange = false;
                },
            },
        },
    };

    const contentContainerVariants = {
        initial: {opacity: dcTheme.numericScale.opacity["80"], y: dcTheme.numericScale.spacing.custom(20)},
        animate: {
            opacity: dcTheme.numericScale.opacity["100"],
            y: 0,
            transition: {
                duration: dcTheme.numericScale.opacity["60"],
                delay: 0.12,
                ease: dcTheme.numericScale.transitions.defaultEase,
                staggerChildren: 0.06,
                delayChildren: 0.18,
            },
        },
        exit: {
            opacity: 0,
            y: 10,
            transition: {duration: 0.35, ease: dcTheme.numericScale.transitions.defaultEase},
        },
    };

    const listItemVariants = {
        initial: {opacity: 0, y: 16},
        animate: {
            opacity: 1,
            y: 0,
            transition: {duration: 0.5, ease: dcTheme.numericScale.transitions.defaultEase},
        },
        exit: {
            opacity: 0,
            y: 8,
            transition: {duration: 0.5, ease: dcTheme.numericScale.transitions.defaultEase},
        },
    };

    useEffect(() => {
        const header = headerRef.current;
        if (!header) return;
        gsap.fromTo(
            header,
            {y: -100, opacity: 0},
            {
                y: 0,
                opacity: 1,
                duration: 0.6,
                ease: dcTheme.numericScale.transitions.defaultEase,
                delay: 0.2,
            },
        );
    }, []);

    // Automatically close on route change
    useEffect(() => {
        if (isMenuOpen) {
            // Re-enable scroll when route changes
            document.body.style.position = '';
            document.body.style.top = '';
            document.body.style.width = '';
            document.body.style.overflowY = '';
            window.preventScrollClassChange = false;
        }
        setIsMenuOpen(false);
    }, [routers]);

    // Cleanup on unmount
    useEffect(() => {
        return () => {
            // Ensure scroll is always re-enabled on unmount
            document.body.style.position = '';
            document.body.style.top = '';
            document.body.style.width = '';
            document.body.style.overflowY = '';
            window.preventScrollClassChange = false;
        };
    }, []);

    // Prevent body scroll when menu is open (additional safety)
    useEffect(() => {
        if (isMenuOpen) {
            const handleWheel = e => e.preventDefault();
            const handleTouchMove = e => e.preventDefault();

            document.addEventListener('wheel', handleWheel, {passive: false});
            document.addEventListener('touchmove', handleTouchMove, {
                passive: false,
            });

            return () => {
                document.removeEventListener('wheel', handleWheel);
                document.removeEventListener('touchmove', handleTouchMove);
            };
        }
    }, [isMenuOpen]);

    const {getMenu} = useShowSetting();
    const {getSettings} = useShowSetting();
    // Prefer menu2 for header if available, fallback to menu1
    const topMenu = React.useMemo(
        () => getMenu?.menu1 || getMenu?.menu2 || null,
        [getMenu],
    );
    const topMenuHeader = React.useMemo(
        () => getMenu?.menu3 || getMenu?.menu2 || null,
        [getMenu],
    );
    const menuItems = React.useMemo(() => {
        const items = topMenu?.data ?? [];
        if (!Array.isArray(items)) return [];
        // Sort by numeric sort_order ascending; fallback to 0
        return [...items].sort((a, b) => {
            const av = a?.sort_order ?? a?.sortOrder;
            const bv = b?.sort_order ?? b?.sortOrder;
            const an =
                typeof av === 'number'
                    ? av
                    : parseInt((av ?? '').toString(), 10);
            const bn =
                typeof bv === 'number'
                    ? bv
                    : parseInt((bv ?? '').toString(), 10);
            const aNum = Number.isFinite(an) ? an : Number.POSITIVE_INFINITY;
            const bNum = Number.isFinite(bn) ? bn : Number.POSITIVE_INFINITY;
            return aNum - bNum;
        });
    }, [topMenu]);
    const menuItemsTop = React.useMemo(() => {
        const items = topMenuHeader?.data ?? [];
        if (!Array.isArray(items)) return [];
        // Sort by numeric sort_order ascending; fallback to 0
        return [...items].sort((a, b) => {
            const av = a?.sort_order ?? a?.sortOrder;
            const bv = b?.sort_order ?? b?.sortOrder;
            const an =
                typeof av === 'number'
                    ? av
                    : parseInt((av ?? '').toString(), 10);
            const bn =
                typeof bv === 'number'
                    ? bv
                    : parseInt((bv ?? '').toString(), 10);
            const aNum = Number.isFinite(an) ? an : Number.POSITIVE_INFINITY;
            const bNum = Number.isFinite(bn) ? bn : Number.POSITIVE_INFINITY;
            return aNum - bNum;
        });
    }, [topMenuHeader]);

    // Enhanced hover functionality with mask effects
    const setupHoverFunctionality = React.useCallback(() => {
        const getLis = document.querySelectorAll('.hover-item');
        const getimgs = document.querySelectorAll('.left li');
        const rightWrapper = document.querySelectorAll('.right');
        const getRightImg = document.querySelectorAll('.right li');
        const wrapper = document.querySelector('.left');
        const imageWrappers = document.querySelectorAll('.image-wrapper');

        if (!getLis.length || !imageWrappers.length) return;

        const handleHover = i => {
            // Scroll to the corresponding image
            if (wrapper) {
                gsap.to(wrapper, {
                    duration: 0.8,
                    scrollTo: {
                        y: getimgs[i]?.offsetTop - 130,
                        autoKill: true,
                    },
                    ease: dcTheme.numericScale.transitions.defaultEase,
                });
            }

            if (rightWrapper.length > 0) {
                gsap.to(rightWrapper, {
                    duration: 0.8,
                    scrollTo: {
                        y: getRightImg[i + 1]?.offsetTop,
                        autoKill: true,
                    },
                    ease: dcTheme.numericScale.transitions.defaultEase,
                });
            }

            // Update image with mask reveal effect
            imageWrappers.forEach((wrap, index) => {
                // Remove all mask classes first
                wrap.classList.remove('active', 'mask-reveal');

                if (index === i) {
                    // Add mask reveal effect for hovered item
                    wrap.classList.add('mask-reveal');
                    gsap.to(wrap, {
                        duration: 0.4,
                        opacity: 1,
                        scale: 1.05,
                        ease: dcTheme.numericScale.transitions.defaultEase,
                    });
                } else {
                    // Reset other items
                    gsap.to(wrap, {
                        duration: 0.4,
                        opacity: 1,
                        scale: 1,
                        ease: dcTheme.numericScale.transitions.defaultEase,
                    });
                }
            });
        };

        const handleMouseLeave = () => {
            // Reset all images and masks when leaving menu items
            imageWrappers.forEach((wrap, index) => {
                wrap.classList.remove('mask-reveal');

                if (index === 0) {
                    // First item stays active
                    wrap.classList.add('active');
                    gsap.to(wrap, {
                        duration: 0.4,
                        opacity: 1,
                        scale: 1,
                        ease: dcTheme.numericScale.transitions.defaultEase,
                    });
                } else {
                    gsap.to(wrap, {
                        duration: 0.4,
                        opacity: 0.3,
                        scale: 1,
                        ease: dcTheme.numericScale.transitions.defaultEase,
                    });
                }
            });
        };

        // Bind listeners once per element to avoid duplicates
        const newLis = document.querySelectorAll('.hover-item');
        newLis.forEach((el, i) => {
            if (el.dataset.bound === '1') return;
            const anchor = el.querySelector('a');
            if (anchor) {
                el.addEventListener('mouseover', () => handleHover(i));
                el.addEventListener('mouseleave', handleMouseLeave);
                el.dataset.bound = '1';
            }
        });
    }, []);

    // Setup hover functionality when menu opens (delay to ensure DOM is ready)
    useEffect(() => {
        if (isMenuOpen) {
            const timer = setTimeout(() => {
                setupHoverFunctionality();
            }, 100);
            return () => clearTimeout(timer);
        }
    }, [isMenuOpen, setupHoverFunctionality]);

    useEffect(() => {
        const body = document.body;
        const scrollUp = 'scroll-up';
        const scrollDown = 'scroll-down';

        let lastScroll = 0;
        let ticking = false;
        const howMuchScroll = window.innerWidth < 991 ? 80 : 250;

        const onScroll = () => {
            // Check if scroll class changes should be prevented
            if (window.preventScrollClassChange) {
                return;
            }

            if (!ticking) {
                requestAnimationFrame(() => {
                    const currentScroll = window.pageYOffset;

                    if (currentScroll <= howMuchScroll) {
                        body.classList.remove(scrollUp, scrollDown);
                        lastScroll = currentScroll;
                        ticking = false;
                        return;
                    }

                    if (currentScroll > lastScroll) {
                        body.classList.add(scrollDown);
                        body.classList.remove(scrollUp);
                    } else {
                        body.classList.add(scrollUp);
                        body.classList.remove(scrollDown);
                    }

                    lastScroll = currentScroll;
                    ticking = false;
                });
                ticking = true;
            }
        };

        window.addEventListener('scroll', onScroll, {passive: true});

        return () => {
            window.removeEventListener('scroll', onScroll);
            body.classList.remove(scrollUp, scrollDown);
        };
    }, [location]);

    return (
        <>
            <HeaderContainer
                ref={headerRef}
                className={`menu-desktop site-header ${isMenuOpen ? 'menu-open' : ''}`}>
                <Container>
                    <Row>
                        <Col>
                            <HeaderContent>
                                <LogoWrapper>
                                    {!isMenuOpen && (
                                      <Logo>
                                          <Link href="/">
                                              {getSettings?.logo_light && (
                                                <img
                                                  src={
                                                    process.env
                                                      .NEXT_PUBLIC_API_URL +
                                                    '/admin/' +
                                                    getSettings?.logo_light
                                                  }
                                                  alt="Palmal Group of Industries Ltd - Powering Business Globally"
                                                />
                                              )}
                                          </Link>
                                      </Logo>
                                    )}
                                </LogoWrapper>
                                <div className="d-flex justify-content-end gap-5" style={{
                                    minWidth: '70%'
                                }}>
                                    <ContactInfo>
                                        {!isMenuOpen && !isTab ? (
                                          <>
                                              {menuItemsTop &&
                                                menuItemsTop.length > 0 && (
                                                  <>
                                                      {menuItemsTop
                                                        .slice(0, -1)
                                                        .map((item, i) => (
                                                          <Button
                                                            className={
                                                                'first-button'
                                                            }
                                                            key={
                                                              item?.id ??
                                                              i
                                                            }
                                                            onMouseEnter={() =>
                                                              CURSOR_EXCLUSION(
                                                                dispatch,
                                                                'START',
                                                                'LARGE',
                                                              )
                                                            }
                                                            onMouseLeave={() =>
                                                              CURSOR_EXCLUSION(
                                                                dispatch,
                                                                'END',
                                                              )
                                                            }
                                                            src={
                                                                item?.item_url
                                                            }
                                                            text={
                                                                item?.item_title
                                                            }
                                                            color={
                                                                location ===
                                                                '/'
                                                                  ? dcTheme
                                                                    .colors
                                                                    .lightBlack
                                                                  : dcTheme
                                                                    .colors
                                                                    .white
                                                            }
                                                            background={
                                                                dcTheme
                                                                  .colors
                                                                  .transparent
                                                            }
                                                            width={
                                                                'auto'
                                                            }
                                                          />
                                                        ))}
                                                      <Button
                                                        onMouseEnter={() =>
                                                          CURSOR_EXCLUSION(
                                                            dispatch,
                                                            'START',
                                                            'LARGE',
                                                          )
                                                        }
                                                        onMouseLeave={() =>
                                                          CURSOR_EXCLUSION(
                                                            dispatch,
                                                            'END',
                                                          )
                                                        }
                                                        src={'/contact-us'}
                                                        color={
                                                            dcTheme.colors
                                                              .white
                                                        }
                                                        text={
                                                            'Get In Touch'
                                                        }
                                                      />
                                                  </>
                                                )}
                                          </>
                                        ) : null}
                                    </ContactInfo>
                                    <NavigationActions>
                                        <MenuButton
                                          role="button"
                                          aria-expanded={isMenuOpen}
                                          aria-label={
                                              isMenuOpen
                                                ? 'Close menu'
                                                : 'Open menu'
                                          }
                                          onClick={toggleMenu}
                                          onMouseEnter={() =>
                                            CURSOR_EXCLUSION(
                                              dispatch,
                                              'START',
                                              'LARGE',
                                            )
                                          }
                                          onMouseLeave={() =>
                                            CURSOR_EXCLUSION(dispatch, 'END')
                                          }
                                          className={'hamburger-menu-for-click'}>
                                            {isMenuOpen ? (
                                              ''
                                            ) : (
                                              <span
                                                className={`menu-text ${location === '/' ? '' : 'color'}`}>
												{isMenuOpen ? '' : 'MENU'}
											</span>
                                            )}
                                            
                                            {isMenuOpen ? (
                                              <div className="d-flex align-items-center gap-2">
                                                  <svg
                                                    width="26"
                                                    height="26"
                                                    viewBox="0 0 26 26"
                                                    fill="none"
                                                    xmlns="http://www.w3.org/2000/svg">
                                                      <path
                                                        d="M24.5203 4.48584C24.7234 4.28991 24.8854 4.0555 24.9969 3.7963C25.1083 3.53709 25.1671 3.25828 25.1697 2.97612C25.1723 2.69397 25.1186 2.41413 25.0119 2.15292C24.9052 1.89172 24.7475 1.65438 24.5481 1.45477C24.3487 1.25515 24.1115 1.09725 23.8504 0.990285C23.5893 0.883315 23.3095 0.829417 23.0273 0.831735C22.7452 0.834053 22.4663 0.89254 22.207 1.00379C21.9477 1.11503 21.7131 1.27681 21.517 1.47967L13 9.99384L4.48583 1.47967C4.29128 1.27089 4.05668 1.10343 3.79602 0.987291C3.53535 0.871147 3.25396 0.808694 2.96864 0.80366C2.68331 0.798626 2.3999 0.851113 2.1353 0.957989C1.8707 1.06487 1.63034 1.22394 1.42855 1.42573C1.22676 1.62751 1.06769 1.86788 0.960812 2.13248C0.853936 2.39708 0.801449 2.68049 0.806483 2.96582C0.811517 3.25114 0.87397 3.53253 0.990114 3.79319C1.10626 4.05386 1.27371 4.28846 1.48249 4.483L9.99099 13L1.47683 21.5142C1.10147 21.917 0.897117 22.4498 0.90683 23.0003C0.916543 23.5508 1.13956 24.0761 1.5289 24.4654C1.91824 24.8548 2.44349 25.0778 2.99401 25.0875C3.54453 25.0972 4.07733 24.8929 4.48016 24.5175L13 16.0033L21.5142 24.5203C21.917 24.8957 22.4498 25.1 23.0003 25.0903C23.5508 25.0806 24.0761 24.8576 24.4654 24.4683C24.8548 24.0789 25.0778 23.5537 25.0875 23.0031C25.0972 22.4526 24.8929 21.9198 24.5175 21.517L16.009 13L24.5203 4.48584Z"
                                                        fill="white"
                                                      />
                                                  </svg>
                                              </div>
                                            ) : (
                                              <div
                                                className={`menu-lines ${location === '/' ? '' : 'color'}`}>
                                                  <span></span>
                                                  <span></span>
                                                  <span></span>
                                              </div>
                                            )}
                                        </MenuButton>
                                    </NavigationActions>
                                </div>
                            </HeaderContent>
                        </Col>
                    </Row>
                </Container>
            </HeaderContainer>
            <AnimatePresence>
                {isMenuOpen && (
                    <MotionMenu
                        variants={overlayVariants}
                        initial="initial"
                        animate="animate"
                        exit="exit"
                        className={'menu-items'}
                        style={{
                            pointerEvents: isMenuOpen ? 'auto' : 'none',
                            willChange: 'clip-path, opacity, transform',
                        }}>
                        {isTab && (
                            <img
                                className={'fixed-element'}
                                src="/images/static/menu-mobile-vector.png"
                                alt=""
                            />
                        )}
                        <motion.div
                            className="d-flex"
                            variants={contentContainerVariants}
                            initial="initial"
                            animate="animate"
                            exit="exit">
                            <motion.div
                                className="menu-items__lists col-sm-5"
                                style={{paddingLeft: offset + 15 + 'px'}}>
                                <div>
                                    <motion.ul
                                        variants={contentContainerVariants}
                                        initial="initial"
                                        animate="animate"
                                        exit="exit">
                                        {menuItems &&
                                            menuItems.length > 0 &&
                                            menuItems.map((item, i) => {
                                                return (
                                                    <motion.li
                                                        variants={
                                                            listItemVariants
                                                        }
                                                        key={
                                                            item?.id ??
                                                            item?.item_url ??
                                                            i
                                                        }
                                                        className={`hover-item ${routers === item?.item_url ? 'active' : ''}`}>
                                                        <CustomLink
                                                            onMouseEnter={() =>
                                                                CURSOR_EXCLUSION(
                                                                    dispatch,
                                                                    'START',
                                                                    'LARGE',
                                                                )
                                                            }
                                                            onMouseLeave={() =>
                                                                CURSOR_EXCLUSION(
                                                                    dispatch,
                                                                    'END',
                                                                )
                                                            }
                                                            toggleMenu={
                                                                toggleMenu
                                                            }
                                                            href={
                                                                item?.item_url
                                                            }>
                                                            {parse(
                                                                item?.item_title,
                                                            )}
                                                        </CustomLink>
                                                    </motion.li>
                                                );
                                            })}
                                    </motion.ul>
                                </div>
                            </motion.div>

                            <motion.div
                                className="menu-items__images d-flex"
                                style={{
                                    paddingLeft: offset + 150 + 'px',
                                    paddingRight: offset + 'px',
                                }}>
                                <motion.ul
                                    className="menu-items__images__list left"
                                    variants={contentContainerVariants}
                                    initial="initial"
                                    animate="animate"
                                    exit="exit">
                                    {menuItems &&
                                        menuItems.length > 0 &&
                                        menuItems.map((item, i) => {
                                            return (
                                                <motion.li
                                                    key={
                                                        item?.id ??
                                                        item?.item_url ??
                                                        i
                                                    }
                                                    className={`${routers === item?.item_url ? 'active' : ''}`}
                                                    variants={listItemVariants}>
                                                    <motion.div
                                                        className={`image-wrapper ${i === 0 ? 'active' : ''}`}
                                                        initial={{
                                                            opacity: 0.3,
                                                            scale: 1.02,
                                                        }}
                                                        animate={{
                                                            opacity: 1,
                                                            scale: 1,
                                                            transition: {
                                                                duration: 0.5,
                                                                ease: [
                                                                    0.83, 0,
                                                                    0.17, 1,
                                                                ],
                                                            },
                                                        }}
                                                        exit={{
                                                            opacity: 0.3,
                                                            scale: 1.01,
                                                            transition: {
                                                                duration: 0.3,
                                                            },
                                                        }}>
                                                        <Img
                                                            src={`${item?.item_icon}`}
                                                            alt={(
                                                                item?.item_title ||
                                                                ''
                                                            ).replace(
                                                                /<[^>]*>/g,
                                                                '',
                                                            )}
                                                        />
                                                    </motion.div>
                                                </motion.li>
                                            );
                                        })}
                                </motion.ul>
                            </motion.div>
                        </motion.div>
                    </MotionMenu>
                )}
            </AnimatePresence>
        </>
    );
};

export default Header;
