"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = SideBarDesktop;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const show_sidebar_1 = tslib_1.__importDefault(require("../assets/icon-v3/show-sidebar"));
const constant_1 = require("../constant");
const helper_1 = require("../helper");
const use_save_menu_config_1 = tslib_1.__importDefault(require("../hooks/use-save-menu-config"));
const nav_item_1 = tslib_1.__importDefault(require("./nav-item"));
const other_menu_1 = tslib_1.__importDefault(require("./other-menu"));
const set_setting_site_1 = tslib_1.__importDefault(require("../../Func/setting-site/set-setting-site"));
const get_setting_site_1 = tslib_1.__importDefault(require("../../Func/setting-site/get-setting-site"));
const types_1 = require("../../types");
function SideBarDesktop({ currentMenuCode, dataInitMain, isActivityHistory, isSettings, navigation, onChangeSideBarType, setShowSubMenu, showSubMenu, sideBarType, userId, }) {
    const keyPinnedMenu = `menu_pinned_${userId}`;
    const keySavedTheme = `saved_theme_${userId}`;
    const [menu, setMenu] = (0, react_1.useState)({
        pined: [],
        noPined: [],
    });
    const { getSavedMenuConfig, handleSaveMenuConfig } = (0, use_save_menu_config_1.default)();
    const [totalItem, setTotalItem] = (0, react_1.useState)(0);
    const [showOtherMenu, setShowOtherMenu] = (0, react_1.useState)(false);
    const [isChange, setIsChange] = (0, react_1.useState)(false);
    const [delayHover, setDelayHover] = (0, react_1.useState)(false);
    const isIconOnly = sideBarType === constant_1.SIDEBAR_TYPE.ONLY_ICON;
    const isIconWithLabelHorizontal = sideBarType === constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL;
    const isIconWithLabelVertical = sideBarType === constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_VERTICAL;
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [theme, setTheme] = (0, react_1.useState)();
    let visibleMenus = menu.pined.slice(0, totalItem);
    const isActiveMenuVisible = visibleMenus.some((item) => item.code === currentMenuCode);
    // Nếu active menu chưa được hiển thị ra ngoài thì luôn đưa nó xuống cuối
    if (!isActiveMenuVisible) {
        const activeMenu = [...menu.pined, ...menu.noPined].find((item) => item.code === currentMenuCode && isHavePerNavByCode(item.code));
        visibleMenus = menu.pined.slice(0, totalItem - 1);
        if (activeMenu && activeMenu.code !== constant_1.MENU_CODE.DASHBOARD) {
            visibleMenus.push(activeMenu);
        }
    }
    const removeDuplicateMenu = (arr) => {
        if (!arr)
            return [];
        const seen = new Set();
        return arr.filter((item) => {
            if (seen.has(item.code))
                return false;
            seen.add(item.code);
            return true;
        });
    };
    const savePinedMenu = async (data) => {
        const { pined: pinedMenu } = data;
        await handleSaveMenuConfig({
            key: keyPinnedMenu,
            data: {
                pinedMenu,
            },
        });
    };
    const handleChangePined = (selectedNav) => {
        const { noPined: currNoPined, pined: currPined } = menu;
        let nextPined, nextNoPined;
        if (selectedNav.isPined) {
            nextPined = currPined.filter((nav) => nav.code !== selectedNav.code);
            nextNoPined = [{ ...selectedNav, isPined: false }, ...currNoPined];
        }
        else {
            nextPined = [{ ...selectedNav, isPined: true }, ...currPined];
            nextNoPined = currNoPined.filter((nav) => nav.code !== selectedNav.code);
        }
        setMenu({
            pined: nextPined,
            noPined: nextNoPined,
        });
        setIsChange(!isChange);
    };
    const onOrder = (newArray) => {
        const orderMap = newArray.map((item) => item.code);
        const sortedPined = [...menu.pined].sort((a, b) => {
            const indexA = orderMap.indexOf(a.code);
            const indexB = orderMap.indexOf(b.code);
            // Nếu không tìm thấy trong mảng 1 => để xuống cuối
            if (indexA === -1 && indexB === -1)
                return 0;
            if (indexA === -1)
                return 1;
            if (indexB === -1)
                return -1;
            return indexA - indexB;
        });
        const newMenu = {
            noPined: menu.noPined,
            pined: sortedPined,
        };
        setMenu(newMenu);
        setIsChange(!isChange);
    };
    function isHavePerNavByCode(code) {
        return dataInitMain.perCode.includes(code);
    }
    async function getSavedPinedMenu() {
        try {
            const { pinedMenu } = await getSavedMenuConfig({ key: keyPinnedMenu });
            return pinedMenu || [];
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    async function getValidSavePinedMenu() {
        try {
            const pinedSavedArr = await getSavedPinedMenu();
            // lấy những menu được lưu và menu đó phải được phân quyền cho user hiện tại
            const validPined = (pinedSavedArr || []).filter((item) => isHavePerNavByCode(item.code));
            return validPined || [];
        }
        catch (e) {
            console.error(e);
            return [];
        }
    }
    async function getInitPined() {
        const validPinedSaveArr = await getValidSavePinedMenu();
        const currMenu = navigation.find((item) => item.code === currentMenuCode && isHavePerNavByCode(item.code));
        const pined = [];
        const noPined = [];
        if (validPinedSaveArr.length > 0) {
            validPinedSaveArr.forEach((pinedSave) => {
                const found = navigation.find((item) => item.code === pinedSave.code);
                if (found && found.code) {
                    pined.push({ ...found, isPined: true });
                }
            });
            const rest = navigation
                .filter((nav) => !pined.some((item) => item.code === nav.code) && nav.code !== constant_1.MENU_CODE.SETTING_SITE)
                .map((item) => ({
                ...item,
                disabled: !isHavePerNavByCode(item.code),
            }));
            noPined.push(...rest);
        }
        else {
            navigation.forEach((nav) => {
                if (nav.code === (currMenu === null || currMenu === void 0 ? void 0 : currMenu.code) || nav.code === constant_1.MENU_CODE.SETTING_SITE) {
                    return;
                }
                const isHavePer = isHavePerNavByCode(nav.code);
                if (isHavePer) {
                    pined.push({
                        ...nav,
                        isPined: true,
                        disabled: !isHavePer,
                    });
                }
                else {
                    noPined.push({
                        ...nav,
                        disabled: !isHavePer,
                    });
                }
            });
            if (currMenu) {
                pined.unshift({ ...currMenu, isPined: true });
            }
            savePinedMenu({
                pined,
                noPined,
            });
        }
        setMenu({
            pined,
            noPined,
        });
    }
    const caculateVisibleMenu = () => {
        var _a;
        let itemHeight = 60;
        if (isIconWithLabelHorizontal || isIconOnly) {
            itemHeight = 42;
        }
        const windowHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0 - 66; // 66 là các phần margin và padding của sidebar
        const nextTotalItem = Math.ceil(windowHeight / itemHeight) - (showSubMenu ? 5 : 6); // 6,7 là số item hiện tại đã auto hiển thị
        if (nextTotalItem !== totalItem) {
            setTotalItem(nextTotalItem);
        }
    };
    const onChangeTheme = async (selectedTheme) => {
        try {
            await (0, set_setting_site_1.default)({
                key: keySavedTheme,
                data: {
                    theme: selectedTheme.code,
                },
            });
            localStorage.setItem(keySavedTheme, JSON.stringify(selectedTheme));
            setTheme(selectedTheme);
        }
        catch (e) {
            console.error(e);
        }
    };
    (0, react_1.useEffect)(() => {
        if (!dataInitMain.perCode || navigation.length === 0 || !userId)
            return;
        getInitPined();
    }, [dataInitMain.perCode, navigation.length]);
    (0, react_1.useEffect)(() => {
        var _a;
        // Log ngay khi component mount
        caculateVisibleMenu();
        (_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.addEventListener('resize', caculateVisibleMenu);
        return () => {
            var _a;
            (_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.removeEventListener('resize', caculateVisibleMenu);
        };
    }, [showSubMenu]);
    (0, react_1.useEffect)(() => {
        caculateVisibleMenu();
    }, [sideBarType]);
    (0, react_1.useEffect)(() => {
        if (menu.pined.length === 0)
            return;
        const timerId = setTimeout(() => {
            savePinedMenu(menu);
        }, 500);
        return () => clearTimeout(timerId);
    }, [isChange]);
    (0, react_1.useEffect)(() => {
        if (!showSubMenu)
            return; // chỉ chạy khi showSubMenu = true
        setDelayHover(true); // khóa hover
        const timerId = setTimeout(() => {
            setDelayHover(false);
        }, 1000);
        return () => {
            clearTimeout(timerId);
        };
    }, [showSubMenu]);
    (0, react_1.useEffect)(() => {
        const getTheme = async () => {
            try {
                const themeSetting = await (0, get_setting_site_1.default)({
                    key: keySavedTheme,
                });
                const defaultThemeCode = isIconWithLabelHorizontal ? constant_1.THEME_CODE.PINK : constant_1.THEME_CODE.BLACK;
                const defaultTheme = constant_1.themes.find((currTheme) => currTheme.code === defaultThemeCode);
                const savedTheme = constant_1.themes.find((i) => i.code === (themeSetting === null || themeSetting === void 0 ? void 0 : themeSetting.theme)) || defaultTheme;
                localStorage.setItem(keySavedTheme, JSON.stringify(savedTheme));
                setTheme(savedTheme);
            }
            catch (e) {
                console.error(e);
            }
            finally {
                setLoading(false);
            }
        };
        getTheme();
    }, []);
    (0, react_1.useEffect)(() => {
        if (navigation.length === 0 || menu.pined.length === 0)
            return;
        setMenu((prev) => {
            const syncCounts = (items, source) => items.map((item) => {
                var _a;
                const fresh = source.find((n) => n.code === item.code);
                if (!fresh)
                    return item;
                return {
                    ...item,
                    requiredActionCount: fresh.requiredActionCount,
                    child: (_a = fresh.child) !== null && _a !== void 0 ? _a : item.child,
                };
            });
            return {
                pined: syncCounts(prev.pined, navigation),
                noPined: syncCounts(prev.noPined, navigation),
            };
        });
    }, [navigation]);
    return (react_1.default.createElement(react_1.default.Fragment, null, loading ? (react_1.default.createElement("div", { "aria-hidden": true, className: (0, types_1.classNames)('relative z-[40] hidden flex-col items-center lg:inset-y-0 lg:flex', showSubMenu ? 'pt-3' : 'rounded-xl pt-[3.2rem]', isIconOnly ? 'w-[3.25rem]' : '', isIconWithLabelHorizontal ? 'w-[12.5rem]' : '', isIconWithLabelHorizontal && showSubMenu ? 'rounded-l-xl' : '', isIconWithLabelVertical ? 'w-14' : '') })) : (react_1.default.createElement("div", { "aria-hidden": true, className: (0, types_1.classNames)('relative z-[40] hidden w-14 flex-col items-center lg:inset-y-0 lg:flex', showSubMenu ? 'pt-3' : 'rounded-xl pt-[3.2rem]', isIconOnly ? 'w-[3.25rem]' : '', isIconWithLabelHorizontal ? 'w-[10.4rem] transition-all duration-150' : '', isIconWithLabelHorizontal && showSubMenu ? 'rounded-l-xl' : 'rounded-xl'), style: {
            background: !isIconWithLabelHorizontal
                ? `linear-gradient(to bottom, ${theme === null || theme === void 0 ? void 0 : theme.bgColorFrom} -6.91%, ${theme === null || theme === void 0 ? void 0 : theme.bgColorTo} 99.96%)`
                : '',
        } },
        react_1.default.createElement("button", { className: (0, types_1.classNames)('group absolute top-4 mb-4 flex items-center gap-x-2.5 px-3 pb-4 ', showSubMenu ? 'hidden' : '', isIconWithLabelHorizontal
                ? 'ml-1.5 w-full text-gray-700 hover:text-gray-900'
                : `${theme === null || theme === void 0 ? void 0 : theme.sideBarColorDefault} hover:text-white`), onClick: () => setShowSubMenu(true), type: 'button' },
            isIconWithLabelHorizontal && (react_1.default.createElement("div", { className: 'absolute left-0 right-0 h-[1.75rem] rounded-lg bg-white opacity-0 transition-opacity group-hover:opacity-100' })),
            react_1.default.createElement("div", { className: (0, types_1.classNames)('absolute bottom-0   h-[0.5px]', isIconWithLabelHorizontal ? 'left-2 right-3 bg-[#CCCCCC]' : 'left-3 right-3 bg-white opacity-40') }),
            react_1.default.createElement(show_sidebar_1.default, null),
            isIconWithLabelHorizontal && (react_1.default.createElement("p", { className: 'absolute -top-[0.2rem] left-[2.25rem] text-xxs' }, "M\u1EDF thanh b\u00EAn"))),
        react_1.default.createElement("div", null, removeDuplicateMenu(visibleMenus).map((item, index) => {
            const isActive = !!(item === null || item === void 0 ? void 0 : item.current);
            return (react_1.default.createElement(react_1.default.Fragment, { key: item.code }, (0, helper_1.enablePer)(item.code, dataInitMain.perCode) && (react_1.default.createElement(nav_item_1.default, { bgActiveColor: constant_1.MENU_ACTIVE_COLORS[index % constant_1.MENU_ACTIVE_COLORS.length], child: item.child, code: item.code, delayHover: delayHover, href: item.path, isActive: isActive, isShowOtherMenu: showOtherMenu, name: item.name, parentPath: item.path, perCodes: dataInitMain.perCode, requiredActionCount: item.requiredActionCount, showSubMenu: showSubMenu && currentMenuCode === item.code, sideBarType: sideBarType, theme: theme }))));
        })),
        react_1.default.createElement(other_menu_1.default, { active: showOtherMenu, handleChangePined: handleChangePined, noPined: menu.noPined, onChangeSideBarType: onChangeSideBarType, onChangeTheme: onChangeTheme, onOrder: onOrder, pined: menu.pined, setActive: setShowOtherMenu, sideBarType: sideBarType, theme: theme }),
        visibleMenus.length > 0 && (react_1.default.createElement("div", { className: (0, types_1.classNames)('absolute  flex flex-col items-center', isIconWithLabelHorizontal ? 'bottom-1' : 'bottom-0') },
            react_1.default.createElement(nav_item_1.default, { key: 'activity_history_nav', bgActiveColor: constant_1.MENU_ACTIVE_COLORS[1], code: 'ACTIVITY_HISTORY', href: '/activity-history/list', isActive: isActivityHistory, name: 'L\u1ECBch s\u1EED ho\u1EA1t \u0111\u1ED9ng', sideBarType: sideBarType, theme: theme }),
            react_1.default.createElement(nav_item_1.default, { key: 'setting_nav', bgActiveColor: constant_1.MENU_ACTIVE_COLORS[2], code: constant_1.MENU_CODE.SETTING_SITE, href: '/setting', isActive: isSettings, name: 'C\u00E0i \u0111\u1EB7t', sideBarType: sideBarType, theme: theme })))))));
}
//# sourceMappingURL=side-bar.js.map