"use client"

import {useEffect, useState} from "react";
import {push as Menu} from "react-burger-menu";
import Image from "next/image";
import data from "@/app/data/categories.json"
 import {cloneDeep} from "lodash";

export const BurgerMenu = () => {

    const [currentMenuSelected, setCurrentMenuSelected] = useState([])
    const [currentMenuIdSelected, setCurrentMenuIdSelected] = useState("")
    const [lastScrollTop, setLastScrollTop] = useState(0)

    useEffect(() => {
        if (currentMenuIdSelected === "") {
            setCurrentMenuSelected(cloneDeep(data.categories))
        } else {
            let arrSubMenu = data.categories.filter(x => x.id === currentMenuIdSelected);
            if (arrSubMenu.length === 0) setCurrentMenuSelected([])
            setCurrentMenuSelected(cloneDeep(arrSubMenu[0].sub_category))
        }
    }, [currentMenuIdSelected])


    const onClickMenuHandler = (e, menuId) => {
        let arrSubMenu = data.categories.filter(x => x.id === menuId)[0];

        if (currentMenuIdSelected.length === 0 && arrSubMenu.sub_category.length>0) {
            e.preventDefault()
            setCurrentMenuIdSelected(menuId)
            // return e.preventDefault()
        }
    }

    useEffect(() => {
        let lastScrollTop = 0; // موقعیت آخرین اسکرول

        window.addEventListener("scroll", function() {
            let currentScroll = window.scrollY || document.documentElement.scrollTop;

            if (currentScroll > lastScrollTop) {
                console.log(currentScroll)
                console.log("Scroll Down");  // کاربر به پایین اسکرول کرده است
            } else {
                console.log("Scroll Up");    // کاربر به بالا اسکرول کرده است
            }

            lastScrollTop = currentScroll <= 0 ? 0 : currentScroll; // جلوگیری از منفی شدن
            setLastScrollTop(lastScrollTop)
        });

    }, []);
    return (
        <div id="outer-container" className="burger-menu">
            <Menu pageWrapId={"pages-container"} outerContainerId={"outer-container"}>
                <ul>
                    {currentMenuIdSelected.length > 0 &&
                        <li><a onClick={() => setCurrentMenuIdSelected("")} className="bm-item"
                        ><i className="fa-regular fa-arrow-left"></i> Back</a></li>}

                    {currentMenuSelected.map(x => <li key={x.id}>
                        <a onClick={(e) => onClickMenuHandler(e, x.id)} className="bm-item"
                              href={x.slug}>{x.name}</a>
                    </li>)}
                </ul>

            </Menu>

          <a href={"/"}>  <Image style={{marginLeft: '22px',height:"90px"}} src="/img/svg/TranTech Logo1.svg" alt="TranTech logo" width={230} height={50}/></a>

            <span></span>
        </div>
    );
};
