<template>
  <div class="header-profile">
    <div class="b-menu-profile menu-have-sub" @click="ProfileMenu">
      <div class="profile-photo-c">
        <img
          :src="
            usersStore.profilePhoto !== '' && usersStore.profilePhoto !== null
              ? dataStore.siteBase + usersStore.profilePhoto
              : profilePhoto
          " />
      </div>
    </div>
    <nav
      id="profilemenu"
      class="menu-header menu-sub menu-sub-top menu-profile"
      v-if="globalStore.profileMenu">
      <ul>
        <li>
          <div>
            <span>Merhaba,</span>
            <strong>{{ usersStore.userName }}</strong>
          </div>
        </li>
        <li>
          <RouterLink to="/profil" @click="globalStore.profileMenu = false">
            <i class="ico-c ico-menu-profile">
              <svg>
                <use href="@/assets/images/icons.svg#profile"></use>
              </svg>
            </i>
            Profil
          </RouterLink>
        </li>
        <li>
          <a href="#" @click="LogOut">
            <i class="ico-c ico-menu-profile">
              <svg>
                <use href="@/assets/images/icons.svg#logout"></use>
              </svg>
            </i>
            <span>Çıkış</span>
          </a>
        </li>
      </ul>
    </nav>
  </div>
</template>
<script setup lang="ts">
  import { onBeforeMount } from 'vue'
  import profilePhoto from '@/assets/images/empty-user.png'

  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()
  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { useUsersStore } from '@/stores/usersStore'
  const usersStore = useUsersStore()
  import router from '@/router'

  const ProfileMenu = () => {
    globalStore.notificationPanel = false
    globalStore.profileMenu = !globalStore.profileMenu
    setTimeout(() => {
      document.addEventListener('click', closeProfileMenu)
    }, 10)
  }
  const LogOut = async () => {
    globalStore.profileMenu = false
    const token = sessionStorage.getItem(usersStore.userStorageKeys.TOKEN)
    if (token) {
      let dt = await dataStore.dataPost('Auth/logout')
    }
    usersStore.ResetUserData()
    router.push('/login')
  }

  const closeProfileMenu = (e: Event) => {
    let p = e.composedPath && e.composedPath()
    var open = false
    if (p) {
      p.pop()
      p.forEach((pv) => {
        if (
          (pv as HTMLElement).id !== '' &&
          (pv as HTMLElement).id !== undefined &&
          (pv as HTMLElement).id.includes('profilemenu')
        )
          open = true
      })
    }
    if (!open) {
      globalStore.profileMenu = false
      document.removeEventListener('click', closeProfileMenu)
    }
  }

  onBeforeMount(async () => {
    let dt = await dataStore.dataGet('AppUserResim/AppUserId/' + usersStore.userId)
    if (dt !== 'errorfalse') {
      usersStore.profilePhoto = dt.filePath
    }
  })
</script>
