<script setup lang="ts">
import { inject, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { RouterView } from 'vue-router'
import { storeToRefs } from 'pinia'

import { useAuthStore } from '@/stores/auth'
import { AuthenticationService } from '@/services/AuthenticationService'
import { emit, listen } from '@tauri-apps/api/event'
import profileStubImage from '@/assets/images/profile-stub.png'

const authStore = useAuthStore()
const router = useRouter()
const userProfileMenuActive = ref(false)
const profileMenu = ref<HTMLElement | null>(null)
const { user } = storeToRefs(authStore)
const authService = inject<AuthenticationService>('auth')
const info: any = inject('info')

const props = defineProps({
  navbar: Boolean,
})

defineOptions({
  name: 'AuthenticatedLayout',
})

function logout() {
  authService?.logout()
  router.push({ name: 'landing' })
}

function toggleProfileMenu() {
  userProfileMenuActive.value = !userProfileMenuActive.value
  if (userProfileMenuActive.value) {
    addClickOutsideListener()
  } else {
    removeClickOutsideListener()
  }
}

function addClickOutsideListener() {
  document.addEventListener('click', closeProfileMenu)
}

function removeClickOutsideListener() {
  document.removeEventListener('click', closeProfileMenu)
}

function closeProfileMenu(event: any) {
  console.log('profileMenu.value :>> ', profileMenu.value)
  if (profileMenu.value !== null && !profileMenu.value.contains(event.target)) {
    userProfileMenuActive.value = false
    removeClickOutsideListener()
  }
}

function checkForUpdates() {
  emit('tauri://update')
}

onMounted(() => {
  if (userProfileMenuActive.value) {
    addClickOutsideListener()
  }
})

onBeforeUnmount(() => {
  removeClickOutsideListener()
})

// Listen for update download progress
if (info.tauri) {
  listen('tauri://update-not-available', () => {
    userProfileMenuActive.value = false
    removeClickOutsideListener()
  })
}
const mode = import.meta.env.MODE
</script>

<template>
  <header class="container" v-if="props.navbar">
    {{ mode }} - {{ info.tauri }} - {{ info }}
    <nav class="navbar is-transparent">
      <div class="navbar-menu">
        <div class="navbar-end">
          <div
            class="navbar-item has-dropdown"
            :class="{ 'is-active': userProfileMenuActive }"
            ref="profileMenu"
            v-if="user"
          >
            <a class="navbar-link" @click.prevent="toggleProfileMenu">
              <figure class="image is-32x32">
                <img class="is-rounded" :src="profileStubImage" alt="{{ user.username }}" />
              </figure>
              <span class="ml-2">{{ user.username }}</span>
            </a>

            <div class="navbar-dropdown is-boxed is-right">
              <a class="navbar-item" @click.prevent="logout">Logout</a>
              <a class="navbar-item" @click.prevent="checkForUpdates" v-if="info.tauri"
                >Check for update</a
              >
              <hr class="navbar-divider" />
              <div class="navbar-item">Version 0.2.0</div>
            </div>
          </div>
        </div>
      </div>
    </nav>
  </header>
  <main class="container">
    <RouterView></RouterView>
  </main>
</template>

<style scoped>
/* Add styles for authenticated layout */
</style>
