<template>
  <v-card variant="outlined" class="rounded-lg overflow-hidden">
    <v-table density="compact">
      <thead>
        <tr>
          <th class="text-left font-weight-bold">Halaman</th>
          <th class="text-center font-weight-bold" style="width: 120px;">Akses</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="item in flatNavItems" :key="item.path || item.name">
          <tr :class="{ 'bg-grey-lighten-4': !item.path }">
            <td :style="{ paddingLeft: item.level * 24 + 'px' }">
              <div class="d-flex align-center">
                <v-icon :icon="item.icon" size="small" class="mr-2" color="grey"></v-icon>
                <span :class="{ 'font-weight-bold': !item.path }">{{ item.name }}</span>
              </div>
            </td>
            <td class="text-center">
              <v-checkbox
                v-if="item.path"
                :model-value="isAllowed(item.path)"
                @update:model-value="toggleAccess(item, !!$event)"
                hide-details
                density="compact"
                color="primary"
                class="d-inline-flex"
              ></v-checkbox>
              <v-icon v-else icon="mdi-folder-open" size="small" color="grey-lighten-1"></v-icon>
            </td>
          </tr>
        </template>
      </tbody>
    </v-table>
  </v-card>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useNavItemsStore } from '~/stores/navItems1';

const props = defineProps({
  pages: {
    type: Array as () => any[], // Be flexible with legacy data
    default: () => []
  }
});

const emit = defineEmits(['update:pages']);

const navItemsStore = useNavItemsStore();

interface FlatNavItem {
  name: string;
  path: string;
  icon: string;
  level: number;
}

const flatNavItems = computed(() => {
  const result: FlatNavItem[] = [];
  
  const walk = (items: any[], level = 0) => {
    items.forEach(item => {
      result.push({
        name: item.name,
        path: item.path,
        icon: item.icon,
        level
      });
      if (item.children && item.children.length > 0) {
        walk(item.children, level + 1);
      }
    });
  };
  
  walk(navItemsStore.getNavItems);
  return result;
});

const isAllowed = (path: string) => {
  if (!props.pages || !Array.isArray(props.pages)) return false;
  
  return props.pages.some(p => {
    if (typeof p === 'string') return p === path;
    if (p && typeof p === 'object' && p.path) return p.path === path;
    return false;
  });
};

const toggleAccess = (item: FlatNavItem, allowed: boolean) => {
  let newPages = [...props.pages];
  
  if (allowed) {
    if (!newPages.includes(item.path)) {
      newPages.push(item.path);
    }
  } else {
    newPages = newPages.filter(p => p !== item.path);
  }
  
  emit('update:pages', newPages);
};
</script>

<style scoped>
.bg-grey-lighten-4 {
  background-color: #f5f5f5;
}
</style>