﻿<template>
  <header
      class="py-1 flex items-center justify-between bg-white shadow-md shadow-gray-700 z-20"
      @click.stop
  >
    <div class="flex items-center">
      <v-app-bar-nav-icon @click.stop="sideBarStore.toggle()">
      </v-app-bar-nav-icon>

      <RouterLink to="/">
        <v-img
            src="/medias/hutopy.png"
            ref="popupButtonRef"
            alt="Hutopy Logo"
            class="mr-2 h-10 w-20"
        ></v-img>
      </RouterLink>
      
    </div>

    <!-- Spacer to push the Explorer button to the center -->
    <div class="flex-grow"></div>


    <!-- FEED -->
    <v-btn
        variant="plain"
        icon
        class="flex flex-row justify-center"
        @click="explorerHandler"
    >
      <v-icon>mdi-television</v-icon>
    </v-btn>

    <!-- Explorer Button -->
    <v-btn
        variant="plain"
        icon
        class="flex flex-row justify-center"
        @click="explorerHandler"
    >
      <v-icon>mdi-earth</v-icon>
    </v-btn>


    <!-- Spacer to keep the search bar to the right -->
    <div class="flex-grow"></div>

    <div class="flex items-center ml-auto space-x-4 search-container">
      <template v-if="showSearch">
        <v-text-field
            density="compact"
            rounded
            variant="outlined"
            v-model="searchQuery"
            placeholder="Recherche"
            hide-details
            clearable
            class="rounded-full w-32 md:w-64 lg:w-96 mx-2"
            append-inner-icon="mdi-magnify"
            @click.stop
            @click:append-inner="onSearch"
            @keyup.enter="onSearch"
        >
        </v-text-field>
      </template>
      <template v-else>
        <v-icon class="mx-2 cursor-pointer" @click.stop="toggleSearch">mdi-magnify</v-icon>
      </template>

      <v-icon class="mx-2">mdi-bell-outline</v-icon>

      <v-btn variant="text"  @click="changeLanguage('fr')">Français</v-btn>
      <v-btn variant="text" class="mx-2" @click="changeLanguage('en')">English</v-btn>

      <div class="text-center">
        <v-menu open-on-hover>
          <template v-slot:activator="{ props }">
            <div v-bind="props" class="flex align-center font-sans py-1 px-4 rounded-lg hover:bg-gray-100">
              <span class="max-w-xs hidden md:block">
                {{ userStore.alias }}
              </span>
              <img
                  :src="userStore.portraitUrl"
                  alt="Profile Image"
                  class="ml-2 rounded-full"
                  width="32"
                  height="32">
            </div>
          </template>

          <v-list min-width="200px" class="align-center mt-3 left-3">

            <template v-if="!authStore.isAuthenticated">
              <v-list-item class="nav-button">
                <v-list-item-title>
                  <v-btn to="/login" class="w-100" variant="plain">Connexion</v-btn>
                </v-list-item-title>
              </v-list-item>
            </template>

            <template v-else>
              <v-list-item v-if="userStore.creator && Object.keys(userStore.creator).length > 0" class="nav-button">
                <router-link :to="`/@${userStore.creator.name}`">
                  <v-btn class="w-100" variant="plain">@{{ userStore.creator.name }}</v-btn>
                </router-link>
              </v-list-item>

              <v-list-item v-if="!userStore.hasCreator" class="nav-button">
                <router-link to="/profile">
                  <v-btn class="w-100" variant="plain">Activer votre page</v-btn>
                </router-link>
              </v-list-item>

              <v-list-item class="nav-button">
                <v-list-item-title>
                  <v-btn to="/profile" class="w-100" variant="plain">Mon profil</v-btn>
                </v-list-item-title>
              </v-list-item>
              <v-list-item class="nav-button">
                <v-list-item-title>
                  <v-btn to="/wallet" class="w-100" variant="plain">Portefeuille</v-btn>
                </v-list-item-title>
              </v-list-item>
              <v-list-item class="nav-button">
                <v-list-item-title>
                  <v-btn @click="authStore.logout" class="w-100" variant="plain">Déconnexion</v-btn>
                </v-list-item-title>
              </v-list-item>
            </template>
          </v-list>
        </v-menu>
      </div>
    </div>
  </header>
</template>

<script setup>
import {ref, onBeforeUnmount, onBeforeMount} from "vue";
import {useRouter} from 'vue-router';
import {useSideBarStore} from '@/stores/sideBarStore.js';
import {useUserStore} from "@/stores/userStore.js";
import {useAuthStore} from "@/stores/authStore.js";
import { useI18n } from 'vue-i18n';

const { locale } = useI18n();
const authStore = useAuthStore()
const userStore = useUserStore()
const sideBarStore = useSideBarStore()

const router = useRouter();
const searchQuery = ref("");
const showSearch = ref(false);

let selectedLanguage = ref('fr');
initializeLocale();

const onSearch = () => {
  const query = searchQuery.value.trim();
  if (!query) {
    router.push("/browse");
  } else {
    const words = query.split(" ");
    if (words.length === 1) {
      router.push(`/@${words[0]}`);
    } else {
      router.push({name: "browse", query: {q: query}});
    }
  }
};

const toggleSearch = () => {
  showSearch.value = !showSearch.value;
};

const explorerHandler = () => {
  router.push('/explorer');
};

const handleClickOutside = (event) => {
  if (!event.target.closest('.search-container')) {
    showSearch.value = false;
  }
};

onBeforeMount(() => {
  document.addEventListener('click', handleClickOutside)
});

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

function initializeLocale(){
  const preferredLocale = localStorage.getItem('preferredLocale');
  selectedLanguage = ref(preferredLocale === null ? locale.value : preferredLocale);
  locale.value = selectedLanguage.value;
}

function changeLanguage(lang) {
  locale.value = lang;
  selectedLanguage.value = lang;
  localStorage.setItem('preferredLocale', lang);
}

</script>

<style scoped>
.search-container {
  position: relative;
}

.nav-button:hover {
  @apply bg-[#903175] text-gray-200;
}
</style>
