<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-[460px] w-[min(92vw,820px)] -translate-x-1/2 rounded-[48px] bg-[radial-gradient(circle_at_20%_30%,rgba(232,184,196,0.6),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(244,197,168,0.5),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(168,200,232,0.56),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full max-w-[1120px] gap-8" aria-labelledby="favoritos-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(232,184,196,0.5)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Favoritos
          </p>
          <h1 id="favoritos-title"
            class="my-5 max-w-[720px] font-serif text-[40px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] md:text-[48px]">
            Meus favoritos
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Jogos que você salvou como favoritos. Gerencie sua lista aqui.
          </p>
        </div>
      </header>

      <section
        class="grid gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-6 shadow-[0_4px_16px_rgba(0,0,0,0.04)] md:p-8"
        aria-label="Lista de jogos favoritos">
        <div>
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(232,184,196,0.5)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Salvos
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            Jogos favoritos
          </h2>
        </div>

        <div v-if="isLoading" class="grid gap-3" role="status" aria-live="polite">
          <div v-for="item in 4" :key="item" class="h-16 animate-pulse rounded-xl bg-[#f0efed]"></div>
        </div>

        <div v-else-if="errorMessage"
          class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-[15px] leading-[1.47] tracking-[0.15px] text-red-700"
          role="alert">
          {{ errorMessage }}
        </div>

        <div v-else-if="!favorites.length" class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-8 text-center"
          role="status">
          <Icon name="mdi:heart-outline" class="mb-3 text-4xl text-[#d6d3d1]" />
          <p class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            Nenhum jogo favorito ainda.<br />
            <NuxtLink to="/ranking-jogos" class="underline hover:text-[#0c0a09]">Vá ao ranking</NuxtLink>
            e adicione seus favoritos!
          </p>
        </div>

        <div v-else class="overflow-hidden rounded-xl border border-[#e7e5e4]">
          <div
            class="hidden bg-[#fafafa] px-4 py-3 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169] md:grid md:grid-cols-[minmax(0,1fr)_160px] md:gap-4">
            <span>Jogo</span>
            <span>Ação</span>
          </div>

          <ul class="grid divide-y divide-[#e7e5e4]">
            <li v-for="game in favorites" :key="game.id"
              class="grid items-center gap-4 bg-white p-4 md:grid-cols-[minmax(0,1fr)_160px] md:gap-4">
              <div class="flex items-center gap-3">
                <Icon name="mdi:heart" class="shrink-0 text-rose-500" />
                <span class="text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                  {{ game.game_id }}
                </span>
              </div>

              <button type="button" :disabled="removingId === game.game_id"
                :aria-label="`Remover ${game.game_id} dos favoritos`" @click="removeFavorite(game)"
                class="inline-flex h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 text-[13px] font-medium leading-none text-[#777169] transition hover:border-red-300 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-50">
                <Icon :name="removingId === game.game_id ? 'mdi:loading' : 'mdi:heart-remove-outline'"
                  :class="['text-sm', removingId === game.game_id && 'animate-spin']" />
                <span class="hidden sm:inline">{{
                  removingId === game.game_id ? 'Removendo...' : 'Remover'
                  }}</span>
              </button>
            </li>
          </ul>
        </div>
      </section>

      <div class="flex flex-col items-center gap-2 text-center text-xs leading-[1.4] tracking-[0.16px] text-[#777169]">
        <p>
          Microsserviço consumido:
          <span class="font-medium text-[#4e4e4e]">https://gameverse-wishlist-production.up.railway.app</span>
          &nbsp;·&nbsp; Feito por Edson e Mateus Lima
        </p>
        <span class="inline-flex items-center gap-1.5">
          <span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
          Sistema de validação de token funcional
        </span>
      </div>
    </main>
  </div>
</template>

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

const WISHLIST_API_BASE_URL = 'https://gameverse-wishlist-production.up.railway.app'

const { $toast } = useNuxtApp()

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

const favorites = ref([])
const isLoading = ref(false)
const errorMessage = ref('')
const removingId = ref(null)

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

async function fetchFavorites() {
  if (!token.value) {
    await navigateTo('/login')
    return
  }

  isLoading.value = true
  errorMessage.value = ''

  try {
    const data = await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist`, {
      headers: {
        Authorization: `Bearer ${token.value}`
      }
    })

    favorites.value = (data?.data ?? []).filter(
      (item) => item.is_favorite === 1 || item.is_favorite === true
    )
  } catch (error) {
    const statusCode = error?.statusCode ?? error?.response?.status ?? error?.data?.statusCode

    if (statusCode === 401) {
      clearToken()
      $toast.error('Sua sessão expirou. Faça login novamente.', { duration: 8000 })
      await navigateTo('/login')
      return
    }

    errorMessage.value = error?.data?.message ?? 'Erro ao carregar os favoritos. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

async function removeFavorite(game) {
  if (!token.value) {
    await navigateTo('/login')
    return
  }

  removingId.value = game.game_id

  try {
    await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist/${encodeURIComponent(game.game_id)}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${token.value}`
      }
    })

    favorites.value = favorites.value.filter((f) => f.game_id !== game.game_id)
    $toast.success(`${game.game_id} removido dos favoritos.`, { duration: 4000 })
  } catch (error) {
    const statusCode = error?.statusCode ?? error?.response?.status ?? error?.data?.statusCode

    if (statusCode === 401) {
      clearToken()
      $toast.error('Sua sessão expirou. Faça login novamente.', { duration: 8000 })
      await navigateTo('/login')
      return
    }

    $toast.error('Erro ao remover o favorito. Tente novamente.', { duration: 6000 })
  } finally {
    removingId.value = null
  }
}

onMounted(() => {
  fetchFavorites()
})
</script>
