<template>
  <header class="flex h-16 shrink-0 items-center gap-2 border-b px-4">
    <!-- Sidebar Toggle -->
    <SidebarTrigger class="-ml-1" />
    <Separator orientation="vertical" class="mr-2 h-4" />
    
    <!-- Breadcrumb Navigation -->
    <Breadcrumb class="flex-1">
      <BreadcrumbList>
        <BreadcrumbItem v-for="(crumb, index) in breadcrumbs" :key="index">
          <DropdownMenu v-if="crumb.isProjectCrumb && projectsForSwitcher.length > 0">
            <DropdownMenuTrigger
              class="flex items-center gap-1 hover:text-foreground transition-colors outline-none"
              :class="{ 'font-semibold text-foreground': crumb.isActive }"
            >
              {{ crumb.label }}
              <ChevronDown class="h-3 w-3" />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
              <DropdownMenuItem v-for="project in projectsForSwitcher" :key="project.id" as-child>
                <router-link :to="`/projects/${project.id}`" class="flex items-center justify-between gap-4 w-full">
                  {{ project.name }}
                  <Check v-if="String(project.id) === projectIdParam" class="h-4 w-4 flex-shrink-0" />
                </router-link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem as-child>
                <router-link to="/projects">All Projects</router-link>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          <DropdownMenu v-else-if="crumb.isTabCrumb && projectIdParam">
            <DropdownMenuTrigger
              class="flex items-center gap-1 hover:text-foreground transition-colors outline-none"
              :class="{ 'font-semibold text-foreground': crumb.isActive }"
            >
              {{ crumb.label }}
              <ChevronDown class="h-3 w-3" />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
              <DropdownMenuItem v-for="tabItem in projectTabItems" :key="tabItem.tab" as-child>
                <router-link :to="`/projects/${projectIdParam}${tabItem.path}`" class="flex items-center justify-between gap-4 w-full">
                  {{ tabItem.label }}
                  <Check v-if="currentTab === tabItem.tab" class="h-4 w-4 flex-shrink-0" />
                </router-link>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          <BreadcrumbLink v-else-if="crumb.href" :href="crumb.href">
            {{ crumb.label }}
          </BreadcrumbLink>
          <BreadcrumbPage v-else :class="{ 'font-semibold': crumb.isActive }">
            {{ crumb.label }}
          </BreadcrumbPage>
          <BreadcrumbSeparator v-if="index < breadcrumbs.length - 1 && !isDropdownCrumb(crumb)" />
        </BreadcrumbItem>
      </BreadcrumbList>
    </Breadcrumb>

    <!-- Header Actions -->
    <div class="flex items-center gap-2">
      <!-- Theme Toggle -->
      <ThemeToggle />
      
      <!-- Notifications -->
      <NotificationCenter />

      <!-- User Menu -->
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button variant="ghost" class="relative h-10 w-10 rounded-full">
            <Avatar class="h-10 w-10">
              <AvatarImage 
                v-if="user?.avatar_url" 
                :src="getAvatarUrl(user.avatar_url, user.first_name, user.last_name)" 
              />
              <AvatarImage 
                v-else
                :src="getInitialsAvatarUrl(user.first_name, user.last_name)" 
              />
              <AvatarFallback>{{ userInitials }}</AvatarFallback>
            </Avatar>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" class="w-56">
          <DropdownMenuLabel>
            <div class="flex flex-col space-y-1">
              <p class="text-sm font-medium leading-none">{{ user?.first_name }} {{ user?.last_name }}</p>
              <p class="text-xs leading-none text-muted-foreground">{{ user?.email }}</p>
            </div>
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuItem as-child>
            <router-link to="/profile" class="flex items-center">
              <User class="mr-2 h-4 w-4" />
              Profile
            </router-link>
          </DropdownMenuItem>
          <DropdownMenuItem as-child>
            <router-link to="/settings" class="flex items-center">
              <Settings class="mr-2 h-4 w-4" />
              Settings
            </router-link>
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem @click="handleLogout" class="text-destructive">
            <LogOut class="mr-2 h-4 w-4" />
            Log out
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  </header>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { SidebarTrigger } from '@/components/ui/sidebar'
import { Separator } from '@/components/ui/separator'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb'
import { User, Settings, LogOut, ChevronDown, Check } from 'lucide-vue-next'

import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useAuthStore } from '@/stores/auth'
import { useProjectsStore } from '@/stores/projects'
import { BreadcrumbService, type BreadcrumbItem as BreadcrumbData } from '@/services/breadcrumb'
import ThemeToggle from '@/components/ui/theme/ThemeToggle.vue'
import NotificationCenter from './NotificationCenter.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const user = computed(() => authStore.user)

const userInitials = computed(() => {
  if (!user.value) return '?'
  return `${user.value.first_name.charAt(0)}${user.value.last_name.charAt(0)}`.toUpperCase()
})

import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getAvatarUrl } = useAvatarUrl()

// Generate breadcrumbs based on current route with enhanced context
const breadcrumbs = ref<BreadcrumbData[]>([])

// The current tab's breadcrumb (Overview/Shots/Assets/...) becomes a quick-nav
// dropdown instead of a plain link/label - see BreadcrumbItem.isTabCrumb.
const projectIdParam = computed(() => {
  const id = route.params.projectId
  return typeof id === 'string' ? id : Array.isArray(id) ? id[0] : null
})

const currentTab = computed(() => route.meta?.tab as string | undefined)

const projectTabItems = [
  { tab: 'overview', label: 'Overview', path: '' },
  { tab: 'shots', label: 'Shots', path: '/shots' },
  { tab: 'assets', label: 'Assets', path: '/assets' },
  { tab: 'tasks', label: 'Tasks', path: '/tasks' },
  { tab: 'schedule', label: 'Schedule', path: '/schedule' },
  { tab: 'settings', label: 'Settings', path: '/settings' }
]

// Project-name breadcrumb becomes a project-switcher dropdown - see BreadcrumbItem.isProjectCrumb.
const projectsStore = useProjectsStore()
const projectsForSwitcher = computed(() => projectsStore.projects)

onMounted(() => {
  if (projectsStore.projects.length === 0 && !projectsStore.isLoading) {
    projectsStore.fetchProjects()
  }
})

// Mirrors the v-if conditions that actually render a crumb as a dropdown,
// so the trailing ">" separator can be skipped for it.
function isDropdownCrumb(crumb: BreadcrumbData): boolean {
  if (crumb.isProjectCrumb) return projectsForSwitcher.value.length > 0
  if (crumb.isTabCrumb) return !!projectIdParam.value
  return false
}

const updateBreadcrumbs = async () => {
  try {
    breadcrumbs.value = await BreadcrumbService.generateBreadcrumbs(route)
  } catch (error) {
    console.error('Failed to generate breadcrumbs:', error)
    // Fallback to simple breadcrumbs
    const pathSegments = route.path.split('/').filter(Boolean)
    const crumbs = [{ label: 'Home', href: '/' }]
    
    let currentPath = ''
    pathSegments.forEach((segment, index) => {
      currentPath += `/${segment}`
      const isLast = index === pathSegments.length - 1
      
      const label = segment.charAt(0).toUpperCase() + segment.slice(1).replace(/-/g, ' ')
      
      crumbs.push({
        label,
        href: isLast ? undefined : currentPath,
        isActive: isLast
      })
    })
    
    breadcrumbs.value = crumbs
  }
}

// Watch for route changes to update breadcrumbs
watch(route, updateBreadcrumbs, { immediate: true })

const handleLogout = async () => {
  await authStore.logout()
  router.push('/login')
}
</script>