<script setup lang="ts">
import { useRouter } from 'vue-router';
import { useUiStore } from '../stores/ui';
import { useVocabularyStore } from '../stores/vocabulary';
import { useSiteConfig } from '../config/use-site-config';
import { useI18n } from '../i18n';
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';

const glossaristLogo = new URL('../assets/glossarist-logo.svg', import.meta.url).href;

const router = useRouter();
const ui = useUiStore();
const store = useVocabularyStore();
const { config: siteConfig, localizedTitle } = useSiteConfig();
const { locale, t, setLocale } = useI18n();
const searchInput = ref('');
const langOpen = ref(false);

const uiLanguages = computed(() => siteConfig.value?.uiLanguages || []);
const showLangSelector = computed(() => uiLanguages.value.length > 1);
const currentLangLabel = computed(() => {
  const cur = uiLanguages.value.find(l => l.code === locale.value);
  return cur?.label || locale.value.toUpperCase();
});

function doSearch() {
  const q = searchInput.value.trim();
  if (q) {
    ui.searchQuery = q;
    router.push({ name: 'search', query: { q } });
  }
}

function goHome() {
  router.push({ name: 'home' });
}

function selectLang(code: string) {
  setLocale(code);
  langOpen.value = false;
}

function closeLangOnOutside(e: MouseEvent) {
  if (langOpen.value) langOpen.value = false;
}

onMounted(() => document.addEventListener('click', closeLangOnOutside));
onBeforeUnmount(() => document.removeEventListener('click', closeLangOnOutside));
</script>

<template>
  <header class="bg-surface-raised border-b border-ink-100/80 z-30 relative">
    <div class="px-4 lg:px-5 h-14 flex items-center gap-3">
      <!-- Mobile hamburger -->
      <button
        @click="ui.toggleSidebar()"
        :aria-label="ui.sidebarOpen ? 'Close navigation menu' : 'Open navigation menu'"
        class="lg:hidden p-2 -ml-1 rounded-lg text-ink-600 hover:bg-ink-50 transition-colors flex-shrink-0"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 6h16M4 12h16M4 18h16"/>
        </svg>
      </button>

      <!-- Logo -->
      <button @click="goHome" class="flex items-center gap-2 hover:opacity-80 transition flex-shrink-0 group">
        <div v-if="siteConfig?.branding?.logo" class="h-8 flex items-center">
          <img
            v-if="siteConfig.branding.logo.light && siteConfig.branding.logo.dark"
            :src="ui.isDark ? siteConfig.branding.logo.dark : siteConfig.branding.logo.light"
            :alt="siteConfig.branding.logo.alt"
            class="h-8 max-w-[48px] object-contain rounded"
          />
          <img
            v-else
            :src="siteConfig.branding.logo.path"
            :alt="siteConfig.branding.logo.alt"
            class="h-8 max-w-[48px] object-contain rounded"
          />
        </div>
        <div v-else class="h-8 flex items-center">
          <img :src="glossaristLogo" alt="Glossarist" class="h-8 max-w-[48px] object-contain rounded" />
        </div>
        <span class="font-serif text-lg text-ink-800 leading-none hidden sm:inline">{{ localizedTitle }}</span>
      </button>

      <!-- Search -->
      <form @submit.prevent="doSearch" class="flex-1 max-w-lg mx-2 sm:mx-4">
        <div class="relative">
          <input
            v-model="searchInput"
            type="text"
            :aria-label="t('search.conceptSearch')"
            :placeholder="t('search.placeholder')"
            class="w-full pl-9 pr-3 py-2 text-sm bg-surface border border-ink-100 rounded-lg focus:ring-2 focus:ring-ink-200 focus:border-ink-400 outline-none placeholder:text-ink-300 transition-all"
          />
          <svg class="absolute left-3 top-2.5 w-4 h-4 text-ink-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
          </svg>
        </div>
      </form>

      <!-- Stats -->
      <div class="text-xs text-ink-400 flex-shrink-0 hidden md:block">
        {{ store.datasetList.length }} {{ t('header.datasets') }}
      </div>

      <!-- Language selector -->
      <div v-if="showLangSelector" class="relative flex-shrink-0" @click.stop>
        <button
          @click="langOpen = !langOpen"
          class="px-2.5 py-1 rounded-lg text-xs font-semibold text-ink-500 hover:text-ink-700 hover:bg-ink-50 transition-colors border border-ink-100 flex items-center gap-1"
        >
          {{ currentLangLabel }}
          <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
        </button>
        <div v-if="langOpen" class="absolute right-0 top-full mt-1 bg-surface-raised border border-ink-100 rounded-lg shadow-lg py-1 min-w-[120px] z-50">
          <button
            v-for="lang in uiLanguages"
            :key="lang.code"
            @click="selectLang(lang.code)"
            class="w-full text-left px-3 py-1.5 text-sm transition-colors"
            :class="locale === lang.code ? 'bg-ink-50 text-ink-800 font-medium' : 'text-ink-600 hover:bg-ink-50'"
          >{{ lang.label }}</button>
        </div>
      </div>

      <!-- Theme toggle -->
      <button
        @click="ui.toggleTheme()"
        :aria-label="ui.isDark ? 'Switch to light mode' : 'Switch to dark mode'"
        class="p-2 rounded-lg text-ink-400 hover:text-ink-600 hover:bg-ink-50 transition-colors flex-shrink-0"
      >
        <!-- Sun icon (shown in dark mode) -->
        <svg v-if="ui.isDark" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"/>
        </svg>
        <!-- Moon icon (shown in light mode) -->
        <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"/>
        </svg>
      </button>
    </div>
  </header>
</template>
