<script lang="ts" setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import type { VerticalNavItems } from '@layouts/types'
import VerticalNav from './VerticalNav.vue'

interface Props {
  navItems: VerticalNavItems
}

defineProps<Props>()

const isOverlayNavActive = ref<boolean>(false)
const isNavCollapsed = ref<boolean>(false)

// Persist collapsed state in localStorage
onMounted(() => {
  const saved = localStorage.getItem('ezscale-nav-collapsed')
  if (saved !== null) {
    isNavCollapsed.value = saved === 'true'
  }
})

watch(isNavCollapsed, (val) => {
  localStorage.setItem('ezscale-nav-collapsed', String(val))
})

// Close overlay when window resizes to desktop
const BREAKPOINT = 1280

function handleResize(): void {
  if (window.innerWidth >= BREAKPOINT && isOverlayNavActive.value) {
    isOverlayNavActive.value = false
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

function toggleOverlayNav(value: boolean): void {
  isOverlayNavActive.value = value
}
</script>

<template>
  <div
    class="layout-wrapper layout-nav-type-vertical"
    :class="{
      'layout-vertical-nav-collapsed': isNavCollapsed,
      'layout-overlay-nav': false,
    }"
  >
    <!-- Vertical Nav -->
    <VerticalNav
      :nav-items="navItems"
      v-model:is-overlay-nav-active="isOverlayNavActive"
      :is-collapsed="isNavCollapsed"
      @update:is-collapsed="isNavCollapsed = $event"
    />

    <!-- Content Wrapper -->
    <div class="layout-content-wrapper">
      <!-- Navbar -->
      <header class="layout-navbar">
        <div class="navbar-content d-flex align-center h-100 px-4">
          <!-- Mobile hamburger (shown below 1280px via CSS) -->
          <VBtn
            icon
            variant="text"
            size="small"
            class="d-lg-none me-2"
            @click="toggleOverlayNav(true)"
          >
            <VIcon icon="tabler-menu-2" size="22" />
          </VBtn>

          <slot name="navbar" />
        </div>
      </header>

      <!-- Main Content -->
      <main class="layout-page-content">
        <slot />
      </main>

      <!-- Footer -->
      <footer class="layout-footer">
        <slot name="footer">
          <span class="text-body-2 text-medium-emphasis">
            &copy; {{ new Date().getFullYear() }} EZSCALE. All rights reserved.
          </span>
        </slot>
      </footer>
    </div>

    <!-- Overlay Backdrop -->
    <div
      class="layout-overlay"
      :class="{ visible: isOverlayNavActive }"
      @click="toggleOverlayNav(false)"
    />
  </div>
</template>
