<script setup>
import { computed } from "vue";
import AppMenuItem from "./AppMenuItem.vue";
import { useLayout } from "../composables/layout/layout.js";
import { useNavigation } from "../composables/useNavigation.js";

const { menu, loaded } = useNavigation();
const { shouldCollapseSidebar } = useLayout();

// Main sidebar: root.items split into scrollable (main) and pinned bottom (e.g. Instellingen).
const allItems = computed(() => {
  if (!loaded.value || !menu.value?.length) return [];
  const root = menu.value.find((n) => n.key === "root") ?? menu.value[0];
  if (!root) return [];
  return root.key === "root" ? (root.items ?? []) : (menu.value ?? []);
});

const mainItems = computed(() =>
  allItems.value.filter((item) => !item.pinnedBottom),
);
const pinnedItems = computed(() =>
  allItems.value.filter((item) => item.pinnedBottom),
);
</script>

<template>
  <div class="flex flex-col h-full overflow-hidden">
    <div
      class="sidebar-scroll flex-1 overflow-y-auto overflow-x-hidden min-h-0"
      :class="shouldCollapseSidebar ? 'pr-3' : 'pr-2'"
    >
      <ul class="layout-menu">
        <template
          v-for="(item, index) in mainItems"
          :key="item.key || item.label + '_' + (item.to || item.path || index)"
        >
          <li
            v-if="item.header && !shouldCollapseSidebar"
            class="layout-root-menuitem mt-4 first:mt-0"
          >
            <div class="layout-menu-section-header">
              {{ item.label }}
            </div>
          </li>
          <AppMenuItem
            v-else-if="!item.header"
            :item="item"
            :index="index"
            :root="true"
            :top-level-only="true"
          />
        </template>
      </ul>
    </div>
    <div v-if="pinnedItems.length" class="shrink-0 pt-2">
      <div class="border-t border-white/10 my-2" aria-hidden="true" />
      <ul class="layout-menu">
        <AppMenuItem
          v-for="(item, index) in pinnedItems"
          :key="item.key || item.label + '_' + (item.to || index)"
          :item="item"
          :index="index"
          :root="true"
          :top-level-only="true"
        />
      </ul>
    </div>
  </div>
</template>

<style scoped>
.sidebar-scroll {
  scrollbar-gutter: stable;
}
</style>
