<script setup>
import { AnimatePresence, motion } from 'motion-v'
import { Check, ChevronDown, FileText, Globe, Menu, User, X } from 'lucide-vue-next'
import { PUBLIC_LOCALES } from '~/utils/public-locales'
import { buildRentSearchRoute } from '~/utils/public-routes'
const props = defineProps({
  theme: {
    type: String,
    default: 'light',
  },
})

const route = useRoute()
const prefRef = ref(null)
const showPrefsDropdown = ref(false)
const { hasActiveRequest, showRequestDetails } = useRequestOverlay()
const { currency } = usePublicPreferences()
const { locale, localeCode, localizedPath, pathWithoutLocale, switchLocale } = usePublicLocale()
const ui = usePublicUi()
const isDark = computed(() => props.theme === 'dark')

const languages = PUBLIC_LOCALES

const currencies = [
  { code: 'USD', symbol: '$' },
  { code: 'EUR', symbol: '€' },
  { code: 'GEL', symbol: '₾' },
]

const activeLang = computed(() => localeCode.value)
const showMobileMenu = ref(false)

const activeCurr = computed({
  get: () => currency.value || 'USD',
  set: (value) => {
    currency.value = value
  },
})

const navItems = computed(() => [
  { to: buildRentSearchRoute({}, { locale: locale.value }), label: ui.value.header.nav.rent, active: pathWithoutLocale.value === '/rent' || pathWithoutLocale.value.startsWith('/rent/') },
  { to: localizedPath('/vehicles'), label: ui.value.header.nav.vehicles, active: pathWithoutLocale.value === '/vehicles' || pathWithoutLocale.value.startsWith('/vehicles/') },
  { to: localizedPath('/locations'), label: ui.value.header.nav.locations, active: pathWithoutLocale.value === '/locations' },
  { to: localizedPath('/offers'), label: ui.value.header.nav.offers, active: pathWithoutLocale.value === '/offers' || pathWithoutLocale.value.startsWith('/offers/') },
  { to: localizedPath('/services'), label: ui.value.header.nav.services, active: pathWithoutLocale.value === '/services' },
  { to: localizedPath('/contact'), label: ui.value.header.nav.contact, active: pathWithoutLocale.value === '/contact' },
])

const headerClass = computed(() => {
  return [
    'w-full max-w-6xl mx-auto px-4 sm:px-6 py-4 flex items-center justify-between rounded-3xl mt-4 relative z-50 transition-[background-color,border-color,box-shadow] duration-300',
    isDark.value
      ? 'bg-white/8 backdrop-blur-2xl border border-white/10 shadow-[0_20px_40px_-20px_rgba(0,0,0,0.55)]'
      : 'bg-white/60 backdrop-blur-2xl border border-white/40 shadow-sm',
  ]
})

const logoClass = computed(() => {
  return isDark.value ? 'text-white' : 'text-slate-900'
})

const navInactiveClass = computed(() => {
  return isDark.value ? 'text-white/60 hover:text-white' : 'text-slate-500 hover:text-brand-orange'
})

const activeRequestClass = computed(() => {
  return isDark.value
    ? 'hidden md:flex items-center gap-2 bg-emerald-500/10 text-emerald-300 border border-emerald-400/20 hover:bg-emerald-500/15 px-4 py-2 rounded-full transition-all duration-300 shadow-sm'
    : 'hidden md:flex items-center gap-2 bg-emerald-50 text-emerald-600 border border-emerald-200 hover:bg-emerald-100 px-4 py-2 rounded-full transition-all duration-300 shadow-sm'
})

const manageClass = computed(() => {
  return isDark.value
    ? 'hidden md:flex items-center gap-2 bg-white/10 text-white hover:bg-brand-orange hover:text-white px-4 py-2 rounded-full transition-all duration-300 border border-white/10'
    : 'hidden md:flex items-center gap-2 bg-brand-orange/10 text-brand-orange hover:bg-brand-orange hover:text-white px-4 py-2 rounded-full transition-all duration-300'
})

const preferencesWrapperClass = computed(() => {
  return isDark.value
    ? 'flex items-center gap-4 md:gap-5 md:border-l border-white/10 md:pl-6 relative'
    : 'flex items-center gap-4 md:gap-5 md:border-l border-white/30 md:pl-6 relative'
})

const preferencesButtonClass = computed(() => {
  if (isDark.value) {
    return showPrefsDropdown.value
      ? 'flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all duration-300 font-bold text-xs tracking-wider bg-white/10 text-white'
      : 'flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all duration-300 font-bold text-xs tracking-wider text-white/70 hover:bg-white/10 hover:text-white'
  }

  return showPrefsDropdown.value
    ? 'flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all duration-300 font-bold text-xs tracking-wider bg-slate-100 text-slate-900'
    : 'flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-all duration-300 font-bold text-xs tracking-wider text-slate-600 hover:bg-slate-50 hover:text-brand-orange'
})

const mobileMenuClass = computed(() => {
  return isDark.value
    ? 'md:hidden flex items-center text-white hover:text-brand-orange transition-colors duration-300 ml-2'
    : 'md:hidden flex items-center text-slate-900 hover:text-brand-orange transition-colors duration-300 ml-2'
})

async function handleLanguageSelect(targetLocale) {
  showPrefsDropdown.value = false
  showMobileMenu.value = false
  await switchLocale(targetLocale)
}

function handleClickOutside(event) {
  const prefElement = prefRef.value?.$el || prefRef.value

  if (prefElement && typeof prefElement.contains === 'function' && !prefElement.contains(event.target)) {
    showPrefsDropdown.value = false
  }
}

onMounted(() => {
  document.addEventListener('mousedown', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside)
})

watch(
  () => route.fullPath,
  () => {
    showMobileMenu.value = false
    showPrefsDropdown.value = false
  },
)
</script>

<template>
  <header :class="headerClass">
    <div class="flex items-center gap-8 lg:gap-12">
      <NuxtLink :to="localizedPath('/')" :class="['text-3xl font-display font-semibold tracking-tight flex items-center gap-1 transition-colors duration-300', logoClass]">
        bent<span class="text-brand-orange">.</span>
      </NuxtLink>

      <nav class="hidden lg:flex items-center gap-5 xl:gap-8 font-display font-medium text-xs tracking-wider uppercase">
        <NuxtLink
          v-for="item in navItems"
          :key="item.to"
          :to="item.to"
          :class="[
            'relative transition-colors duration-300',
            item.active ? 'text-brand-orange' : navInactiveClass,
          ]"
        >
          <span>
            <span>{{ item.label }}</span>
          </span>
          <span
            v-if="item.active"
            class="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-4 h-[2px] bg-brand-orange rounded-full"
          />
        </NuxtLink>
      </nav>
    </div>

    <div class="flex items-center gap-4 md:gap-6 font-display font-medium text-xs tracking-wider uppercase">
      <AnimatePresence>
        <motion.button
          v-if="hasActiveRequest"
          :initial="{ opacity: 0, scale: 0.9, x: 20 }"
          :animate="{ opacity: 1, scale: 1, x: 0 }"
          :exit="{ opacity: 0, scale: 0.9, x: 20 }"
          :class="activeRequestClass"
          @click="showRequestDetails = true"
        >
          <FileText class="w-3.5 h-3.5" :stroke-width="2.5" />
          <span class="flex items-center gap-2">
            {{ ui.header.activeRequest }}
            <span class="flex h-2 w-2 relative">
              <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
              <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
            </span>
          </span>
        </motion.button>
      </AnimatePresence>

      <NuxtLink :to="localizedPath('/manage')" :class="manageClass">
        <User class="w-3.5 h-3.5" :stroke-width="2.5" />
        {{ ui.header.manageBookings }}
      </NuxtLink>

      <div :class="preferencesWrapperClass">
        <div ref="prefRef" class="relative">
          <button
            :class="preferencesButtonClass"
            @click="showPrefsDropdown = !showPrefsDropdown"
          >
            <Globe class="w-4 h-4" :stroke-width="2" />
            <span class="hidden sm:inline">{{ activeLang }} · {{ activeCurr }}</span>
            <ChevronDown :class="['w-3 h-3 transition-transform duration-300', showPrefsDropdown ? 'rotate-180' : '']" />
          </button>

          <AnimatePresence>
            <motion.div
              v-if="showPrefsDropdown"
              :initial="{ opacity: 0, y: 10, scale: 0.95 }"
              :animate="{ opacity: 1, y: 0, scale: 1 }"
              :exit="{ opacity: 0, y: 10, scale: 0.95 }"
              :transition="{ duration: 0.2 }"
              class="absolute top-full right-0 mt-3 w-56 bg-white/95 backdrop-blur-2xl border border-white/60 shadow-[0_20px_40px_-15px_rgba(0,0,0,0.1)] rounded-[1.5rem] p-2 z-50 flex flex-col"
            >
              <div class="mb-1">
                <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-3 py-2">{{ ui.header.language }}</div>
                <div class="flex flex-col gap-0.5">
                  <button
                    v-for="lang in languages"
                    :key="lang.locale"
                    :class="[
                      'flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium transition-all',
                      activeLang === lang.code ? 'bg-brand-orange/10 text-brand-orange' : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
                    ]"
                    @click="handleLanguageSelect(lang.locale)"
                  >
                    <span>{{ lang.name }}</span>
                    <Check v-if="activeLang === lang.code" class="w-4 h-4" />
                  </button>
                </div>
              </div>

              <div class="h-px bg-slate-100 mx-3 my-1" />

              <div>
                <div class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-3 py-2">{{ ui.header.currency }}</div>
                <div class="flex flex-col gap-0.5">
                  <button
                    v-for="entry in currencies"
                    :key="entry.code"
                    :class="[
                      'flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium transition-all',
                      activeCurr === entry.code ? 'bg-brand-orange/10 text-brand-orange' : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
                    ]"
                    @click="activeCurr = entry.code"
                  >
                    <div class="flex items-center gap-3">
                      <span :class="['w-5 text-center font-bold', activeCurr === entry.code ? 'text-brand-orange' : 'text-slate-400']">{{ entry.symbol }}</span>
                      <span>{{ ui.header.currencyNames?.[entry.code] || entry.code }}</span>
                    </div>
                    <Check v-if="activeCurr === entry.code" class="w-4 h-4" />
                  </button>
                </div>
              </div>
            </motion.div>
          </AnimatePresence>
        </div>

        <button
          :class="mobileMenuClass"
          @click.stop="showPrefsDropdown = false; showMobileMenu = !showMobileMenu"
        >
          <Menu v-if="!showMobileMenu" class="w-5 h-5" :stroke-width="2" />
          <X v-else class="w-5 h-5" :stroke-width="2" />
        </button>
      </div>
    </div>

    <div
      v-if="showMobileMenu"
      @click.stop
      :class="[
        'absolute top-[calc(100%+0.75rem)] inset-x-4 rounded-3xl p-4 shadow-xl border z-[70] md:hidden',
        isDark
          ? 'bg-slate-950/95 border-white/10 backdrop-blur-2xl'
          : 'bg-white/95 border-white/70 backdrop-blur-2xl',
      ]"
    >
      <nav class="flex flex-col gap-1.5 mb-3">
        <NuxtLink
          v-for="item in navItems"
          :key="`mobile-${item.to}`"
          :to="item.to"
          :class="[
            'px-3 py-2.5 rounded-xl text-sm font-semibold transition-colors',
            item.active
              ? 'bg-brand-orange/10 text-brand-orange'
              : (isDark ? 'text-white/80 hover:bg-white/10 hover:text-white' : 'text-slate-700 hover:bg-slate-100 hover:text-slate-900'),
          ]"
          @click="showMobileMenu = false"
        >
          {{ item.label }}
        </NuxtLink>
      </nav>

      <NuxtLink
        :to="localizedPath('/manage')"
        :class="[
          'w-full flex items-center justify-center gap-2 rounded-xl px-3 py-2.5 text-sm font-bold transition-colors',
          isDark ? 'bg-white/10 text-white hover:bg-brand-orange' : 'bg-brand-orange text-white hover:bg-[#E66000]',
        ]"
        @click="showMobileMenu = false"
      >
        <User class="w-4 h-4" :stroke-width="2.2" />
        {{ ui.header.manageBookings }}
      </NuxtLink>
    </div>
  </header>
</template>
