<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(167,229,211,0.62),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="ranking-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(244,197,168,0.56)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Rankings
          </p>
          <h1 id="ranking-title"
            class="my-5 max-w-[720px] font-serif text-[40px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] md:text-[48px]">
            Ranking de jogos
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Acompanhe os jogos por período, plataforma e volume de jogadores ativos.
          </p>
        </div>

        <NuxtLink to="/home"
          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]">
          Voltar
        </NuxtLink>
      </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 ranking de jogos">
        <div class="grid gap-5 md:grid-cols-[minmax(0,1fr)_minmax(240px,320px)] md:items-end">
          <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]">
              {{ selectedRankingMeta.badge }}
            </span>
            <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
              {{ selectedRankingMeta.title }}
            </h2>
          </div>

          <AppSelect id="ranking-filter" v-model="selectedRanking" label="Visualização" :options="rankingOptions"
            :disabled="isLoading" />
        </div>

        <div v-if="isLoading" class="grid gap-3" role="status" aria-live="polite">
          <div v-for="item in 4" :key="item" class="h-20 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="!rankings.length"
          class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-6 text-center text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
          Nenhum jogo encontrado para este ranking.
        </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-[72px_minmax(180px,1.5fr)_minmax(130px,1fr)_repeat(4,minmax(100px,1fr))] md:gap-4">
            <span>Posição</span>
            <span>Jogo</span>
            <span>Plataforma</span>
            <span>Jogadores</span>
            <span>Semanal</span>
            <span>Mensal</span>
            <span>Anual</span>
          </div>

          <ol class="grid divide-y divide-[#e7e5e4]">
            <li v-for="(game, index) in rankings" :key="game.id"
              class="grid gap-4 bg-white p-4 md:grid-cols-[72px_minmax(180px,1.5fr)_minmax(130px,1fr)_repeat(4,minmax(100px,1fr))] md:items-center md:gap-4">
              <div class="flex items-center justify-between gap-3 md:block">
                <span class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169] md:hidden">
                  Posição
                </span>
                <span
                  class="inline-flex h-9 min-w-9 items-center justify-center rounded-full bg-[#292524] px-3 text-[15px] font-medium leading-none text-white">
                  {{ index + 1 }}
                </span>
              </div>

              <div class="grid gap-1">
                <span class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169] md:hidden">
                  Jogo
                </span>
                <strong class="text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                  {{ game.name }}
                </strong>
              </div>

              <div v-for="stat in getGameStats(game)" :key="stat.label"
                class="flex items-center justify-between gap-3 md:block">
                <span class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169] md:hidden">
                  {{ stat.label }}
                </span>
                <span class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#292524]">
                  {{ stat.value }}
                </span>
              </div>
            </li>
          </ol>
        </div>
      </section>
    </main>
  </div>
</template>

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

const RANKINGS_API_BASE_URL = 'https://api-ranking-jogos-production.up.railway.app/api/v1'

const rankingOptions = [
  {
    label: 'Semanal',
    value: 'weekly',
    endpoint: '/rankings/weekly',
    badge: 'Semana',
    title: 'Ranking semanal'
  },
  {
    label: 'Mensal',
    value: 'monthly',
    endpoint: '/rankings/monthly',
    badge: 'Mês',
    title: 'Ranking mensal'
  },
  {
    label: 'Anual',
    value: 'yearly',
    endpoint: '/rankings/yearly',
    badge: 'Ano',
    title: 'Ranking anual'
  },
  {
    label: 'Steam',
    value: 'steam',
    endpoint: '/rankings/platforms/Steam',
    badge: 'Steam',
    title: 'Ranking da Steam'
  },
  {
    label: 'Epic Games',
    value: 'epic-games',
    endpoint: '/rankings/platforms/Epic Games',
    badge: 'Epic Games',
    title: 'Ranking da Epic Games'
  },
  {
    label: 'Riot Launcher',
    value: 'riot-launcher',
    endpoint: '/rankings/platforms/Riot Launcher',
    badge: 'Riot Launcher',
    title: 'Ranking da Riot Launcher'
  },
  {
    label: 'Multiplataforma',
    value: 'multi-platform',
    endpoint: '/rankings/platforms/Multiplataforma',
    badge: 'Multiplataforma',
    title: 'Ranking multiplataforma'
  },
  {
    label: 'Battle.net',
    value: 'battle-net',
    endpoint: '/rankings/platforms/Battle.net',
    badge: 'Battle.net',
    title: 'Ranking da Battle.net'
  },
  {
    label: 'Mais jogados',
    value: 'most-played',
    endpoint: '/games/most-played',
    badge: 'Ativos',
    title: 'Jogos mais jogados'
  }
]

const { $toast } = useNuxtApp()

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

const selectedRanking = ref('weekly')
const rankings = ref([])
const isLoading = ref(false)
const errorMessage = ref('')

const selectedRankingMeta = computed(() => {
  return rankingOptions.find((option) => option.value === selectedRanking.value) ?? rankingOptions[0]
})

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

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

const getGameStats = (game) => [
  {
    label: 'Plataforma',
    value: game.platform
  },
  {
    label: 'Jogadores',
    value: formatNumber(game.active_players)
  },
  {
    label: 'Semanal',
    value: formatNumber(game.weekly_points)
  },
  {
    label: 'Mensal',
    value: formatNumber(game.monthly_points)
  },
  {
    label: 'Anual',
    value: formatNumber(game.yearly_points)
  }
]

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

  isLoading.value = true
  errorMessage.value = ''

  try {
    const data = await $fetch(`${RANKINGS_API_BASE_URL}${selectedRankingMeta.value.endpoint}`, {
      headers: {
        Authorization: `Bearer ${token.value}`
      }
    })

    rankings.value = Array.isArray(data) ? data : []
  } 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
    }

    rankings.value = []
    errorMessage.value = error?.data?.message ?? 'Erro ao carregar o ranking de jogos. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  fetchRankings()
})

watch(selectedRanking, () => {
  if (import.meta.client) {
    fetchRankings()
  }
})
</script>
