<template>
  <div class="h-[60px] md:h-[125px]">
    <div class="fixed top-[20px] z-50 w-full md:top-[45px]">
      <div class="container">
        <header
          class="lucid-glass-bar flex h-[40px] items-center justify-between rounded-[90px] p-[4px] transition-all duration-300 md:h-[60px]"
        >
          <router-link
            to="/"
            class="ml-[clamp(0.25rem,2vw,0.625rem)] flex min-w-0 items-center gap-[clamp(0.25rem,1vw,0.5rem)] whitespace-nowrap md:ml-[47px]"
          >
            <Logo
              alt="Hi快VPN"
              class="h-[clamp(0.875rem,4vw,1.125rem)] w-auto shrink-0 md:h-[29px]"
            />
            <span
              class="text-[clamp(0.875rem,4.25vw,1.5rem)] leading-none font-black whitespace-nowrap md:ml-3 md:text-2xl"
            >
              高能合伙人
            </span>
          </router-link>

          <router-link
            v-if="isLoggedIn"
            to="/user-center"
            aria-label="进入用户中心"
            class="flex size-[30px] shrink-0 items-center justify-center rounded-full bg-[#78788029] text-xl font-bold text-white shadow-lg transition hover:scale-105 md:size-[40px] md:text-3xl"
          >
            {{ userLetter }}
          </router-link>
          <button
            v-else
            type="button"
            class="header-login-button flex h-[30px] shrink-0 cursor-pointer items-center justify-center rounded-full px-[clamp(0.625rem,3vw,1.5rem)] text-[clamp(0.75rem,3.2vw,0.875rem)] leading-none font-bold whitespace-nowrap transition hover:brightness-110 md:h-[50px] md:w-[220px] md:px-6 md:text-xl"
            @click="openLoginModal"
          >
            登录/注册
          </button>
        </header>
      </div>
    </div>

    <LoginFormModal ref="loginModalRef" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useLocalStorage } from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'
import LoginFormModal from '@/pages/Home/components/LoginFormModal.vue'
import Logo from '@/pages/Home/logo.svg?component'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const token = useLocalStorage('Authorization', '')
const userEmail = useLocalStorage('UserEmail', '')
const loginModalRef = ref<InstanceType<typeof LoginFormModal> | null>(null)

interface UserInfoResponse {
  auth_methods?: Array<{
    auth_type?: string
    auth_identifier?: string
  }>
}

const isLoggedIn = computed(() => !!token.value)
const userLetter = computed(() => userEmail.value?.charAt(0).toUpperCase() || '?')

const openLoginModal = () => {
  loginModalRef.value?.show()
}

const handleLoginQuery = () => {
  if (route.query.login !== 'true') return

  openLoginModal()
  router.replace({ query: { ...route.query, login: undefined } })
}

const fetchUserInfo = async () => {
  if (route.path !== '/' || !token.value) return

  try {
    const res = (await request.get('/api/v1/public/user/info')) as UserInfoResponse
    const emailInfo = res.auth_methods?.find((item) => item.auth_type === 'email')
    if (emailInfo?.auth_identifier) userEmail.value = emailInfo.auth_identifier
  } catch (error: unknown) {
    console.error('Failed to fetch user info:', error)
    const status =
      typeof error === 'object' && error !== null
        ? (error as { code?: number; status?: number })
        : {}
    if (status.code === 401 || status.status === 401) {
      token.value = ''
      userEmail.value = ''
    }
  }
}

onMounted(() => {
  fetchUserInfo()
  handleLoginQuery()
})

watch(() => route.query.login, handleLoginQuery)
</script>

<style scoped>
.header-login-button {
  -webkit-appearance: none;
  appearance: none;
  border: 0;
  background: rgb(120 120 128 / 16%);
  box-shadow: none;
  -webkit-tap-highlight-color: transparent;
}

@media (min-width: 768px) {
  .header-login-button {
    -webkit-appearance: button;
    appearance: button;
    -webkit-backdrop-filter: blur(12px);
    backdrop-filter: blur(12px);
  }
}
</style>
