// stores/navItems.ts
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';
import { computed, ref } from 'vue'; // Import computed dari Vue
import { useHakAkses } from '~/composables/useHakAkses';

interface NavItem {
  id: number;
  name: string; // Menggantikan 'title'
  path: string; // Menggantikan 'to'
  icon: string;
  children?: NavItem[];
  badge?: string; // Tambahkan properti badge
}

// Initial default navigation items
const defaultNavItems: NavItem[] = [
  { id: 1, name: "Dashboard", icon: "mdi-view-dashboard", path: "/dashboard" },
  { id: 2, name: "Verifikasi Akun", icon: "mdi-account-check-outline", path:"/verifikasiAkun/VerifikasiAkun" },
  { 
    id: 3, 
    name: "Check In", 
    icon: "mdi-file-document-edit-outline", 
    path: "/CheckInPasien/checkIn"
    // badge: "3", 
  },
  { id: 4, name: "Admin Loket", icon: "mdi-account-supervisor-outline", path: "/AdminLoket" },
  { id: 6, name: "Admin Klinik Ruang", icon: "mdi-door-open", path: "/AdminKlinikRuang" },
  // { id: 7, name: "Admin Penunjang", icon: "mdi-plus-box-outline", path: "/AdminPenunjang" },
  // { id: 8, name: "Buat Antrean", icon: "mdi-account-multiple-plus-outline", path: "/BuatAntrean" },
  { id: 9, name: "Monitoring Pasien", icon: "mdi-account-group-outline", path: "/MonitoringPasien/monitoringPasien" },
  {
    id: 10,
    name: "Layar Informasi",
    icon: "mdi-monitor-multiple",
    path: "",
    children: [
      // { id: 10, name: "Anjungan", path: "/Anjungan/Anjungan", icon: "mdi-circle-small" },
      { id: 11, name: "Anjungan", path: "/anjungan/anjungancopy", icon: "mdi-circle-small" },
      // { id: 11, name: "Klinik", path: "/Anjungan/AntrianKlinik", icon: "mdi-circle-small" },
      { id: 12, name: "Klinik Ruang", path: "/Anjungan/AntrianKlinikRuang", icon: "mdi-circle-small"},
      // { id: 13, name: "Penunjang", path: "/Anjungan/AntrianPenunjang", icon: "mdi-circle-small"},
      {id: 14, name: "Loket", path: "/Anjungan/AntrianLoket", icon: "mdi-circle-small"},
      {id: 15, name: "Antrean Masuk", path: "/Anjungan/AntreanMasuk", icon: "mdi-circle-small"},

    ],
  },
    {
    id: 15,
    name: "Master Data",
    icon: "mdi-cog-outline",
    path: "",
    children: [
      { id: 16, name: "Hak Akses", path: "/Setting/HakAkses", icon: "mdi-circle-small" },
      { id: 17, name: "User Login", path: "/Setting/UserLogin", icon: "mdi-circle-small" },
      { id: 18, name: "Master Anjungan", path: "/Setting/MasterAnjungan", icon: "mdi-circle-small" },
      { id: 19, name: "Master Loket", path: "/Setting/MasterLoket", icon: "mdi-circle-small" },
      { id: 20, name: "Master Klinik", path: "/Setting/MasterKlinik", icon: "mdi-circle-small" },
      { id: 21, name: "Master Klinik Ruang", path: "/Setting/MasterKlinikRuang", icon: "mdi-circle-small" },
      // { id: 22, name: "Master Penunjang", path: "/Setting/MasterPenunjang", icon: "mdi-circle-small" },
      // { id: 23, name: "Screen", path: "/Setting/Screen", icon: "mdi-circle-small" },
      { id: 24, name: "Screen Antrean Masuk", path: "/Setting/ScreenAntreanMasuk", icon: "mdi-circle-small" },
    ],
  },
];

const STORAGE_VERSION = '1.3'; // Increment this if you change structure or default paths

export const useNavItemsStore = defineStore('navItems', () => {
  const storedVersion = useLocalStorage('navItems_version', '0');
  const navItems = useLocalStorage<NavItem[]>('navItems', defaultNavItems);

  // Force reset if version mismatch (stale paths in localStorage)
  if (storedVersion.value !== STORAGE_VERSION) {
    console.log(`🔄 Version mismatch: ${storedVersion.value} -> ${STORAGE_VERSION}. Resetting navItems...`);
    navItems.value = JSON.parse(JSON.stringify(defaultNavItems));
    storedVersion.value = STORAGE_VERSION;
  }

  // === GETTER PENTING UNTUK MENGATASI MASALAH 'NULL' DI AWAL ===
  const getNavItems = computed(() => {
    // Jika navItems.value null, undefined, atau bukan array yang valid, 
    // kembalikan array default.
    if (!Array.isArray(navItems.value) || navItems.value === null || navItems.value === undefined) {
      return defaultNavItems; 
    }
    return navItems.value;
  });
  // =============================================================

  function updateNavItems(newItems: NavItem[]) {
    navItems.value = newItems.map((item, index) => ({
      ...item,
      id: index + 1
    }));
  }

  function addNavItem(newItem: Omit<NavItem, 'id'>) {
    const newId = navItems.value.length > 0 ? Math.max(...navItems.value.map(item => item.id)) + 1 : 1;
    navItems.value.push({ ...newItem, id: newId });
  }

  // Filtered navigation items based on hakAkses
  const filteredNavItems = ref<NavItem[]>(defaultNavItems);

  async function refreshNavItems() {
    const { getAllowedPages } = useHakAkses();
    const allowedPages = await getAllowedPages();
    
    if (allowedPages.length === 0) {
       // If no hak akses defined (maybe new system not setup yet), 
       // keep default or clear? Let's keep for now for safety during transition
       filteredNavItems.value = defaultNavItems;
       return;
    }

    const filterItems = (items: NavItem[]): NavItem[] => {
      return items.filter(item => {
        // If it's a parent with no path, check if any children are allowed
        if (!item.path && item.children) {
          const allowedChildren = filterItems(item.children);
          if (allowedChildren.length > 0) {
            item.children = allowedChildren;
            return true;
          }
          return false;
        }
        
        // If it's a child or leaf, check if path is in allowedPages
        return allowedPages.includes(item.path);
      });
    };

    filteredNavItems.value = filterItems(JSON.parse(JSON.stringify(defaultNavItems)));
  }

  return {
    navItems,
    getNavItems, // Diekspor untuk digunakan di Sidebar
    filteredNavItems,
    refreshNavItems,
    updateNavItems,
    addNavItem,
  };
});