<template>
  <header class="fixed top-0 left-0 right-0 z-50 bg-white/70 backdrop-blur-xl border-b border-black/[0.04]">
    <div class="container mx-auto px-4">
      <div class="flex items-center justify-between h-14 lg:h-16">
        <!-- Logo -->
        <RouterLink :to="{ name: 'home', params: { lang: activeLang } }"><Logo /></RouterLink>

        <!-- Desktop Nav -->
        <nav class="hidden lg:flex items-center gap-8">
          <component
            v-for="link in navLinks"
            :key="link.href"
            :is="link.isInternal ? RouterLink : 'a'"
            v-bind="link.isInternal ? { to: link.href } : { href: link.href }"
            class="text-foreground/50 hover:text-primary transition-colors duration-300 font-bold text-[13px] tracking-tight"
          >
            {{ link.label }}
          </component>
        </nav>

        <!-- Right controls -->
        <div class="flex items-center gap-2">
          <div class="hidden lg:flex items-center gap-2">
          <RouterLink
            v-if="isAdmin"
            :to="{ name: 'admin', params: { lang: activeLang } }"
            class="inline-flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-primary hover:bg-primary/10 rounded-lg transition-colors cursor-pointer"
          >
            <LayoutPanelTop class="w-4 h-4" />
            {{ t("nav.admin") }}
          </RouterLink>

          <!-- Unread Messages Badge -->
          <RouterLink
            v-if="isLoggedIn && authStore.unreadMessagesCount > 0"
            :to="isAdmin ? `/${activeLang}/admin` : `/${activeLang}/orders`"
            class="inline-flex items-center gap-1.5 px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-xs font-bold rounded-full transition-all shadow-md animate-in fade-in"
            :title="t('nav.unreadTooltip')"
          >
            <MessageSquare class="w-3.5 h-3.5 animate-pulse" />
            <span class="tabular-nums">{{ authStore.unreadMessagesCount }}</span>
          </RouterLink>

          <RouterLink
            v-if="isLoggedIn"
            :to="{ name: 'orders', params: { lang: activeLang } }"
            class="inline-flex items-center gap-2 px-3 py-1.5 text-sm font-medium hover:bg-secondary rounded-lg transition-colors cursor-pointer"
          >
            <PackageCheck class="w-4 h-4" />
            {{ t("nav.myOrders") }}
          </RouterLink>

          <template v-if="isLoggedIn">
            <Button variant="ghost" size="sm" class="group" @click="handleLogout">
              <LogOut class="w-4 h-4 mr-2 group-hover:text-destructive transition-colors" />
              {{ t("nav.logOut") }}
            </Button>
          </template>
          <template v-else>
            <Button variant="ghost" size="sm" as="router-link" :to="`/${activeLang}/auth`" class="text-[13px] font-bold">
              {{ t("nav.logIn") }}
            </Button>
            <Button variant="default" size="sm" as="router-link" :to="{ name: 'auth', params: { lang: activeLang }, query: { mode: 'register' } }" class="text-[13px] font-bold shadow-md">
              {{ t("nav.register") }}
            </Button>
          </template>
          </div>

          <!-- Language Switcher visible everywhere -->
          <LanguageSwitcher />

          <!-- Hamburger -->
          <Button variant="ghost" size="icon" class="lg:hidden" @click="mobileOpen = !mobileOpen" :aria-label="t('nav.toggleMenu')">
            <X v-if="mobileOpen" class="w-5 h-5" />
            <Menu v-else class="w-5 h-5" />
          </Button>
        </div>
      </div>
    </div>

    <!-- Mobile Menu -->
    <Transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="opacity-0 -translate-y-2"
      enter-to-class="opacity-100 translate-y-0"
      leave-active-class="transition duration-150 ease-in"
      leave-from-class="opacity-100 translate-y-0"
      leave-to-class="opacity-0 -translate-y-2"
    >
      <div v-if="mobileOpen" class="lg:hidden py-4 border-t border-border/50 bg-background/95 backdrop-blur-lg">
        <nav class="container mx-auto px-4 flex flex-col gap-3">
          <component
            v-for="link in navLinks"
            :key="link.href"
            :is="link.isInternal ? RouterLink : 'a'"
            v-bind="link.isInternal ? { to: link.href } : { href: link.href }"
            class="text-muted-foreground hover:text-foreground transition-colors py-2"
            @click="mobileOpen = false"
          >
            {{ link.label }}
          </component>

          <RouterLink
            v-if="isAdmin"
            :to="{ name: 'admin', params: { lang: activeLang } }"
            class="flex items-center gap-2 text-primary py-2"
            @click="mobileOpen = false"
          >
            <LayoutPanelTop class="w-4 h-4" />{{ t("nav.adminPanel") }}
          </RouterLink>

          <RouterLink
            v-if="isLoggedIn && authStore.unreadMessagesCount > 0"
            :to="`/${activeLang}/orders`"
            class="flex items-center gap-2 text-red-500 font-bold py-2"
            @click="mobileOpen = false"
          >
            <MessageSquare class="w-4 h-4 animate-pulse" />
            {{ t("nav.unreadMessages") }} ({{ authStore.unreadMessagesCount }})
          </RouterLink>

          <RouterLink
            v-if="isLoggedIn"
            :to="{ name: 'orders', params: { lang: activeLang } }"
            class="flex items-center gap-2 text-muted-foreground hover:text-foreground py-2"
            @click="mobileOpen = false"
          >
            <PackageCheck class="w-4 h-4" />
            {{ t("nav.myOrders") }}
          </RouterLink>

          <div class="flex flex-col gap-2 pt-4 border-t border-border/50">
            <template v-if="isLoggedIn">
              <Button variant="ghost" class="justify-start" @click="handleLogout">
                <LogOut class="w-4 h-4 mr-2" />{{ t("nav.logOut") }}
              </Button>
            </template>
            <template v-else>
              <Button variant="ghost" class="justify-start" as="router-link" :to="`/${activeLang}/auth`" @click="mobileOpen = false">
                {{ t("nav.logIn") }}
              </Button>
              <Button variant="default" as="router-link" :to="{ name: 'auth', params: { lang: activeLang }, query: { mode: 'register' } }" @click="mobileOpen = false">
                {{ t("nav.register") }}
              </Button>
            </template>
          </div>
        </nav>
      </div>
    </Transition>
  </header>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { RouterLink, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { toast } from "vue-sonner";
import { Menu, X, LayoutPanelTop, LogOut, PackageCheck, MessageSquare } from "lucide-vue-next";
import Logo from "./Logo.vue";
import LanguageSwitcher from "./LanguageSwitcher.vue";
import Button from "./ui/button.vue";
import { useAuthStore } from "@/stores/auth";
import { currentLanguage } from "@/i18n";
import { useFeatureFlags } from "@/composables/useFeatureFlags";

const { t } = useI18n();
const router = useRouter();
const authStore = useAuthStore();
const flags = useFeatureFlags();
const mobileOpen = ref(false);
const activeLang = computed(() => currentLanguage() || localStorage.getItem('locale') || 'en');

const isLoggedIn = computed(() => !!authStore.user);
const isAdmin = computed(() => authStore.user?.role === "admin");

const navLinks = computed(() => {
  const links = [
    { label: t("nav.services"), href: `/${activeLang.value}/#services`, isInternal: true },
    { label: t("nav.materials"), href: `/${activeLang.value}/#materials`, isInternal: true },
    { label: t("nav.nuances"), href: `/${activeLang.value}/nuances`, isInternal: true },
    { label: t("nav.howItWorks"), href: `/${activeLang.value}/#process`, isInternal: true },
    { label: t("nav.portfolio"), href: `/${activeLang.value}/portfolio`, isInternal: true },
    { label: t("nav.philosophy"), href: `/${activeLang.value}/#philosophy`, isInternal: true },
  ];
  if (flags.is3DScanningEnabled) {
    links.splice(1, 0, { label: t("nav.scanning"), href: `/${activeLang.value}/scanning`, isInternal: true });
  }
  return links;
});

async function handleLogout() {
  const currentPath = router.currentRoute.value.path;
  await authStore.logout();
  toast.success(t("nav.loggedOut"));
  mobileOpen.value = false;
  
  if (currentPath === "/" || currentPath.startsWith("/#")) {
    window.location.reload(); // Refresh if already on home to clear all states
  } else {
    router.push("/");
  }
}
</script>
