<template>
  <header class="border-b border-neutral-200 bg-primary-500 px-3 py-2 text-white sm:px-5 sm:py-2 max-h-[60px]">
    <div class="flex h-full items-center justify-between">
      <MalioButtonIcon
        icon="mdi:menu"
        aria-label="Menu"
        variant="ghost"
        icon-size="24"
        button-class="lg:hidden text-white hover:bg-primary-600"
        @click="ui.openMobileSidebar()"
      />
      <div class="hidden items-center gap-2 lg:flex">
        <h1 class="text-lg font-bold tracking-tight">{{ appTitle }}</h1>
        <MalioButtonIcon
          icon="mdi:swap-horizontal"
          :aria-label="appTitle === 'NeauTime' ? 'Switch to Lesstime' : 'Switch to NeauTime'"
          variant="ghost"
          icon-size="18"
          button-class="text-white/60 hover:bg-primary-600 hover:text-white"
          @click="toggleTitle"
        />
      </div>
      <div class="ml-auto flex items-center gap-4 text-xl text-white sm:gap-8">
        <MalioButtonIcon
          :icon="ui.darkMode ? 'mdi:weather-sunny' : 'mdi:weather-night'"
          :aria-label="ui.darkMode ? 'Mode clair' : 'Mode sombre'"
          variant="ghost"
          icon-size="22"
          button-class="text-white/70 hover:bg-primary-600 hover:text-white"
          @click="ui.toggleDarkMode()"
        />
        <NotificationBell />
        <div class="group relative flex gap-2 sm:gap-4">
          <UserAvatar v-if="user" :user="user" size="md" class="cursor-pointer" />
          <Icon v-else name="mdi:account-circle-outline" class="self-center cursor-pointer" size="36" />
          <p class="hidden self-center cursor-pointer sm:block">{{ user?.username }}</p>
          <div class="invisible absolute right-0 top-full z-50 mt-2 w-44 rounded-md border border-neutral-200 bg-white py-1 text-sm text-neutral-800 opacity-0 shadow-lg transition-all group-hover:visible group-hover:opacity-100">
            <button
              type="button"
              class="block w-full px-3 py-2 text-left hover:bg-neutral-100"
              @click="navigateTo('/profile')"
            >
              {{ $t('profile.title') }}
            </button>
            <button
              type="button"
              class="block w-full px-3 py-2 text-left hover:bg-neutral-100"
              @click="handleLogout"
            >
              Déconnexion
            </button>
          </div>
        </div>
      </div>
    </div>
  </header>
</template>

<script setup lang="ts">
import type { UserData } from '~/services/dto/user-data'

defineProps<{
  user?: UserData
}>()

const auth = useAuthStore()
const ui = useUiStore()

const appTitle = ref(localStorage.getItem('appTitle') || 'NeauTime')

function toggleTitle() {
  appTitle.value = appTitle.value === 'NeauTime' ? 'Lesstime' : 'NeauTime'
  localStorage.setItem('appTitle', appTitle.value)
}

async function handleLogout() {
  await auth.logout()
  await navigateTo('/login')
}
</script>
