import { library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { Menu, Transition } from '@headlessui/react';
import { Bars3Icon } from '@heroicons/react/24/outline';
import { XMarkIcon } from '@heroicons/react/24/solid';
import axios from 'axios';
import React, { Fragment, Suspense, useCallback, useEffect, useRef, useState } from 'react';
import StyledCustomLayoutProps from './appearance/appearance-styled';
import CallbackUrlSetter from './components/CallbackUrlSetter';
import LeftHeaderSection from './components/left-heder-section';
import MainContent from './components/main-content';
import Notification from './components/notification';
import { useNotificationUnreadPolling } from './components/notification/hook/useNotificationUnreadPolling';
import SearchBarHeader from './components/search';
import SideBarDesktop from './components/side-bar';
import SubMenu from './components/submenu';
import { LOCALSTORAGE_SHOW_SIDEBAR_TYPE, LOCALSTORAGE_SHOW_SUB_MENU_KEY, SIDEBAR_TYPE } from './constant';
import NavMobile from './navigator/nav-mobile';
import PHXFuncGetCookieSession from '../Func/getCookieSession';
import { useLoading } from '../LoadingProvider';
import { COOKIE_SESSION_SIGN_IN, DEFAULT_AVATAR, DEFAULT_LOGO_DASHBOARD, MENU_ACTIVITY_HISTORY_CHILD, PATH_ACTIVITY_HISTORY, } from '../../utils/constants';
import { clearSession } from '../Func/sessionStore';
import { deleteAllCookies } from '../Func/deleteCookie';
import { deleteLocalStorage } from '../Func/save-local-storage';
import { PHXClientQueryV3, PHXGrpcQueryAllSchool } from '../Func/GRPC/PHXGrpcClientV3';
import { GET_CROSS_SCHOOL_ACCESS_V3, GET_PERMISSION_DETAIL_USER_V3, GET_SCHOOL_V3, QUERY_GET_PROFILE_USER, } from '../../query';
import PHXGetEnvPublicV3 from '../Func/getEnvPublic';
import saveCookiesClient from '../Func/saveCookiesClient';
import { decryptCookie } from '../../helpers/helpers';
import { PHXModal } from '../Modal';
import { classNames } from '../types';
import { PHXGrpcQueryAllSchoolV6 } from '../Func/GRPC/PHXGrpcClientV6';
import { PageTracker } from '../../stores/page-tracker/page-tracker';
import { fetchRequiredActionData } from './components/require-action/required-action-api';
import { applyRequiredActionCount } from './components/require-action/required-action';
import { useMainwrapRealtimeCounts } from './hooks/use-mainwrap-realtime-counts';
library.add(fas);
// Option hiển thị required action count cho menu
const REQUIRED_ACTION_MENU_CONFIG = {
    // Bật để xem mock UI khi API chưa trả count
    useMockFallbackWhenMissing: false,
    fallbackCount: 100,
    // 'all': hiện count cả menu cha + menu con
    // 'leaf-only': chỉ hiện ở menu nhỏ nhất
    displayMode: 'all',
    // Khi API chỉ trả count theo code menu lá, bật true để cộng dồn lên menu cha
    aggregateToParent: true,
    // API/backend sẽ xử lý roll-up; frontend chỉ map count theo code menu
    aggregateByCodeLevel: false,
    codeLevels: [],
};
export const PHXMainWrapV4 = ({ children, getDataCookies, logoHeight = '28px', multipleMenu = false, params, pathName, router, }) => {
    var _a, _b, _c, _d;
    const { pid } = params ? params : {};
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [subNavigation, setSubNavigation] = useState([]);
    const [navigation, setNavigation] = useState([]);
    const [modalSignOut, setModalSignOut] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const sessionCookie = PHXFuncGetCookieSession();
    const userSessionInfo = sessionCookie === null || sessionCookie === void 0 ? void 0 : sessionCookie.user_info;
    const schoolInfoId = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.school_id;
    const userId = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.id;
    const { setLoading: setGlobalLoading } = useLoading();
    const [showSubMenu, setShowSubMenu] = useState(true);
    const [mounted, setMounted] = useState(false);
    const contentRef = useRef(null);
    const [sideBarType, setSideBarType] = useState(SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL);
    const [dataInitMain, setDataInitMain] = useState({
        menuDefault: [],
        loadingMenu: true,
        loadingSchool: true,
        listSchool: [],
        logo: {
            path: '',
            height: logoHeight,
        },
        menu: [],
        schoolId: null,
        configLayout: undefined,
        perCode: [],
        roleCode: [],
        isLoadingPermission: true,
        sourceAvatar: ((_a = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.user_avatar) === null || _a === void 0 ? void 0 : _a.size_small) || (userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.avatar) || DEFAULT_AVATAR,
    });
    const [isRealtimeSocketConnected, setIsRealtimeSocketConnected] = useState(false);
    const accessToken = sessionCookie === null || sessionCookie === void 0 ? void 0 : sessionCookie.access_token;
    const enableUnreadPollingFallback = !mounted || !accessToken || !isRealtimeSocketConnected;
    const { applyUnreadCount, unreadCount } = useNotificationUnreadPolling(5000, enableUnreadPollingFallback);
    const locationPathname = typeof window !== 'undefined' ? window.location.pathname : '';
    const locationArr = locationPathname.split('/').filter(Boolean);
    const basePath = locationArr.slice(0, locationArr.length - pathName.split('/').filter(Boolean).length).join('/');
    const pathNameWithBasePath = `${basePath ? `${'/' + basePath}` : ''}${pathName}`;
    // Lấy code phân quyền trong menu từ path hiện tại
    function getCodesByPath(dataMenu, currentPath) {
        let lastMatchingCode = null;
        const normalizedPath = currentPath.replace(/\/$/, '');
        function traverse(items, prefix) {
            for (const item of items) {
                const fullPath = item.path.startsWith('/') ? prefix + item.path : item.path;
                const normalizedFullPath = fullPath.replace(/\/$/, '');
                if (normalizedPath === normalizedFullPath || normalizedPath.startsWith(normalizedFullPath + '/')) {
                    lastMatchingCode = item.code;
                }
                if (item.child) {
                    traverse(item.child, prefix);
                }
            }
        }
        for (const rootItem of dataMenu) {
            const rootPath = rootItem.path;
            const prefix = rootPath.split('/').slice(0, 2).join('/');
            traverse([rootItem], prefix);
        }
        return lastMatchingCode ? lastMatchingCode : null;
    }
    // code phân quyền path hiện tại
    const currentCode = getCodesByPath(dataInitMain.menuDefault, locationPathname);
    const currentMenuByPath = navigation === null || navigation === void 0 ? void 0 : navigation.find((nav) => { var _a; return (_a = nav === null || nav === void 0 ? void 0 : nav.child) === null || _a === void 0 ? void 0 : _a.some((c) => { var _a; return (c === null || c === void 0 ? void 0 : c.code) === currentCode || ((_a = c === null || c === void 0 ? void 0 : c.child) === null || _a === void 0 ? void 0 : _a.some((x) => (x === null || x === void 0 ? void 0 : x.code) === currentCode)); }); });
    const requireLoginValidation = () => {
        clearSession();
        const currentURL = window.location.href;
        const url = currentURL.split('/');
        const loginPush = `${url[0]}//${url[2]}/login-sso`;
        window.location.replace(loginPush);
    };
    const checkIsQuitJob = ({ profileStaff, profileTeacher }) => {
        try {
            // xóa cookies với những tài khoản giáo viên, nhân viên đã nghỉ việc
            const staffIsQuitJob = profileStaff === null || profileStaff === void 0 ? void 0 : profileStaff.is_quit_job;
            const teacherIsQuitJob = profileTeacher === null || profileTeacher === void 0 ? void 0 : profileTeacher.is_quit_job;
            if (staffIsQuitJob || teacherIsQuitJob) {
                console.log('Phiên đăng nhập đã hết hạn');
                deleteAllCookies();
                deleteLocalStorage(COOKIE_SESSION_SIGN_IN);
                requireLoginValidation();
            }
        }
        catch (error) {
            console.log(error);
        }
    };
    const fetchDataPer = async () => {
        var _a, _b, _c, _d;
        try {
            const res = await PHXClientQueryV3({
                query: GET_PERMISSION_DETAIL_USER_V3,
                variables: { id: userId, school_id: schoolInfoId },
            });
            const userPermissions = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.permission_user) !== null && _b !== void 0 ? _b : [];
            const rolePermissions = (_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c.permission_role) !== null && _d !== void 0 ? _d : [];
            const allPermissions = [...userPermissions, ...rolePermissions];
            // Tách quyền theo loại: quyền route (không phải action) và quyền action
            const permissionCodes = allPermissions.map((p) => p.permission);
            const routePermissions = permissionCodes.filter((p) => !p.is_action).map((p) => p.code);
            const actionPermissions = permissionCodes.filter((p) => p.is_action).map((p) => p.code);
            // Tạo object dạng { ACTION_CODE: true }
            const actionPermissionMap = Object.fromEntries(actionPermissions.map((code) => [code, true]));
            // Xoá trùng và set route permissions
            const uniqueRoutePermissions = Array.from(new Set(routePermissions));
            return { uniqueRoutePermissions, actionPermissionMap };
        }
        catch (error) {
            console.error('Error fetching school data:', error);
            return { uniqueRoutePermissions: null, actionPermissionMap: null };
        }
    };
    const getProfileByUser = async () => {
        try {
            const response = await PHXClientQueryV3({
                query: QUERY_GET_PROFILE_USER,
                variables: {
                    user_id: userId,
                },
            });
            const profileUser = response.data.users_by_pk;
            const { avatar, email, full_name, profile_staff, profile_teacher, user_avatar, user_roles } = profileUser;
            // check user is quit job
            checkIsQuitJob({
                profileStaff: profile_staff,
                profileTeacher: profile_teacher,
            });
            // renew list role in cookie
            return {
                avatar,
                user_avatar,
                full_name,
                email,
                user_code: (profile_staff === null || profile_staff === void 0 ? void 0 : profile_staff.user_code) || (profile_teacher === null || profile_teacher === void 0 ? void 0 : profile_teacher.user_code) || '',
                user_roles,
            };
        }
        catch (error) {
            console.log(error);
            return;
        }
    };
    const fidSettingSiteBySchool = (settings, schoolId) => settings === null || settings === void 0 ? void 0 : settings.find((setting) => setting.school_id === schoolId);
    const fetchDataSchool = async () => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        if (!userSessionInfo)
            return;
        const { email, school: { school_name: { group_id }, school_name_id, }, school_id, } = userSessionInfo;
        setIsLoading(true);
        let settingSiteDb = undefined;
        try {
            const res = await PHXGrpcQueryAllSchool({
                query: GET_SCHOOL_V3,
                variables: { group_id, school_name_id, email },
                isDelay: false,
                isQuery: true,
            });
            const userIds = ((_c = (_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.school) === null || _b === void 0 ? void 0 : _b.flatMap((s) => { var _a; return (_a = s.users) === null || _a === void 0 ? void 0 : _a.map((u) => u.id); })) === null || _c === void 0 ? void 0 : _c.filter(Boolean)) || [];
            let resGraphile = null;
            if (userIds.length > 0) {
                resGraphile = await PHXGrpcQueryAllSchoolV6({
                    query: GET_CROSS_SCHOOL_ACCESS_V3,
                    variables: { userIds },
                    isDelay: false,
                    schemaGroup: 'core-shared',
                });
            }
            let dataSchool = (_e = (_d = res === null || res === void 0 ? void 0 : res.data) === null || _d === void 0 ? void 0 : _d.school_name[0]) === null || _e === void 0 ? void 0 : _e.schools;
            const settingSites = (_f = res === null || res === void 0 ? void 0 : res.data) === null || _f === void 0 ? void 0 : _f.setting_site;
            const canSwitchSchool = ((_j = (_h = (_g = resGraphile === null || resGraphile === void 0 ? void 0 : resGraphile.data) === null || _g === void 0 ? void 0 : _g.allCoreSharedPermissionCrossSchoolAccesses) === null || _h === void 0 ? void 0 : _h.nodes) === null || _j === void 0 ? void 0 : _j.length) > 0;
            if (canSwitchSchool) {
                dataSchool =
                    ((_l = (_k = resGraphile.data.allCoreSharedPermissionCrossSchoolAccesses) === null || _k === void 0 ? void 0 : _k.nodes) === null || _l === void 0 ? void 0 : _l.map((node) => {
                        var _a, _b, _c, _d, _e;
                        const school = node.coreSharedPublicSchoolBySchoolId;
                        const logo = (_b = (_a = fidSettingSiteBySchool(settingSites, school === null || school === void 0 ? void 0 : school.rowId)) === null || _a === void 0 ? void 0 : _a.value_setting) === null || _b === void 0 ? void 0 : _b.replace(/^"(.*)"$/, '$1');
                        return {
                            id: (school === null || school === void 0 ? void 0 : school.rowId) || node.schoolId,
                            name: school === null || school === void 0 ? void 0 : school.name,
                            school_name: {
                                id: (_c = school === null || school === void 0 ? void 0 : school.coreSharedPublicSchoolNameBySchoolNameIdAndSchoolId) === null || _c === void 0 ? void 0 : _c.rowId,
                                group_id: (_d = school === null || school === void 0 ? void 0 : school.coreSharedPublicSchoolNameBySchoolNameIdAndSchoolId) === null || _d === void 0 ? void 0 : _d.groupId,
                            },
                            userId: node.userId,
                            logo: logo ? (_e = JSON.parse(logo)) === null || _e === void 0 ? void 0 : _e.logo_dashboard : null,
                        };
                    })) || [];
            }
            const settingFetchData = (_m = fidSettingSiteBySchool(settingSites, school_id)) === null || _m === void 0 ? void 0 : _m.value_setting;
            if (settingFetchData) {
                const cleanedJsonString = settingFetchData.replace(/^"(.*)"$/, '$1');
                settingSiteDb = JSON.parse(cleanedJsonString);
            }
            setIsLoading(false);
            return {
                settingSiteDb,
                loadingSchool: dataSchool.length === 0,
                listSchool: dataSchool,
                schoolId: school_id,
            };
        }
        catch (error) {
            setIsLoading(false);
            console.error('Error fetching school data:', error);
            return;
        }
    };
    const fetchDataMenu = async () => {
        const envPublic = await PHXGetEnvPublicV3();
        const menuUrl = envPublic === null || envPublic === void 0 ? void 0 : envPublic.SCHOOL_MENU_V2;
        const logoMenuTop = envPublic === null || envPublic === void 0 ? void 0 : envPublic.SCHOOL_TOP_MENU_LOGO;
        if (!menuUrl || !logoMenuTop) {
            console.error('menu or logo not found');
        }
        const data = await fetch(menuUrl, {
            cache: 'no-store', // tắt cache menu
        });
        const menuJson = await data.json();
        return {
            loadingMenu: false,
            logo: { path: logoMenuTop, height: logoHeight },
            menu: menuJson,
        };
    };
    const detectEnvByDomain = (domain, configEnv) => {
        for (const [env, pattern] of Object.entries(configEnv)) {
            if (env.startsWith('_comment'))
                continue; // bỏ qua comment
            const regex = new RegExp(pattern.replace(/\\\\/g, '\\'));
            if (regex.test(domain))
                return env;
        }
        return 'stg';
    };
    const getEnvByConfig = (configEnv) => {
        const domain = window.location.hostname;
        const env = detectEnvByDomain(domain, configEnv);
        return `config_menu_${env}:disable`;
    };
    const isConfigEnvValid = (code, configDisable) => configDisable.length === 0 || !(configDisable === null || configDisable === void 0 ? void 0 : configDisable.includes(code));
    const funcMenuByConfigEnv = (menuJson, configDisable) => {
        const menuWithConfigEnv = [];
        for (const item of menuJson) {
            if (!isConfigEnvValid(item === null || item === void 0 ? void 0 : item.code, configDisable))
                continue;
            const menuItem = { ...item, child: [] };
            const menuSecondLevel = (item === null || item === void 0 ? void 0 : item.child) || [];
            for (const childItem of menuSecondLevel || []) {
                if (!isConfigEnvValid(childItem === null || childItem === void 0 ? void 0 : childItem.code, configDisable))
                    continue;
                const childMenuItem = { ...childItem, child: [] };
                const menuThirdLevel = (childItem === null || childItem === void 0 ? void 0 : childItem.child) || [];
                for (const subChildItem of menuThirdLevel) {
                    if (!isConfigEnvValid(subChildItem === null || subChildItem === void 0 ? void 0 : subChildItem.code, configDisable))
                        continue;
                    childMenuItem.child.push(subChildItem);
                }
                menuItem.child.push(childMenuItem);
            }
            menuWithConfigEnv.push(menuItem);
        }
        return menuWithConfigEnv;
    };
    const fetchInitData = async () => {
        var _a;
        const { loadingMenu, logo, menu } = await fetchDataMenu();
        const requiredActionData = await fetchRequiredActionData();
        const profileNew = await getProfileByUser();
        const dataPer = await fetchDataPer();
        const { actionPermissionMap, uniqueRoutePermissions } = dataPer;
        const dataSchool = await fetchDataSchool();
        const { config_env } = menu;
        const enviromentByDomainConfig = getEnvByConfig(config_env);
        const menuJson = menu.menu;
        const configDisable = menu[enviromentByDomainConfig];
        const menuWithConfigEnv = funcMenuByConfigEnv(menuJson, configDisable);
        const menuWithRequiredAction = applyRequiredActionCount(menuWithConfigEnv, requiredActionData.countByCode, REQUIRED_ACTION_MENU_CONFIG);
        setDataInitMain({
            menuDefault: menuJson,
            logo,
            menu: menuWithRequiredAction,
            loadingMenu,
            schoolId: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.schoolId) || null,
            loadingSchool: !!(dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.loadingSchool),
            listSchool: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.listSchool) || [],
            isLoadingPermission: false,
            perCode: uniqueRoutePermissions,
            roleCode: (profileNew === null || profileNew === void 0 ? void 0 : profileNew.user_roles.map((userRole) => { var _a; return (_a = userRole === null || userRole === void 0 ? void 0 : userRole.role) === null || _a === void 0 ? void 0 : _a.role_code; })) || [],
            configLayout: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.settingSiteDb) || undefined,
            sourceAvatar: ((_a = profileNew === null || profileNew === void 0 ? void 0 : profileNew.user_avatar) === null || _a === void 0 ? void 0 : _a.size_small) || (profileNew === null || profileNew === void 0 ? void 0 : profileNew.avatar) || DEFAULT_AVATAR,
        });
        const currentSession = PHXFuncGetCookieSession();
        saveCookiesClient({
            value: {
                ...currentSession,
                ...(actionPermissionMap && {
                    action_permission: actionPermissionMap || [],
                }),
                setting_site: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.settingSiteDb) || {},
                ...(profileNew && {
                    user_info: {
                        ...userSessionInfo,
                        ...profileNew,
                    },
                }),
            },
        });
    };
    const isEqualUrl = (parentHref, pathNameCompare) => {
        if (!parentHref || !pathNameCompare) {
            return false;
        }
        const pathNameSplit = pathNameCompare.split('/');
        const hrefSplit = parentHref.split('/');
        if (!pathNameSplit || !hrefSplit) {
            return false;
        }
        let urlRouter;
        let currentMenu;
        if (multipleMenu) {
            urlRouter = pathNameSplit[1] + pathNameSplit[2];
            currentMenu = hrefSplit[1] + hrefSplit[2];
        }
        else {
            urlRouter = pathNameSplit[1];
            currentMenu = hrefSplit[1];
        }
        return urlRouter === currentMenu;
    };
    const isBelongParentWithMicroservice = (parentSplit, pathNameSplit) => {
        if (parentSplit.length > 2) {
            const compareLength = parentSplit.length;
            for (let i = 1; i < compareLength; i++) {
                if (parentSplit[i] !== pathNameSplit[i])
                    return false;
            }
            return true;
        }
        else {
            return parentSplit[1] === pathNameSplit[3];
        }
    };
    const isBelongParent = (parentUrl, pathNameCompare, isMicroservice) => {
        const parentSplit = parentUrl.split('/');
        const pathNameSplit = pathNameCompare.split('/');
        if (isMicroservice) {
            return isBelongParentWithMicroservice(parentSplit, pathNameSplit);
        }
        if (parentSplit.length > 2 && !parentSplit.includes('list')) {
            return parentSplit[1] === pathNameSplit[2] && parentSplit[2] === pathNameSplit[3];
        }
        else {
            return parentSplit[1] === pathNameSplit[2];
        }
    };
    const loadParentNavigation = (path) => {
        const mainNavigation = dataInitMain.menu;
        const naviSize = mainNavigation.length;
        for (let i = 0; i < naviSize; i++) {
            const item = mainNavigation[i];
            item.current = false;
            if (item.path === path || isEqualUrl(item.path, path)) {
                item.current = true;
                // Find sub modules
                const itemLength = item.child.length;
                const listChildren = [];
                for (let j = 0; j < itemLength; j++) {
                    const childItem = item.child[j];
                    // Active child item
                    childItem.current = isBelongParent(childItem.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice));
                    if (childItem.child) {
                        const childItemLength = childItem.child.length;
                        let count = 0;
                        for (let k = 0; k < childItemLength; k++) {
                            const subChild = childItem.child[k];
                            subChild.current = isBelongParent(subChild.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice));
                            if (isBelongParent(subChild.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice)) ||
                                isBelongParent(childItem.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice))) {
                                count++;
                            }
                            const isSameSubChildPath = (subChild === null || subChild === void 0 ? void 0 : subChild.isMicroservice)
                                ? subChild.path === (childItem === null || childItem === void 0 ? void 0 : childItem.path)
                                : subChild.path === (childItem === null || childItem === void 0 ? void 0 : childItem.pathInternal);
                            const isPathInternal = (childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice) ? isSameSubChildPath : subChild.path === childItem.path;
                            childItem.showChild = count > 0;
                            if (isPathInternal)
                                childItem.current = false;
                        }
                    }
                    listChildren.push(childItem);
                }
                setSubNavigation(listChildren);
            }
        }
        setNavigation(mainNavigation);
    };
    const loadSubNavigation = (path, isChild, childPath) => {
        const subLength = subNavigation.length;
        const newSub = [];
        for (let i = 0; i < subLength; i++) {
            const item = subNavigation[i];
            item.current = item.path === path && !isChild;
            if (item.child) {
                item.showChild = item.path === path;
                for (let j = 0; j < item.child.length; j++) {
                    const child = item.child[j];
                    child.current = child.path === childPath;
                    if (child.path === item.path) {
                        item.current = false;
                        child.current = childPath ? child.path === childPath : child.path === path;
                    }
                }
            }
            newSub.push(item);
        }
        setSubNavigation(newSub);
    };
    const subNavigationTriggerClicked = (item, parent) => {
        if (parent) {
            loadSubNavigation(parent.path, true, item.path);
        }
        else {
            loadSubNavigation(item.path, false);
        }
        if (pathName !== item.path) {
            setGlobalLoading(true);
        }
        router.push(item.path);
    };
    const { path: topMenuLogoFromEnv } = dataInitMain.logo;
    const handleModalSignOut = () => setModalSignOut(true);
    const handleRedirectRouter = (path) => {
        const currentURL = window.location.href;
        const url = currentURL.split('/');
        const pushPath = `${url[0]}//${url[2]}/${path}`;
        window.location.replace(pushPath);
    };
    const callApiLogoutToken = async () => {
        try {
            return await axios.post(`/api/authenticate/logout`, {}, {
                withCredentials: true,
            });
        }
        catch (error) {
            console.error(error);
            return;
        }
    };
    const handleSignOut = async () => {
        setModalSignOut(false);
        deleteAllCookies();
        deleteLocalStorage(COOKIE_SESSION_SIGN_IN);
        await callApiLogoutToken();
        handleRedirectRouter('login-sso');
    };
    const handleProfilePage = () => {
        handleRedirectRouter('profile');
    };
    const isSettingPage = ((_b = pathNameWithBasePath === null || pathNameWithBasePath === void 0 ? void 0 : pathNameWithBasePath.split('/')) === null || _b === void 0 ? void 0 : _b[1]) === 'setting';
    const checkLogoHeader = ((_c = dataInitMain.configLayout) === null || _c === void 0 ? void 0 : _c.logo_dashboard) || topMenuLogoFromEnv || DEFAULT_LOGO_DASHBOARD;
    const isActivityHistory = () => {
        const pathNameSplit = pathNameWithBasePath.split('/');
        return pathNameSplit[1] === PATH_ACTIVITY_HISTORY;
    };
    const [activityHistoryChild, setActivityHistoryChild] = useState(MENU_ACTIVITY_HISTORY_CHILD);
    const handleClickActivityHistoryChild = (clickedItem) => {
        const updated = activityHistoryChild.map((item) => ({
            ...item,
            current: item.code === clickedItem.code,
        }));
        setActivityHistoryChild(updated);
    };
    const onChangeSideBarType = (type) => {
        setSideBarType(type);
        localStorage.setItem(LOCALSTORAGE_SHOW_SIDEBAR_TYPE, type);
    };
    useEffect(() => {
        if (basePath === PATH_ACTIVITY_HISTORY) {
            setActivityHistoryChild((prev) => prev.map((item) => ({
                ...item,
                current: pathNameWithBasePath.endsWith(item.path),
            })));
        }
        else {
            setActivityHistoryChild([]);
        }
    }, [pathNameWithBasePath, basePath]);
    useEffect(() => {
        loadParentNavigation(pathNameWithBasePath);
    }, [dataInitMain, pid, pathNameWithBasePath]);
    useEffect(() => {
        if (!userSessionInfo) {
            // Require login if production mode
            requireLoginValidation();
            return;
        }
        setMounted(true);
        setShowSubMenu(JSON.parse(localStorage.getItem(LOCALSTORAGE_SHOW_SUB_MENU_KEY) || 'true'));
        setSideBarType(localStorage.getItem(LOCALSTORAGE_SHOW_SIDEBAR_TYPE) || SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL);
        fetchInitData();
    }, []);
    useEffect(() => {
        if (mounted) {
            localStorage.setItem(LOCALSTORAGE_SHOW_SUB_MENU_KEY, JSON.stringify(showSubMenu));
        }
    }, [showSubMenu, mounted]);
    const handleSocketRequiredAction = useCallback(({ countByCode }) => {
        setDataInitMain((prev) => {
            var _a;
            if (!((_a = prev.menu) === null || _a === void 0 ? void 0 : _a.length))
                return prev;
            const nextMenu = applyRequiredActionCount(prev.menu, countByCode, REQUIRED_ACTION_MENU_CONFIG);
            return { ...prev, menu: nextMenu };
        });
    }, []);
    const handleSocketConnectionChange = useCallback((connected) => {
        setIsRealtimeSocketConnected(connected);
    }, []);
    useMainwrapRealtimeCounts({
        accessToken,
        currentUserId: userId,
        enabled: mounted,
        onConnectionChange: handleSocketConnectionChange,
        onRequiredAction: handleSocketRequiredAction,
        onUnreadCount: applyUnreadCount,
    });
    return (mounted && (React.createElement(React.Fragment, null,
        React.createElement(PageTracker, null),
        React.createElement(Suspense, { fallback: null },
            React.createElement(CallbackUrlSetter, { path: pathNameWithBasePath })),
        React.createElement("div", { className: 'flex h-12 flex-col bg-[#DEDEDE]' },
            React.createElement(StyledCustomLayoutProps, { configLayout: dataInitMain === null || dataInitMain === void 0 ? void 0 : dataInitMain.configLayout, settingSiteCookie: getDataCookies ? (_d = decryptCookie(getDataCookies)) === null || _d === void 0 ? void 0 : _d.setting_site : null }),
            React.createElement("header", { className: 'fixed top-0 z-[50] flex h-12 min-w-full flex-col justify-between pl-1.5 pr-2 lg:px-5 bg-[#DEDEDE] lg:bg-transparent' },
                React.createElement("div", { className: 'flex h-12 w-full items-center justify-between' },
                    React.createElement("div", { className: 'flex items-center gap-x-2' },
                        React.createElement("div", { className: 'flex items-center lg:hidden' },
                            React.createElement("button", { className: 'bg-grey-100 inline-flex items-center justify-center rounded-md p-1 text-gray-200 hover:bg-white hover:text-gray-600', onClick: () => setSidebarOpen(!sidebarOpen), type: 'button' },
                                React.createElement("span", { className: 'sr-only' }, "Open sidebar"),
                                sidebarOpen ? (React.createElement(XMarkIcon, { "aria-hidden": 'true', className: 'h-5 w-5 text-gray-900' })) : (React.createElement(Bars3Icon, { "aria-hidden": 'true', className: 'h-5 w-5 text-gray-900' })))),
                        !isLoading && (React.createElement(LeftHeaderSection, { checkLogoHeader: checkLogoHeader, currSchoolId: dataInitMain.schoolId, perCodes: dataInitMain.perCode, schools: dataInitMain.listSchool, topMenuLogoFromEnv: topMenuLogoFromEnv }))),
                    React.createElement(SearchBarHeader, { contentRef: contentRef, menu: navigation, perCode: dataInitMain.perCode, sideBarType: sideBarType, unreadCount: unreadCount, userId: userId }),
                    React.createElement("div", { className: 'flex items-center gap-2' },
                        React.createElement(Notification, { unreadCount: unreadCount }),
                        React.createElement("div", null,
                            React.createElement(Menu, { as: 'div', className: 'relative' },
                                React.createElement("div", null,
                                    React.createElement(Menu.Button, { className: 'flex max-w-xs items-center rounded-full bg-gray-800 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800' },
                                        React.createElement("span", { className: 'sr-only' }, "Open user menu"),
                                        isLoading ? (React.createElement("div", { className: 'flex animate-pulse' },
                                            React.createElement("div", { className: 'header-loading-avatar h-6 w-6 rounded-full' }))) : (React.createElement("img", { alt: '', className: 'h-6 w-6 rounded-full', src: dataInitMain.sourceAvatar })))),
                                React.createElement(Transition, { as: Fragment, enter: 'transition ease-out duration-100', enterFrom: 'transform opacity-0 scale-95', enterTo: 'transform opacity-100 scale-100', leave: 'transition ease-in duration-75', leaveFrom: 'transform opacity-100 scale-100', leaveTo: 'transform opacity-0 scale-95' },
                                    React.createElement(Menu.Items, { className: ' shadow-lg absolute right-0 z-10 mt-2 w-[340px] origin-top-right rounded-md bg-white px-2 ring-1 ring-black ring-opacity-5 focus:outline-none' },
                                        React.createElement(Menu.Item, null,
                                            React.createElement("div", { "aria-hidden": true, className: 'px-2 pb-2 pt-4  text-sm font-semibold text-gray-900' }, "T\u00F9y ch\u1ECDn")),
                                        React.createElement(Menu.Item, null,
                                            React.createElement("div", { "aria-hidden": true, className: 'cursor-pointer px-2 py-1.5 text-sm text-gray-900 hover:rounded-lg hover:bg-gray-100', onClick: handleProfilePage }, "Th\u00F4ng tin c\u00E1 nh\u00E2n")),
                                        React.createElement(Menu.Item, null,
                                            React.createElement("div", { "aria-hidden": true, className: 'mb-2.5 cursor-pointer px-2 py-1.5 text-sm text-[#8e1f0c] hover:rounded-lg hover:bg-gray-100', onClick: handleModalSignOut }, "\u0110\u0103ng xu\u1EA5t")))))))))),
        React.createElement(PHXModal, { dangerActionText: '\u0110\u0103ng xu\u1EA5t', onDangerClick: handleSignOut, onHide: () => setModalSignOut(false), primaryActionText: '', show: modalSignOut, title: '\u0110\u0103ng xu\u1EA5t' },
            React.createElement("div", { className: 'text-sm text-gray-700' }, "Khi th\u1EF1c hi\u1EC7n thao t\u00E1c n\u00E0y b\u1EA1n s\u1EBD tho\u00E1t kh\u1ECFi trang qu\u1EA3n tr\u1ECB v\u00E0 tr\u1EDF v\u1EC1 trang \u0111\u0103ng nh\u1EADp")),
        React.createElement("div", { className: classNames('relative h-screen bg-[#DEDEDE] pb-[0.5rem] lg:flex lg:h-[calc(100vh-3rem)] lg:flex-col lg:overflow-hidden', sideBarType === SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL ? 'lg:!pl-4' : 'lg:!pl-2') },
            React.createElement("div", { className: 'h-full lg:flex' },
                React.createElement(NavMobile, { hiddenSideBar: () => setSidebarOpen(false), menu: dataInitMain.menu, path: pathNameWithBasePath, pathNameWithBasePath: pathNameWithBasePath, permission: dataInitMain.perCode, router: router, setSidebarOpen: setSidebarOpen, sidebarOpen: sidebarOpen }),
                React.createElement(SideBarDesktop, { currentMenuCode: (currentMenuByPath === null || currentMenuByPath === void 0 ? void 0 : currentMenuByPath.code) || '', dataInitMain: dataInitMain, isActivityHistory: isActivityHistory(), isSettings: isSettingPage, navigation: navigation, onChangeSideBarType: onChangeSideBarType, setShowSubMenu: setShowSubMenu, showSubMenu: showSubMenu, sideBarType: sideBarType, userId: userId }),
                React.createElement(SubMenu, { activityHistoryChild: activityHistoryChild, currentMenuByPath: currentMenuByPath, handleClickActivityHistoryChild: handleClickActivityHistoryChild, isActivityHistory: isActivityHistory(), isShowSubmenu: showSubMenu, loadingMenu: dataInitMain.loadingMenu, perCode: dataInitMain.perCode, roleCodes: dataInitMain.roleCode, setShowSubMenu: setShowSubMenu, sideBarType: sideBarType, subNavigation: subNavigation, subNavigationTriggerClicked: subNavigationTriggerClicked }),
                React.createElement(MainContent, { contentRef: contentRef, currentCode: currentCode || '', isLoadingPermission: dataInitMain.isLoadingPermission, perCode: dataInitMain.perCode, showSubMenu: showSubMenu, sideBarType: sideBarType }, children))))));
};
//# sourceMappingURL=MainWrapV4.js.map