<script setup lang="ts">
/**
 * Primary sidebar with search, Today, timeline density rail, and
 * collapsible Pages/Tags sections sourced from the SQLite index.
 *
 * Adapts layout to the sidebar state (expanded/collapsed):
 * - **Expanded**: labels visible, Pages/Tags sections shown below timeline
 * - **Collapsed**: only icons + compact TimelineRail (dots only)
 */
interface Page {
  name: string
  displayName?: string
  backlinkCount?: number
}

interface Tag {
  name: string
  count: number
}

const props = defineProps<{
  open: boolean
  today: string
  activeDate: string
  dateKeys: string[]
  densityMap: Map<string, number>
  pages?: Page[]
  tags?: Tag[]
}>()

const emit = defineEmits<{
  "update:open": [value: boolean]
  "select-date": [date: string]
  search: []
  "page-clicked": [pageName: string]
  "tag-clicked": [tag: string]
}>()

const pagesOpen = ref(true)
const tagsOpen = ref(true)

const sortedPages = computed(() =>
  [...(props.pages ?? [])].sort((a, b) => a.name.localeCompare(b.name)),
)

const sortedTags = computed(() =>
  [...(props.tags ?? [])].sort((a, b) => b.count - a.count).slice(0, 30),
)
</script>

<template>
  <USidebar
    :open="open"
    collapsible="offcanvas"
    side="left"
    rail
    @update:open="emit('update:open', $event)"
  >
    <template #default="{ state }">
      <div class="flex flex-col h-full overflow-hidden">

        <!-- Search -->
        <div class="shrink-0 p-2">
          <UButton
            icon="i-lucide-search"
            :label="state === 'expanded' ? 'Search notes...' : undefined"
            color="neutral"
            variant="ghost"
            size="sm"
            class="w-full"
            :class="state === 'expanded' ? 'justify-start' : 'justify-center'"
            @click="emit('search')"
          />
        </div>

        <!-- Today -->
        <div class="shrink-0 px-2 pb-2">
          <UButton
            icon="i-lucide-calendar"
            :label="state === 'expanded' ? 'Today' : undefined"
            color="neutral"
            variant="ghost"
            size="sm"
            class="w-full"
            :class="[
              state === 'expanded' ? 'justify-start' : 'justify-center',
              activeDate === today ? 'bg-elevated' : '',
            ]"
            @click="emit('select-date', today)"
          />
        </div>

        <USeparator />

        <!-- Timeline — scrollable, takes remaining space -->
        <div class="flex-1 overflow-y-auto min-h-0 py-2">
          <TimelineRail
            :days="dateKeys"
            :active-date="activeDate"
            :density-map="densityMap"
            :compact="state === 'collapsed'"
            @select="emit('select-date', $event)"
          />
        </div>

        <!-- Pages + Tags — only meaningful when expanded -->
        <div v-if="state === 'expanded'" class="shrink-0">
          <USeparator />

          <div class="overflow-y-auto max-h-64 py-2 space-y-0.5">

            <!-- Pages -->
            <UCollapsible v-if="sortedPages.length > 0" v-model:open="pagesOpen">
              <button
                class="flex items-center gap-2 w-full px-3 py-1.5 rounded-md
                       text-xs font-medium text-muted hover:text-default
                       hover:bg-elevated transition-colors"
              >
                <UIcon name="i-lucide-file-text" class="w-3.5 h-3.5 shrink-0" />
                <span class="flex-1 text-left">Pages</span>
                <span class="text-muted/50 tabular-nums">{{ sortedPages.length }}</span>
                <UIcon
                  name="i-lucide-chevron-right"
                  class="w-3 h-3 shrink-0 transition-transform duration-150"
                  :class="{ 'rotate-90': pagesOpen }"
                />
              </button>

              <template #content>
                <ul class="mt-0.5 space-y-0.5">
                  <li v-for="page in sortedPages" :key="page.name">
                    <button
                      class="flex items-center gap-2 w-full px-3 py-1.5 rounded-md
                             text-sm text-muted hover:text-default hover:bg-elevated
                             transition-colors text-left group"
                      @click="emit('page-clicked', page.name)"
                    >
                      <UIcon name="i-lucide-file-text" class="w-3.5 h-3.5 shrink-0 opacity-50" />
                      <span class="flex-1 truncate">{{ page.displayName || page.name }}</span>
                      <span
                        v-if="page.backlinkCount"
                        class="text-xs text-muted/40 tabular-nums
                               opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        {{ page.backlinkCount }}
                      </span>
                    </button>
                  </li>
                </ul>
              </template>
            </UCollapsible>

            <!-- Tags -->
            <UCollapsible v-if="sortedTags.length > 0" v-model:open="tagsOpen">
              <button
                class="flex items-center gap-2 w-full px-3 py-1.5 rounded-md
                       text-xs font-medium text-muted hover:text-default
                       hover:bg-elevated transition-colors"
              >
                <UIcon name="i-lucide-hash" class="w-3.5 h-3.5 shrink-0" />
                <span class="flex-1 text-left">Tags</span>
                <span class="text-muted/50 tabular-nums">{{ sortedTags.length }}</span>
                <UIcon
                  name="i-lucide-chevron-right"
                  class="w-3 h-3 shrink-0 transition-transform duration-150"
                  :class="{ 'rotate-90': tagsOpen }"
                />
              </button>

              <template #content>
                <ul class="mt-0.5 space-y-0.5">
                  <li v-for="tag in sortedTags" :key="tag.name">
                    <button
                      class="flex items-center gap-2 w-full px-3 py-1.5 rounded-md
                             text-sm text-muted hover:text-default hover:bg-elevated
                             transition-colors text-left group"
                      @click="emit('tag-clicked', tag.name)"
                    >
                      <UIcon name="i-lucide-hash" class="w-3.5 h-3.5 shrink-0 opacity-50" />
                      <span class="flex-1 truncate">{{ tag.name }}</span>
                      <span
                        class="text-xs text-muted/40 tabular-nums
                               opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        {{ tag.count }}
                      </span>
                    </button>
                  </li>
                </ul>
              </template>
            </UCollapsible>
          </div>
        </div>
      </div>
    </template>
  </USidebar>
</template>
