<template>
  <div class="q-gutter-md">
    <q-btn dense flat round icon="person" :color="currentUser ? 'green' : ''">
      <q-menu ref="refLoginMenu">
        <q-list style="min-width: 120px">
          <q-item v-if="userLogin.getUser()" class="text-primary">{{
            currentUser?.username
          }}</q-item>
          <q-item v-if="showLogin" clickable v-close-popup @click="openLogin">
            <q-item-section class="text-primary">{{ loginText }}</q-item-section>
          </q-item>
          <q-item>
            <q-select
              :label="$t('language')"
              borderless
              color="primary"
              dense
              v-model="langSelected"
              :options="langSelection"
            ></q-select>
          </q-item>
          <q-item v-if="autorized">
            <q-btn flat color="secondary" icon="settings" to="/settings"></q-btn>
          </q-item>
          <q-item v-if="autorized">
            <q-btn flat color="secondary" icon="group" to="/usersSettings"></q-btn>
          </q-item>
        </q-list>
      </q-menu>
    </q-btn>
  </div>
  <LoginDialog ref="refLoginDialog"></LoginDialog>
</template>

<script setup lang="ts">
import LoginDialog from './LoginDialog.vue';
import { computed, ref, watch } from 'vue';
import { useLogin } from './useLogin';
import { useNotify } from '../general/useNotify';
import { lang, i18n } from 'src/boot/lang';
import { useUserStore } from './userStore';
import { useRoute } from 'vue-router';

const route = useRoute();
const showLogin = computed(
  () => (route.path !== '/' && route.path !== '/login') || currentUser.value?.username === '',
);

const userLogin = useLogin();
const user = useUserStore();
const autorized = computed(() => !!user.isAuthorizedAs(['admin']));
const { NotifyResponse } = useNotify();
const currentUser = computed(() => userLogin.getUser());

const loginText = computed(() => {
  return currentUser.value ? 'Logout' : 'Login';
});

const refLoginDialog = ref();

function openLogin() {
  if (currentUser.value) {
    userLogin.logout().catch((err) => NotifyResponse(err, 'error'));
    return;
  }
  refLoginDialog.value?.open();
}

const langSelected = ref(i18n.global.locale);
const langSelection = ref(lang);

// Watch for changes and update i18n locale
watch(langSelected, (newLang) => {
  i18n.global.locale = newLang;
  localStorage.setItem('lang', newLang);
});
</script>
