<script setup>
import { useLayout } from '@/layout/composables/layout';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { UserPrefStore } from '../stores/UserPrefStore.js';
import AppFooter from './AppFooter.vue';
import AppSidebar from './AppSidebar.vue';
import AppTopbar from './AppTopbar.vue';


const { hideMenu, layoutConfig, layoutState, isSidebarActive, resetMenu,setPrimary, setPreset } = useLayout();

const outsideClickListener = ref(null);
const page = ref("progetti");
const userPrefStore = UserPrefStore();
const route = useRoute();

onMounted(() => {
    userPrefStore.fetchUserData();
    
});

watch(isSidebarActive, (newVal) => {
    //console.log("routerLink", routerLink);
    if (newVal) {
        bindOutsideClickListener();
    } else {
        unbindOutsideClickListener();
    }
});

watch(route, (newRoute) => {
    if (newRoute.path === '/projects') {
        hideMenu();
    }
});

const containerClass = computed(() => {
    return {
        'layout-theme-light': !layoutConfig.darkTheme,
        'layout-theme-dark': layoutConfig.darkTheme,
        'layout-overlay': layoutConfig.menuMode === 'overlay',
        'layout-static': layoutConfig.menuMode === 'static',
        'layout-static-inactive': layoutState.staticMenuDesktopInactive && layoutConfig.menuMode === 'static',
        'layout-overlay-active': layoutState.overlayMenuActive,
        'layout-mobile-active': layoutState.staticMenuMobileActive
    };
});
const bindOutsideClickListener = () => {
    if (!outsideClickListener.value) {
        outsideClickListener.value = (event) => {
            if (isOutsideClicked(event)) {
                resetMenu();
            }
        };
        document.addEventListener('click', outsideClickListener.value);
    }
};
const unbindOutsideClickListener = () => {
    if (outsideClickListener.value) {
        document.removeEventListener('click', outsideClickListener);
        outsideClickListener.value = null;
    }
};
const isOutsideClicked = (event) => {
    const sidebarEl = document.querySelector('.layout-sidebar');
    const topbarEl = document.querySelector('.layout-menu-button');

    return !(sidebarEl.isSameNode(event.target) || sidebarEl.contains(event.target) || topbarEl.isSameNode(event.target) || topbarEl.contains(event.target));
};
</script>

<template>
    <div v-if="userPrefStore.userLoaded" class="layout-wrapper" :class="containerClass">
        <app-topbar :page="page"></app-topbar>
       <div class="layout-sidebar">

            <app-sidebar v-if="route.path !== '/projects'"></app-sidebar>
        </div>
        <div class="layout-main-container">
            <div  class="layout-main">
                <router-view></router-view>
            </div>
            <app-footer></app-footer>
        </div>
        <div class="layout-mask"></div>
    </div>
    <ConfirmDialog />
    <Toast />
</template>

<style lang="scss" scoped></style>
