<template>
    <div>
        <ul v-if="loading" class="side-menu" style="margin-right: 0px; flex-wrap: nowrap; margin-left: 0px;">
            <li class="side-item text-center">
                <a class="" href="javascript:void(0);">
                    <span class="spinner-border spinner-border-sm"></span>
                </a>
            </li>
        </ul>
        <ul v-if="!loading" class="side-menu" style="margin-right: 0px; flex-wrap: nowrap; margin-left: 0px;">
            <li class="slide" v-for="(menu, index) in menus" :key="'menu-' + index"
                :class="{ 'is-expanded': expandedMenus[index] }">
                <a href="javascript:void(0);" v-if="menu.Kind === 1 || menu.Kind === 2" class="side-menu__item"
                    @click="toggleMenu(index)">
                    <span class="side-menu__icon " :class="menu.IconClass"></span>
                    <span class="side-menu__label">{{ menu.Label }}</span>
                    <i v-if="menu.Childs != null && menu.Childs.length > 0" class="angle fe fe-chevron-down"></i>
                </a>
                <router-link v-if="menu.Kind === 3" class="side-menu__item" :to="menu.Url == '' ? '/' : '/' + menu.Url">
                    <span class="side-menu__icon " :class="menu.IconClass"></span>
                    <span class="side-menu__label">{{ menu.Label }}</span>
                    <i v-if="menu.Childs != null && menu.Childs.length > 0" class="angle fe fe-chevron-down"></i>
                </router-link>
                <template v-if="menu.Childs != null && menu.Childs.length > 0">
                    <MenuTree :menu-items="menu.Childs" :expanded-sub-menus="expandedSubMenus[index] || {}"
                        @toggle-sub-menu="(subIndex) => toggleSubMenu(index, subIndex)" :key="'menu-' + index">
                    </MenuTree>
                </template>
            </li>
        </ul>

        <!-- Debug info for development -->
        <!-- <div v-if="showDebug"
            style="position: fixed; bottom: 10px; right: 10px; background: rgba(0,0,0,0.8); color: white; padding: 10px; border-radius: 5px; font-size: 12px; z-index: 9999;">
            <div>Menu States:</div>
            <div v-for="(expanded, index) in expandedMenus" :key="'debug-' + index">
                Menu {{ index }}: {{ expanded ? 'Mở' : 'Đóng' }}
            </div>
        </div> -->
    </div>
</template>
<script setup>
import { onMounted, ref, reactive, onUnmounted, nextTick } from 'vue';
import { useUserStore } from '@/stores';
import menuService from "@/services/menuService";



import MenuTree from './components/menuTree.vue';

const uStore = useUserStore();

const loading = ref(false);
const menus = reactive([]);
const expandedMenus = reactive({});
const expandedSubMenus = reactive({});
const showDebug = ref(true); // Bật debug để kiểm tra

function toggleMenu(index) {
    console.log('Toggle menu:', index, 'Current state:', expandedMenus[index]);
    // Force reactivity by using Vue.set or direct assignment
    if (expandedMenus[index]) {
        expandedMenus[index] = false;
    } else {
        expandedMenus[index] = true;
    }
    console.log('New state:', expandedMenus[index]);
    if (!expandedSubMenus[index]) {
        expandedSubMenus[index] = {};
    }

    // Force Vue to re-render
    nextTick(() => {
        console.log('Menu element classes:', document.querySelectorAll('.slide')[index]?.classList.toString());
    });
}

function toggleSubMenu(parentIndex, subIndex) {
    if (!expandedSubMenus[parentIndex]) {
        expandedSubMenus[parentIndex] = {};
    }
    // Force reactivity
    if (expandedSubMenus[parentIndex][subIndex]) {
        expandedSubMenus[parentIndex][subIndex] = false;
    } else {
        expandedSubMenus[parentIndex][subIndex] = true;
    }
}

// Close menu when clicking outside
function handleClickOutside(event) {
    const menuContainer = event.target.closest('.side-menu');
    if (!menuContainer) {
        // Reset all expanded states
        Object.keys(expandedMenus).forEach(key => {
            expandedMenus[key] = false;
        });
        Object.keys(expandedSubMenus).forEach(key => {
            expandedSubMenus[key] = {};
        });
    }
}

async function getMenus() {
    loading.value = true;
    menus.splice(0, menus.length);
    var parentResult = await menuService.getMenuList();
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(menu => {
            menus.push(menu);
        });
    }
    loading.value = false;
}

onMounted(async () => {
    //console.log('onMounted menus');
    //console.log(localStorage.user);
    if (uStore.user) {
        //console.log(uStore.user);
        await getMenus();
    }

    // Add click outside listener
    document.addEventListener('click', handleClickOutside);
})

onUnmounted(() => {
    // Remove click outside listener
    document.removeEventListener('click', handleClickOutside);
})





</script>
<style scoped>
.side-menu .side-menu__icon {
    margin-inline-end: 3px;
    line-height: 20px;
    font-size: 12px;
}

/* Responsive styles for mobile */
@media (max-width: 991px) {
    .slide-menu {
        max-height: 0;
        overflow: hidden;
        padding-inline-start: 15px;
        transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
        opacity: 0;
    }

    .slide.is-expanded .slide-menu {
        max-height: 500px;
        opacity: 1;
    }

    .sub-slide-menu {
        max-height: 0;
        overflow: hidden;
        padding-inline-start: 15px;
        transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
        opacity: 0;
    }

    .sub-slide.is-expanded .sub-slide-menu {
        max-height: 300px;
        opacity: 1;
    }

    .slide-item {
        padding: 10px 15px !important;
        font-size: 14px;
    }

    .sub-side-menu__item {
        padding: 8px 15px !important;
        font-size: 13px;
    }

    .side-menu__item {
        padding: 12px 15px !important;
        font-size: 14px;
    }
}

/* Ensure menu items are clickable on mobile */
.side-menu__item,
.slide-item {
    cursor: pointer;
    user-select: none;
}

/* Smooth transitions for menu expansion */
.slide-menu,
.sub-slide-menu {
    transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

.angle,
.sub-angle {
    transition: transform 0.3s ease-in-out;
    transform-origin: center;
}
</style>