<template>
  <div class="relative min-h-screen overflow-hidden bg-[#f5f5f5] px-4 py-10 font-sans text-[#0c0a09] md:px-8 md:py-16">
    <div
      class="pointer-events-none absolute left-1/2 top-8 h-[420px] w-[min(92vw,760px)] -translate-x-1/2 rounded-[48px] bg-[radial-gradient(circle_at_20%_30%,rgba(167,229,211,0.62),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(168,200,232,0.56),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(232,184,196,0.5),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full max-w-[960px] gap-8" aria-labelledby="home-title">
      <header class="flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p
            class="m-0 inline-flex rounded-full bg-[rgba(168,200,232,0.56)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Conta
          </p>
          <h1 id="home-title"
            class="my-5 max-w-[680px] font-serif text-[40px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] md:text-[48px]">
            Olá, você está autenticado!
          </h1>
          <p class="m-0 max-w-[540px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Estes são os dados retornados pelo perfil da sua sessão atual.
          </p>
        </div>

        <div class="flex flex-col gap-3 sm:flex-row">
          <NuxtLink to="/ranking-jogos"
            class="inline-flex h-10 items-center justify-center rounded-full border border-[#d6d3d1] bg-transparent px-5 text-[15px] font-medium leading-none text-[#0c0a09] transition hover:border-[#0c0a09]">
            Ver rankings
          </NuxtLink>
          <button type="button" :disabled="isLeaving" @click="sair"
            class="inline-flex h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 text-[15px] font-medium leading-none text-white transition hover:bg-[#0c0a09] active:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70">
            <Icon v-if="isLeaving" name="mdi:loading" class="animate-spin text-base" />
            <span v-else>Sair</span>
          </button>
        </div>
      </header>

      <section
        class="grid gap-5 rounded-2xl border border-[#e7e5e4] bg-white p-6 shadow-[0_4px_16px_rgba(0,0,0,0.04)] md:p-8"
        aria-label="Dados do perfil autenticado">
        <div>
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(167,229,211,0.62)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Perfil
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            Dados da conta
          </h2>
        </div>

        <dl class="grid gap-4">
          <div v-for="item in profileRows" :key="item.label"
            class="grid gap-1 border-t border-[#e7e5e4] pt-4 sm:grid-cols-[160px_minmax(0,1fr)] sm:gap-5">
            <dt class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
              {{ item.label }}
            </dt>
            <dd class="m-0 break-words text-base leading-6 tracking-[0.16px] text-[#0c0a09]">
              {{ item.value }}
            </dd>
          </div>
        </dl>
      </section>
    </main>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: 'auth'
})

const { $toast } = useNuxtApp()

const token = useCookie('token', {
  secure: true,
  sameSite: 'lax',
  maxAge: 900
})

const isLeaving = ref(false)

const clearToken = () => {
  token.value = null
}

const { data: profile, error } = await useAsyncData('profile-me', () =>
  $fetch('/profile/me', {
    headers: {
      Authorization: `Bearer ${token.value}`
    }
  })
)

if (error.value) {
  clearToken()

  if (import.meta.client) {
    $toast.error('Sua sessão expirou. Faça login novamente.', { duration: 8000 })
  }

  await navigateTo('/login')
}

const profileRows = computed(() => [
  {
    label: 'user_id',
    value: profile.value?.user_id ?? profile.value?.id ?? '-'
  },
  {
    label: 'email',
    value: profile.value?.email ?? '-'
  },
  {
    label: 'created_at',
    value: profile.value?.created_at ?? '-'
  },
  {
    label: 'updated_at',
    value: profile.value?.updated_at ?? '-'
  },
  {
    label: 'jwt_token',
    value: token.value ?? '-'
  }
])

async function sair() {
  isLeaving.value = true
  clearToken()
  $toast.success('Sessão encerrada com sucesso.', { duration: 8000 })
  await navigateTo('/login')
}
</script>
