<script setup lang="ts">
import { computed } from "vue";
import { usePage, router } from "@inertiajs/vue3";
import { useNavigation } from "../composables/useNavigation";
import HorizontalTabNavigation from "./HorizontalTabNavigation.vue";
import type { NavigationItem } from "../registry";

const { normalizePath, isNavActive } = useNavigation();

const page = usePage<{ navigation?: NavigationItem[] }>();

const settingsNavItems = computed(
  () =>
    (page.props.navigation ?? []).find((i) => i.key === "settings")?.children ??
    [],
);

const isSettingsSection = computed(() =>
  settingsNavItems.value.some((i) => isNavActive(i.route, page.url)),
);

const activeKey = computed((): string => {
  let bestKey: string | null = null;
  let bestLen = -1;
  for (const item of settingsNavItems.value) {
    if (!item.route) continue;
    const routePath = normalizePath(item.route);
    const current = normalizePath(page.url);
    if (current === routePath || current.startsWith(routePath + "/")) {
      if (routePath.length > bestLen) {
        bestLen = routePath.length;
        bestKey = item.key;
      }
    }
  }
  return bestKey ?? "";
});

function navigateTo(key: string): void {
  const item = settingsNavItems.value.find((i) => i.key === key);
  if (item?.route) {
    router.visit(item.route);
  }
}
</script>

<template>
  <!-- Settings section: tab strip flanked by top and bottom border -->
  <div v-if="isSettingsSection" class="-mx-6 px-6 border-b mb-6">
    <HorizontalTabNavigation
      :model-value="activeKey"
      :tabs="settingsNavItems.map((i) => ({ key: i.key, label: i.label }))"
      @update:model-value="navigateTo"
    />
  </div>

  <!-- Other pages: just a separator line -->
  <div v-else class="-mx-6 border-t mb-6" />
</template>
