<script setup lang="ts">
import { ref } from "vue";
import { Head } from "@inertiajs/vue3";
import { Search } from "lucide-vue-next";
import Kbd from "../components/ui/Kbd.vue";
import { useEventListener } from "@vueuse/core";
import { useTheme } from "../composables/useTheme";
import { useFlashToast } from "../composables/useFlashToast";
import { useValidationErrorToast } from "../composables/useValidationErrorToast";
import { useBreadcrumbs } from "../composables/useBreadcrumbs";
import Toaster from "../components/ui/Sonner.vue";
import AppSidebar from "../components/AppSidebar.vue";
import Breadcrumbs from "../components/Breadcrumbs.vue";
import CommandPalette from "../components/CommandPalette.vue";
import SidebarInset from "../components/ui/sidebar/SidebarInset.vue";
import SidebarProvider from "../components/ui/sidebar/SidebarProvider.vue";
import SidebarTrigger from "../components/ui/sidebar/SidebarTrigger.vue";

const commandOpen = ref(false);

useEventListener(window, "keydown", (e: KeyboardEvent) => {
  if ((e.metaKey || e.ctrlKey) && e.key === "k") {
    e.preventDefault();
    commandOpen.value = !commandOpen.value;
  }
});

useTheme();
useFlashToast();
useValidationErrorToast();

const { breadcrumbs, pageTitle } = useBreadcrumbs();
</script>

<template>
  <Head :title="pageTitle" />
  <Toaster />
  <SidebarProvider>
    <CommandPalette v-model:open="commandOpen" />
    <AppSidebar />

    <SidebarInset>
      <header
        class="flex h-16 shrink-0 items-center gap-2 border-b bg-background px-4 transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12"
      >
        <SidebarTrigger />
        <div class="h-4 w-px bg-border" />
        <Breadcrumbs :crumbs="breadcrumbs" />
        <h1
          v-if="!breadcrumbs.length"
          class="text-base font-medium text-foreground"
        >
          <slot name="title" />
        </h1>
        <button
          class="ml-auto hidden h-8 w-64 items-center gap-2 rounded-md border bg-background px-3 text-sm text-muted-foreground shadow-xs hover:bg-accent md:flex"
          type="button"
          @click="commandOpen = true"
        >
          <Search class="size-3.5 shrink-0" />
          <span class="flex-1 text-left">Search...</span>
          <span class="flex items-center gap-0.5">
            <Kbd>⌘</Kbd>
            <Kbd>K</Kbd>
          </span>
        </button>
      </header>

      <div class="flex flex-1 flex-col p-6">
        <slot />
      </div>
    </SidebarInset>
  </SidebarProvider>
</template>
