<script setup lang="ts">
import { activeNotesSource, availableNotesSources } from '@/composables/useNotes'
import { signOut as firebaseSignOut } from '@/composables/useFirebase'
import { OnClickOutside } from '@vueuse/components'
import { preferredNotesSource } from '@/composables/useSettings'

const sourceLabels: { [source: string]: string } = {
  local: 'Switch to local notes',
  firebase: 'Switch to cloud notes'
}

const signOut = async (close: () => Promise<boolean>) => {
  await firebaseSignOut()
  preferredNotesSource.value = null
  close()
}

const blur = () => (document.activeElement as HTMLElement)?.blur()

const handleClick = (fn: (...args: any[]) => any) => {
  blur()
  fn()
}
</script>
<template>
  <OnClickOutside>
    <div class="search-active-hide dropdown-end dropdown">
      <label tabindex="0" class="btn-outline btn-sm btn py-1 text-white">
        <i class="fa-fw fa-solid fa-user-gear" />
      </label>
      <ul
        tabindex="0"
        class="dropdown-content menu rounded-box menu-compact mt-1 w-52 bg-base-100 p-2 text-base-content shadow"
      >
        <li
          class="text-base"
          v-for="source in availableNotesSources.filter(
            (source) => source !== activeNotesSource
          )"
          :key="source"
          @click="handleClick(() => (preferredNotesSource = source))"
        >
          <a>
            <i class="fa-fw fa-solid fa-database" />
            {{ sourceLabels[source] }}
          </a>
        </li>
        <Modal>
          <template #activator="{ open }">
            <li @click="open" class="text-base">
              <a>
                <i class="fa-fw fa-solid fa-right-from-bracket" />
                Sign out
              </a>
            </li>
          </template>
          <template #title>Sign out</template>
          <template #default>
            <p>Are you sure want to signout?</p>
            <p>Your synchronized notes can't be accessed until you sign-in again.</p>
          </template>
          <template #actions="{ close }">
            <button class="btn-sm btn" @click="close">Cancel</button>
            <button class="btn-primary btn-sm btn" @click="signOut(close)">Sign out</button>
          </template>
        </Modal>
      </ul>
    </div>
  </OnClickOutside>
</template>
