<template>
  <div
    class="relative min-h-[calc(100vh-66px)] overflow-x-hidden bg-[#f5f5f5] px-3 py-8 font-sans text-[#0c0a09] sm:px-4 md:px-6 md:py-12 xl:px-8 xl:py-16">
    <div
      class="pointer-events-none absolute left-1/2 top-8 h-[500px] w-[min(94vw,900px)] -translate-x-1/2 rounded-[48px] bg-[radial-gradient(circle_at_18%_28%,rgba(167,229,211,0.62),transparent_28%),radial-gradient(circle_at_76%_22%,rgba(244,197,168,0.5),transparent_30%),radial-gradient(circle_at_54%_82%,rgba(168,200,232,0.56),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full min-w-0 max-w-[1180px] gap-6 md:gap-8" aria-labelledby="home-title">
      <section class="grid min-w-0 gap-6 2xl:grid-cols-[minmax(0,1.45fr)_minmax(300px,0.55fr)] 2xl:items-stretch">
        <div class="grid min-w-0 gap-6">
          <header>
            <p
              class="m-0 inline-flex rounded-full bg-[rgba(167,229,211,0.62)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
              Dashboard
            </p>
            <h1 id="home-title"
              class="my-5 max-w-[760px] break-words font-serif text-[34px] font-light leading-[1.05] tracking-[-1.2px] text-[#0c0a09] sm:text-[40px] md:text-[52px] xl:text-[60px] xl:tracking-[-1.6px]">
              Olá, {{ userName }}.
            </h1>
            <p class="m-0 max-w-[620px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
              Acompanhe sua sessão, ranking semanal, favoritos, catálogo, gift cards e perfil gamer
              em um só lugar.
            </p>
          </header>

          <div class="grid min-w-0 gap-4 md:grid-cols-2 2xl:grid-cols-4">
            <NuxtLink v-for="card in dashboardCards" :key="card.label" :to="card.to"
              class="grid min-h-[156px] min-w-0 content-between rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] transition hover:border-[#d6d3d1] hover:shadow-[0_8px_24px_rgba(0,0,0,0.07)] sm:p-5">
              <div class="flex items-center justify-between gap-3">
                <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl" :class="card.accent">
                  <Icon :name="card.icon" class="text-xl text-[#0c0a09]" />
                </span>
                <Icon name="mdi:arrow-right" class="text-lg text-[#777169]" />
              </div>

              <div class="grid gap-2">
                <p class="m-0 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  {{ card.label }}
                </p>
                <strong
                  class="min-w-0 break-words text-[22px] font-medium leading-[1.18] tracking-[0.16px] text-[#0c0a09]">
                  {{ card.value }}
                </strong>
                <p class="m-0 text-[13px] leading-[1.5] tracking-[0.13px] text-[#777169]">
                  {{ card.helper }}
                </p>
              </div>
            </NuxtLink>
          </div>
        </div>

        <aside
          class="grid min-w-0 gap-4 rounded-2xl border border-[#e7e5e4] bg-white p-5 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-6 md:p-8">
          <div class="flex min-w-0 items-center gap-3">
            <span
              class="inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[#292524] text-base font-semibold text-white">
              {{ userInitial }}
            </span>
            <div class="min-w-0">
              <p class="m-0 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Sessão ativa
              </p>
              <p class="m-0 mt-1 min-w-0 truncate text-[15px] font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                {{ profile?.email ?? '-' }}
              </p>
            </div>
          </div>

          <dl class="grid gap-3 border-t border-[#e7e5e4] pt-5">
            <div v-for="item in accountFacts" :key="item.label" class="grid gap-1">
              <dt class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                {{ item.label }}
              </dt>
              <dd class="m-0 min-w-0 truncate text-[15px] leading-[1.47] tracking-[0.15px] text-[#0c0a09]">
                {{ item.value }}
              </dd>
            </div>
          </dl>

          <NuxtLink to="/dados-conta"
            class="inline-flex min-h-10 min-w-0 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 py-2 text-center text-[15px] font-medium leading-[1.2] text-white transition hover:bg-[#0c0a09]">
            <span class="min-w-0 break-words">Ver dados da conta</span>
            <Icon name="mdi:arrow-right" class="shrink-0 text-base" />
          </NuxtLink>
        </aside>
      </section>

      <section class="grid min-w-0 gap-6 md:gap-8 2xl:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.65fr)]">
        <article
          class="grid min-w-0 gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6 xl:p-8"
          aria-labelledby="weekly-ranking-title">
          <div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <span
                class="inline-flex min-h-6 items-center rounded-full bg-[rgba(244,197,168,0.56)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
                Semana
              </span>
              <h2 id="weekly-ranking-title"
                class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
                Ranking semanal em destaque
              </h2>
            </div>

            <NuxtLink to="/ranking-jogos"
              class="inline-flex min-h-10 w-full min-w-0 items-center justify-center gap-2 rounded-full border border-[#d6d3d1] bg-transparent px-5 py-2 text-center text-[15px] font-medium leading-[1.2] text-[#0c0a09] transition hover:border-[#0c0a09] sm:w-fit">
              <span class="min-w-0 break-words">Ver ranking completo</span>
              <Icon name="mdi:arrow-right" class="text-base" />
            </NuxtLink>
          </div>

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

          <div v-else-if="ranking.error"
            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">
            {{ ranking.error }}
          </div>

          <ol v-else-if="ranking.items.length" class="grid overflow-hidden rounded-xl border border-[#e7e5e4]">
            <li v-for="(game, index) in ranking.items.slice(0, 5)" :key="game.id ?? game.name"
              class="flex min-w-0 flex-col gap-3 border-b border-[#e7e5e4] bg-white p-4 last:border-b-0 sm:flex-row sm:items-center">
              <span
                class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#292524] text-[15px] font-medium leading-none text-white">
                {{ index + 1 }}
              </span>
              <div class="min-w-0 flex-1">
                <strong
                  class="block min-w-0 break-words text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                  {{ game.name }}
                </strong>
                <span class="text-[13px] leading-[1.5] tracking-[0.13px] text-[#777169]">
                  {{ game.platform ?? 'Plataforma não informada' }}
                </span>
              </div>
              <div class="flex min-w-0 flex-wrap gap-x-4 gap-y-1 sm:justify-end">
                <span class="whitespace-nowrap text-[15px] leading-[1.47] tracking-[0.15px] text-[#292524]">
                  {{ formatNumber(game.active_players) }} jogadores
                </span>
                <span class="whitespace-nowrap text-[15px] leading-[1.47] tracking-[0.15px] text-[#292524]">
                  {{ formatNumber(game.weekly_points) }} pts
                </span>
              </div>
            </li>
          </ol>

          <div v-else
            class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-8 text-center text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            Nenhum jogo encontrado no ranking semanal.
          </div>
        </article>

        <aside class="grid min-w-0 gap-4">
          <article
            class="grid min-w-0 gap-4 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6"
            aria-labelledby="profile-gamer-summary">
            <div class="flex items-start justify-between gap-3">
              <div>
                <span
                  class="inline-flex min-h-6 items-center rounded-full bg-[rgba(232,184,196,0.55)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
                  Perfil
                </span>
                <h2 id="profile-gamer-summary"
                  class="mt-4 font-serif text-2xl font-light leading-[1.13] tracking-[-0.24px] text-[#0c0a09]">
                  Perfil gamer
                </h2>
              </div>
              <Icon name="mdi:account-star-outline" class="text-2xl text-[#777169]" />
            </div>

            <div v-if="gamerProfile.isLoading" class="grid gap-2" role="status" aria-live="polite">
              <div class="h-5 animate-pulse rounded-xl bg-[#f0efed]"></div>
              <div class="h-5 w-2/3 animate-pulse rounded-xl bg-[#f0efed]"></div>
            </div>

            <p v-else-if="gamerProfile.error" class="m-0 text-[15px] leading-[1.47] tracking-[0.15px] text-red-700">
              {{ gamerProfile.error }}
            </p>

            <div v-else class="grid gap-2">
              <p class="m-0 text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                {{ gamerProfile.data?.nickname ?? 'Perfil ainda não criado' }}
              </p>
              <p class="m-0 text-[13px] leading-[1.5] tracking-[0.13px] text-[#777169]">
                {{ gamerProfileHelper }}
              </p>
            </div>

            <NuxtLink to="/perfil-gamer"
              class="inline-flex min-h-10 min-w-0 items-center justify-center rounded-full border border-[#d6d3d1] bg-transparent px-5 py-2 text-center text-[15px] font-medium leading-[1.2] text-[#0c0a09] transition hover:border-[#0c0a09]">
              Abrir perfil gamer
            </NuxtLink>
          </article>

          <article
            class="grid min-w-0 gap-4 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6"
            aria-labelledby="shortcuts-title">
            <div>
              <span
                class="inline-flex min-h-6 items-center rounded-full bg-[rgba(168,200,232,0.56)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
                Acesso rápido
              </span>
              <h2 id="shortcuts-title"
                class="mt-4 font-serif text-2xl font-light leading-[1.13] tracking-[-0.24px] text-[#0c0a09]">
                Rotas internas
              </h2>
            </div>

            <div class="grid gap-2">
              <NuxtLink v-for="shortcut in shortcuts" :key="shortcut.to" :to="shortcut.to"
                class="flex min-h-11 min-w-0 items-center justify-between gap-3 rounded-xl border border-[#e7e5e4] px-4 text-[15px] font-medium leading-[1.47] tracking-[0.15px] text-[#0c0a09] transition hover:border-[#0c0a09]">
                <span class="inline-flex min-w-0 items-center gap-2">
                  <Icon :name="shortcut.icon" class="shrink-0 text-base text-[#777169]" />
                  {{ shortcut.label }}
                </span>
                <Icon name="mdi:arrow-right" class="shrink-0 text-base text-[#777169]" />
              </NuxtLink>
            </div>
          </article>
        </aside>
      </section>

      <section class="grid min-w-0 gap-4 sm:grid-cols-2 xl:grid-cols-4" aria-label="Prévia dos serviços">
        <article v-for="service in servicePreviews" :key="service.title"
          class="grid min-w-0 gap-4 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6">
          <div class="flex items-start justify-between gap-3">
            <div>
              <span
                class="inline-flex min-h-6 items-center rounded-full px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]"
                :class="service.badgeClass">
                {{ service.badge }}
              </span>
              <h2 class="mt-4 font-serif text-2xl font-light leading-[1.13] tracking-[-0.24px] text-[#0c0a09]">
                {{ service.title }}
              </h2>
            </div>
            <Icon :name="service.icon" class="text-2xl text-[#777169]" />
          </div>

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

          <p v-else-if="service.error" class="m-0 text-[15px] leading-[1.47] tracking-[0.15px] text-red-700">
            {{ service.error }}
          </p>

          <ul v-else-if="service.items.length" class="grid gap-2">
            <li v-for="item in service.items" :key="item"
              class="flex items-center gap-2 text-[15px] leading-[1.47] tracking-[0.15px] text-[#292524]">
              <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-[#292524]"></span>
              <span class="min-w-0 break-words">{{ item }}</span>
            </li>
          </ul>

          <p v-else class="m-0 text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            {{ service.empty }}
          </p>

          <NuxtLink :to="service.to"
            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]">
            {{ service.action }}
          </NuxtLink>
        </article>
      </section>
    </main>
  </div>
</template>

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

useHead({
  title: 'Home | GameVerse',
  meta: [
    {
      name: 'description',
      content:
        'Acompanhe sua sessão, ranking semanal, favoritos, catálogo, gift cards e perfil gamer em um só lugar.'
    }
  ]
})

const RANKINGS_API_BASE_URL = 'https://api-ranking-jogos-production.up.railway.app/api/v1'
const COMPARE_API_BASE_URL = 'https://ranking-plataforma.onrender.com'
const WISHLIST_API_BASE_URL = 'https://gameverse-wishlist-production.up.railway.app'
const CATALOG_API_BASE_URL = 'https://catalogo-jogos-sd-production.up.railway.app'
const GIFT_CARD_API_BASE_URL = 'https://giftcardapipedro-production.up.railway.app/api'
const PERFIL_GAMER_API_BASE_URL = 'https://perfilgameredivaldo-production.up.railway.app/api'

const { $toast } = useNuxtApp()

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

const authHeaders = () => ({
  Authorization: `Bearer ${token.value}`
})

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

const { data: profile, error: profileError } = await useAsyncData('profile-me-home', () =>
  $fetch('/profile/me', {
    headers: authHeaders()
  })
)

if (profileError.value) {
  clearToken()

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

  await navigateTo('/login')
}

const ranking = reactive({
  isLoading: true,
  error: '',
  items: []
})

const favorites = reactive({
  isLoading: true,
  error: '',
  items: []
})

const catalog = reactive({
  isLoading: true,
  error: '',
  items: []
})

const giftCards = reactive({
  isLoading: true,
  error: '',
  items: []
})

const gamerProfile = reactive({
  isLoading: true,
  error: '',
  data: null
})

const rankingPlataforma = reactive({
  isLoading: true,
  error: '',
  items: []
})

const isRedirecting = ref(false)

const userName = computed(
  () => gamerProfile.data?.nickname || profile.value?.email?.split('@')?.[0] || 'jogador'
)
const userInitial = computed(() => (profile.value?.email?.[0] ?? 'G').toUpperCase())
const userId = computed(() => profile.value?.user_id ?? profile.value?.id ?? '-')

const accountFacts = computed(() => [
  {
    label: 'User ID',
    value: userId.value
  },
  {
    label: 'Criada em',
    value: formatDate(profile.value?.created_at)
  },
  {
    label: 'Atualizada em',
    value: formatDate(profile.value?.updated_at)
  }
])

const topRanking = computed(() => ranking.items[0] ?? null)
const activeCatalogGames = computed(() => catalog.items.filter((game) => game.active !== false))
const totalGiftBalance = computed(() =>
  giftCards.items.reduce((sum, card) => sum + Number(card.balance ?? 0), 0)
)
const favoriteNames = computed(() => favorites.items.map((item) => item.game_id).filter(Boolean))
const rankingPlataformaItems = computed(() =>
  rankingPlataforma.items.slice(0, 3).map((g) => `${g.name} · ${g.platform} · ${g.score}`)
)
const catalogNames = computed(() => catalog.items.map((item) => item.title).filter(Boolean))
const giftCardCodes = computed(() =>
  giftCards.items.map((item) => `${item.code} · ${formatCurrency(item.balance)}`).filter(Boolean)
)

const gamerProfileHelper = computed(() => {
  if (!gamerProfile.data) {
    return 'Use a rota Perfil gamer para cadastrar nickname, bio, país e preferências.'
  }

  const platforms = Array.isArray(gamerProfile.data.platforms)
    ? gamerProfile.data.platforms.slice(0, 3).join(', ')
    : ''
  return platforms ? `Plataformas: ${platforms}` : 'Perfil gamer conectado à sua sessão.'
})

const dashboardCards = computed(() => [
  {
    label: 'Líder semanal',
    value: ranking.isLoading ? 'Carregando...' : (topRanking.value?.name ?? 'Sem dados'),
    helper:
      ranking.error ||
      (topRanking.value
        ? `${formatNumber(topRanking.value.active_players)} jogadores ativos`
        : 'Ranking semanal'),
    icon: 'mdi:trophy-outline',
    to: '/ranking-jogos',
    accent: 'bg-[rgba(244,197,168,0.56)]'
  },
  {
    label: 'Favoritos',
    value: favorites.isLoading ? 'Carregando...' : formatNumber(favorites.items.length),
    helper: favorites.error || 'Jogos salvos por você',
    icon: 'mdi:heart-outline',
    to: '/favoritos',
    accent: 'bg-[rgba(232,184,196,0.55)]'
  },
  {
    label: 'Catálogo',
    value: catalog.isLoading ? 'Carregando...' : formatNumber(activeCatalogGames.value.length),
    helper: catalog.error || 'Jogos ativos no catálogo',
    icon: 'mdi:controller-classic-outline',
    to: '/catalogo',
    accent: 'bg-[rgba(196,184,232,0.45)]'
  },
  {
    label: 'Gift cards',
    value: giftCards.isLoading ? 'Carregando...' : formatCurrency(totalGiftBalance.value),
    helper: giftCards.error || `${formatNumber(giftCards.items.length)} cartões emitidos`,
    icon: 'mdi:gift-outline',
    to: '/gift-card',
    accent: 'bg-[rgba(167,229,211,0.62)]'
  }
])

const shortcuts = [
  {
    label: 'Dados da conta',
    to: '/dados-conta',
    icon: 'mdi:account-circle-outline'
  },
  {
    label: 'Ranking de jogos',
    to: '/ranking-jogos',
    icon: 'mdi:trophy-outline'
  },
  {
    label: 'Ranking por plataforma',
    to: '/ranking-plataforma',
    icon: 'mdi:layers-outline'
  },
  {
    label: 'Novo jogo no catálogo',
    to: '/catalogo/criar',
    icon: 'mdi:plus'
  },
  {
    label: 'Gift cards',
    to: '/gift-card',
    icon: 'mdi:gift-outline'
  }
]

const servicePreviews = computed(() => [
  {
    badge: 'Favoritos',
    badgeClass: 'bg-[rgba(232,184,196,0.5)]',
    title: 'Jogos salvos',
    icon: 'mdi:heart-outline',
    loading: favorites.isLoading,
    error: favorites.error,
    items: favoriteNames.value.slice(0, 3),
    empty: 'Nenhum favorito encontrado.',
    to: '/favoritos',
    action: 'Ver favoritos'
  },
  {
    badge: 'Catálogo',
    badgeClass: 'bg-[rgba(196,184,232,0.45)]',
    title: 'Últimos jogos',
    icon: 'mdi:controller-classic-outline',
    loading: catalog.isLoading,
    error: catalog.error,
    items: catalogNames.value.slice(0, 3),
    empty: 'Nenhum jogo encontrado no catálogo.',
    to: '/catalogo',
    action: 'Abrir catálogo'
  },
  {
    badge: 'Carteira',
    badgeClass: 'bg-[rgba(167,229,211,0.62)]',
    title: 'Gift cards',
    icon: 'mdi:gift-outline',
    loading: giftCards.isLoading,
    error: giftCards.error,
    items: giftCardCodes.value.slice(0, 3),
    empty: 'Nenhum gift card emitido.',
    to: '/gift-card',
    action: 'Gerenciar gift cards'
  },
  {
    badge: 'Plataformas',
    badgeClass: 'bg-[rgba(196,184,232,0.56)]',
    title: 'Ranking por plataforma',
    icon: 'mdi:layers-outline',
    loading: rankingPlataforma.isLoading,
    error: rankingPlataforma.error,
    items: rankingPlataformaItems.value,
    empty: 'Nenhum dado disponível.',
    to: '/ranking-plataforma',
    action: 'Ver ranking completo'
  }
])

const formatNumber = (value) => {
  return new Intl.NumberFormat('pt-BR').format(Number(value ?? 0))
}

const formatCurrency = (value) => {
  return new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL'
  }).format(Number(value ?? 0))
}

const formatDate = (value) => {
  if (!value) return '-'

  return new Intl.DateTimeFormat('pt-BR', {
    dateStyle: 'short',
    timeStyle: 'short'
  }).format(new Date(value))
}

const getStatusCode = (error) =>
  error?.statusCode ?? error?.response?.status ?? error?.data?.statusCode

async function tratarErroAuth(error) {
  if (getStatusCode(error) !== 401) {
    return false
  }

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

  return true
}

async function fetchRanking() {
  ranking.isLoading = true
  ranking.error = ''

  try {
    const data = await $fetch(`${RANKINGS_API_BASE_URL}/rankings/weekly`, {
      headers: authHeaders()
    })

    ranking.items = Array.isArray(data) ? data : []
  } catch (error) {
    if (await tratarErroAuth(error)) return

    ranking.items = []
    ranking.error = error?.data?.message ?? 'Erro ao carregar o ranking semanal.'
  } finally {
    ranking.isLoading = false
  }
}

async function fetchFavorites() {
  favorites.isLoading = true
  favorites.error = ''

  try {
    const data = await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist`, {
      headers: authHeaders()
    })

    favorites.items = (data?.data ?? []).filter(
      (item) => item.is_favorite === 1 || item.is_favorite === true
    )
  } catch (error) {
    if (await tratarErroAuth(error)) return

    favorites.items = []
    favorites.error = error?.data?.message ?? 'Erro ao carregar os favoritos.'
  } finally {
    favorites.isLoading = false
  }
}

async function fetchCatalog() {
  catalog.isLoading = true
  catalog.error = ''

  try {
    const data = await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games`, {
      headers: authHeaders()
    })

    catalog.items = data?.data ?? []
  } catch (error) {
    if (await tratarErroAuth(error)) return

    catalog.items = []
    catalog.error = error?.data?.message ?? 'Erro ao carregar o catálogo.'
  } finally {
    catalog.isLoading = false
  }
}

async function fetchGiftCards() {
  giftCards.isLoading = true
  giftCards.error = ''

  try {
    const data = await $fetch(`${GIFT_CARD_API_BASE_URL}/giftcards`, {
      headers: authHeaders()
    })

    giftCards.items = Array.isArray(data) ? data : []
  } catch (error) {
    if (await tratarErroAuth(error)) return

    giftCards.items = []
    giftCards.error = error?.data?.message ?? 'Erro ao carregar seus gift cards.'
  } finally {
    giftCards.isLoading = false
  }
}

async function fetchRankingPlataforma() {
  rankingPlataforma.isLoading = true
  rankingPlataforma.error = ''

  try {
    const data = await $fetch(`${COMPARE_API_BASE_URL}/compare`, {
      headers: authHeaders()
    })
    rankingPlataforma.items = Array.isArray(data?.data) ? data.data : []
  } catch (error) {
    if (await tratarErroAuth(error)) return
    rankingPlataforma.items = []
    rankingPlataforma.error = error?.data?.message ?? 'Erro ao carregar ranking por plataforma.'
  } finally {
    rankingPlataforma.isLoading = false
  }
}

async function fetchGamerProfile() {
  gamerProfile.isLoading = true
  gamerProfile.error = ''

  try {
    gamerProfile.data = await $fetch(`${PERFIL_GAMER_API_BASE_URL}/profiles/me`, {
      headers: authHeaders()
    })
  } catch (error) {
    if (await tratarErroAuth(error)) return

    if (getStatusCode(error) === 404) {
      gamerProfile.data = null
      return
    }

    gamerProfile.data = null
    gamerProfile.error = error?.data?.message ?? 'Erro ao carregar o perfil gamer.'
  } finally {
    gamerProfile.isLoading = false
  }
}

onMounted(() => {
  Promise.all([
    fetchRanking(),
    fetchFavorites(),
    fetchCatalog(),
    fetchGiftCards(),
    fetchGamerProfile(),
    fetchRankingPlataforma()
  ])
})
</script>
