<script setup lang="ts">
import './styles/layout.scss';

import { computed, ref, watch } from 'vue';

import AppFooter from './AppFooter.vue';
import AppSidebar from './AppSidebar.vue';
import AppTopbar from './AppTopbar.vue';
import { useLayout } from './composables/layout';

const { isSidebarActive, layoutConfig, layoutState } = useLayout();

const outsideClickListener = ref(null as null | Parameters<typeof document.addEventListener>[1]);

watch(isSidebarActive, (newValue) => {
  if (newValue) {
    bindOutsideClickListener();
  } else {
    unbindOutsideClickListener();
  }
});

const containerClass = computed(() => {
  return {
    'layout-mobile-active': layoutState.staticMenuMobileActive,
    'layout-overlay': layoutConfig.menuMode === 'overlay',
    'layout-overlay-active': layoutState.overlayMenuActive,
    'layout-static': layoutConfig.menuMode === 'static',
    'layout-static-inactive': layoutState.staticMenuDesktopInactive && layoutConfig.menuMode === 'static',
  };
});

function bindOutsideClickListener() {
  if (!outsideClickListener.value) {
    outsideClickListener.value = (event) => {
      if (isOutsideClicked(event)) {
        layoutState.overlayMenuActive = false;
        layoutState.staticMenuMobileActive = false;
        layoutState.menuHoverActive = false;
      }
    };
    document.addEventListener('click', outsideClickListener.value);
  }
}

function isOutsideClicked(event: Event) {
  const sidebarEl = document.querySelector('.layout-sidebar')!;
  const topbarEl = document.querySelector('.layout-menu-button')!;

  return !(
    sidebarEl.isSameNode(event.target as never) ||
    sidebarEl.contains(event.target as never) ||
    topbarEl.isSameNode(event.target as never) ||
    topbarEl.contains(event.target as never)
  );
}

function unbindOutsideClickListener() {
  if (outsideClickListener.value) {
    document.removeEventListener('click', outsideClickListener.value);
    outsideClickListener.value = null;
  }
}
</script>

<template>
  <div class="layout-wrapper" :class="containerClass">
    <app-topbar></app-topbar>
    <app-sidebar></app-sidebar>
    <div class="layout-main-container">
      <div class="layout-main">
        <router-view></router-view>
      </div>
      <app-footer></app-footer>
    </div>
    <div class="layout-mask animate-fadein"></div>
  </div>
  <Toast />
</template>
