<script lang="ts" setup>
import { Link, usePage } from '@inertiajs/vue3'
import { ref, watch } from 'vue'
import type { NavGroup, NavLink, VerticalNavItems } from '@layouts/types'
import logoWhite from '@images/ezscale_logo_white.png'

interface Props {
  navItems: VerticalNavItems
  collapsed?: boolean
  mobileOpen?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  collapsed: false,
  mobileOpen: false,
})

const emit = defineEmits<{
  'update:collapsed': [value: boolean]
  'update:mobileOpen': [value: boolean]
}>()

const page = usePage()

function isActive(to: string): boolean {
  const url = page.url
  if (to === '/dashboard') return url === '/dashboard' || url === '/dashboard/'
  return url.startsWith(to)
}

function isGroupActive(children: (NavLink | NavGroup)[]): boolean {
  return children.some(child => {
    if ('children' in child) return isGroupActive(child.children)
    return isActive(child.to)
  })
}

const openGroups = ref<Set<number>>(new Set())

function toggleGroup(index: number): void {
  if (openGroups.value.has(index)) {
    openGroups.value.delete(index)
  } else {
    openGroups.value.add(index)
  }
}

// Auto-open groups containing active links
watch(() => page.url, () => {
  props.navItems.forEach((item, index) => {
    if ('children' in item && isGroupActive(item.children)) {
      openGroups.value.add(index)
    }
  })
  // Close mobile nav on route change
  if (props.mobileOpen) emit('update:mobileOpen', false)
}, { immediate: true })

function toggleCollapse(): void {
  emit('update:collapsed', !props.collapsed)
}
</script>

<template>
  <aside
    class="app-sidebar"
    :class="{
      'app-sidebar--collapsed': collapsed && !mobileOpen,
      'app-sidebar--mobile-open': mobileOpen,
    }"
  >
    <!-- Header -->
    <div class="sidebar-header">
      <Link href="/dashboard" class="d-flex align-center text-decoration-none">
        <img :src="logoWhite" alt="EZSCALE" style="height: 28px; width: auto;" />
        <span class="sidebar-logo-text text-white">EZSCALE</span>
      </Link>
      <VBtn
        icon
        variant="text"
        size="x-small"
        color="white"
        class="ms-auto sidebar-logo-text"
        @click="toggleCollapse"
      >
        <VIcon :icon="collapsed ? 'tabler-layout-sidebar-right-expand' : 'tabler-layout-sidebar-left-collapse'" size="20" />
      </VBtn>
    </div>

    <!-- Navigation -->
    <nav class="sidebar-nav">
      <template v-for="(item, index) in navItems" :key="index">
        <!-- Section Title -->
        <div v-if="'heading' in item" class="nav-section-title">
          {{ item.heading }}
        </div>

        <!-- Nav Group -->
        <template v-else-if="'children' in item">
          <div
            class="nav-item"
            :class="{ 'nav-item--active': isGroupActive(item.children) }"
            @click="toggleGroup(index)"
          >
            <VIcon v-if="item.icon" :icon="item.icon" class="nav-item-icon" size="22" />
            <span class="nav-item-title">{{ item.title }}</span>
            <VIcon
              icon="tabler-chevron-right"
              size="16"
              class="nav-item-title ms-auto"
              :style="{ transform: openGroups.has(index) ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s ease' }"
            />
          </div>
          <div v-show="openGroups.has(index) && !(collapsed && !mobileOpen)" style="padding-left: 12px;">
            <template v-for="(child, ci) in item.children" :key="ci">
              <Link
                v-if="!('children' in child)"
                :href="child.to"
                class="nav-item"
                :class="{ 'nav-item--active': isActive(child.to) }"
              >
                <VIcon icon="tabler-circle" size="10" class="nav-item-icon" />
                <span class="nav-item-title">{{ child.title }}</span>
              </Link>
            </template>
          </div>
        </template>

        <!-- Nav Link -->
        <Link
          v-else
          :href="item.to"
          class="nav-item"
          :class="{ 'nav-item--active': isActive(item.to) }"
        >
          <VIcon v-if="item.icon" :icon="item.icon" class="nav-item-icon" size="22" />
          <span class="nav-item-title">{{ item.title }}</span>
          <VChip
            v-if="item.badgeContent"
            size="x-small"
            :color="item.badgeClass || 'primary'"
            class="nav-item-badge nav-item-title"
          >
            {{ item.badgeContent }}
          </VChip>
        </Link>
      </template>
    </nav>
  </aside>
</template>
