<template>
  <SideBar
    :items="filteredNavItems"
    v-model:drawer="drawer"
    :rail="rail"
    @toggle-rail="rail = !rail"
  />

  <v-main app>
    <slot />
  </v-main>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useLocalStorage } from "@vueuse/core";
import SideBar from "../components/layout/SideBar.vue";
// Ensure this path matches your store location
import { useNavItemsStore } from '~/stores/navItems1'; 
import { useAuth } from "~/composables/useAuth";
import { usePermissionStore } from '~/stores/permissionStore';

// State for controlling the sidebar
const drawer = ref(true);
const rail = ref(true);

const navItemsStore = useNavItemsStore();
const permissionStore = usePermissionStore();
const { user, checkAuth } = useAuth();

// Navigation will be filtered via navItemsStore using the new hakAkses system

const filteredNavItems = computed(() => navItemsStore.filteredNavItems);

onMounted(async () => {
  await checkAuth();
  
  if (user.value) {
    if (!permissionStore.isLoaded) {
      const roles = [
          ...(user.value.realm_access?.roles || []),
          ...(user.value.roles || [])
      ];
      
      const groups: string[] = [];
      const rawGroups = (user.value as any).groups || [];
      rawGroups.forEach((g: string) => {
          const parts = g.split('/').filter(Boolean);
          if (parts.length > 1) {
              groups.push(parts[1]);
          } else if (parts.length === 1) {
              groups.push(parts[0]);
          }
      });
      
      const primaryRole = roles[0] || '';
      const primaryGroup = groups[0] || '';
      const username = user.value.preferred_username || user.value.email || user.value.name || '';
      
      await permissionStore.load(primaryRole, primaryGroup, username);
    }
    await navItemsStore.refreshNavItems();
  }
});

// Watch for permissions loaded state to refresh navItems (fixes empty sidebar on F5)
watch(() => permissionStore.isLoaded, async (isLoaded) => {
  if (isLoaded && user.value) {
    await navItemsStore.refreshNavItems();
  }
}, { immediate: true });

// Watch for user changes to refresh navItems
watch(() => user.value, async (newUser) => {
  if (newUser && permissionStore.isLoaded) {
    await navItemsStore.refreshNavItems();
  } else if (!newUser) {
    // Optionally reset navItems when logged out
    navItemsStore.filteredNavItems = [];
  }
}, { deep: true });
</script>

<style scoped>
/* Global styles for layout */
</style>