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

    <main class="relative mx-auto grid w-full min-w-0 max-w-[1120px] gap-6 md:gap-8"
      aria-labelledby="ranking-plataforma-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(196,184,232,0.56)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Rankings
          </p>
          <h1 id="ranking-plataforma-title"
            class="my-5 max-w-[720px] break-words font-serif text-[34px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] sm:text-[40px] md:text-[48px]">
            Ranking por plataforma
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Compare os jogos mais bem avaliados de cada plataforma em um ranking unificado por pontuação.
          </p>
        </div>
      </header>

      <section
        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-label="Lista de ranking por plataforma">
        <div class="grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1fr)_minmax(240px,320px)] xl:items-end">
          <div>
            <span
              class="inline-flex min-h-6 items-center rounded-full bg-[rgba(196,184,232,0.56)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
              {{ selectedPlatform === 'all' ? 'Todas as plataformas' : selectedPlatform }}
            </span>
            <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
              {{ selectedPlatform === 'all' ? 'Ranking geral por plataforma' : `Ranking — ${selectedPlatform}` }}
            </h2>
          </div>

          <AppSelect id="platform-filter" v-model="selectedPlatform" label="Filtrar por plataforma"
            :options="platformOptions" :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="!filteredRankings.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 esta plataforma.
        </div>

        <!-- Mobile: cards horizontais -->
        <ol class="grid gap-2.5 xl:hidden">
          <li v-for="game in filteredRankings" :key="game.rank"
            class="flex items-center gap-3 rounded-xl border border-[#e7e5e4] bg-white p-3">
            <span
              class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[#292524] text-[13px] font-semibold leading-none text-white">
              {{ game.rank }}
            </span>
            <img v-if="game.image" :src="game.image" :alt="game.name" class="w-24 shrink-0 rounded-lg" loading="lazy" />
            <div v-else class="h-14 w-24 shrink-0 rounded-lg bg-[#f0efed]"></div>
            <div class="flex min-w-0 flex-1 flex-col gap-2">
              <strong
                class="min-w-0 line-clamp-2 text-[13px] font-medium leading-[1.35] tracking-[0.1px] text-[#0c0a09]">
                {{ game.name }}
              </strong>
              <div class="flex items-center gap-1.5">
                <span
                  :class="['inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase leading-none tracking-[0.6px] text-[#0c0a09]', platformBadgeClass(game.platform)]">
                  {{ game.platform }}
                </span>
                <span
                  class="inline-flex items-center justify-center rounded-full bg-[#292524] px-2 py-0.5 text-[12px] font-semibold leading-none text-white">
                  {{ game.score }}
                </span>
              </div>
            </div>
          </li>
        </ol>

        <!-- Desktop: tabela -->
        <div class="hidden overflow-hidden rounded-xl border border-[#e7e5e4] xl:block">
          <div
            class="bg-[#fafafa] px-4 py-3 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169] xl:grid xl:grid-cols-[72px_minmax(220px,2fr)_minmax(140px,1fr)_120px] xl:gap-4">
            <span>Posição</span>
            <span>Jogo</span>
            <span>Plataforma</span>
            <span>Pontuação</span>
          </div>
          <ol class="grid divide-y divide-[#e7e5e4]">
            <li v-for="game in filteredRankings" :key="game.rank"
              class="grid grid-cols-[72px_minmax(220px,2fr)_minmax(140px,1fr)_120px] items-center gap-4 bg-white p-4">
              <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">
                {{ game.rank }}
              </span>
              <div class="flex min-w-0 items-center gap-3">
                <img v-if="game.image" :src="game.image" :alt="game.name"
                  class="h-16 w-28 shrink-0 rounded-lg object-cover shadow-sm" loading="lazy" />
                <div v-else class="h-16 w-28 shrink-0 rounded-lg bg-[#f0efed]"></div>
                <strong class="min-w-0 break-words text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                  {{ game.name }}
                </strong>
              </div>
              <span
                :class="['inline-flex items-center rounded-full px-2.5 py-1 text-[12px] font-semibold uppercase leading-none tracking-[0.8px] text-[#0c0a09]', platformBadgeClass(game.platform)]">
                {{ game.platform }}
              </span>
              <span
                class="inline-flex items-center justify-center rounded-full bg-[#292524] px-3 py-1 text-[13px] font-semibold leading-none text-white">
                {{ game.score }}
              </span>
            </li>
          </ol>
        </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://ranking-plataforma.onrender.com</span>
          &nbsp;·&nbsp; Feito por Ingrid e Marcelo
        </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'
})

useHead({
  title: 'Ranking por plataforma | GameVerse',
  meta: [
    {
      name: 'description',
      content: 'Compare os jogos mais bem avaliados de cada plataforma em um ranking unificado por pontuação.'
    }
  ]
})

const COMPARE_API_BASE_URL = 'https://ranking-plataforma.onrender.com'

const platformOptions = [
  { label: 'Todas as plataformas', value: 'all' },
  { label: 'Steam', value: 'Steam' },
  { label: 'PlayStation', value: 'PlayStation' },
  { label: 'Xbox', value: 'Xbox' },
  { label: 'Epic', value: 'Epic' }
]

const platformBadgeClasses = {
  Steam: 'bg-[rgba(167,229,211,0.56)]',
  PlayStation: 'bg-[rgba(168,200,232,0.56)]',
  Xbox: 'bg-[rgba(167,229,211,0.4)]',
  Epic: 'bg-[rgba(196,184,232,0.4)]'
}

const { $toast } = useNuxtApp()

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

const selectedPlatform = ref('all')
const rankings = ref([])
const isLoading = ref(false)
const errorMessage = ref('')

const filteredRankings = computed(() => {
  if (selectedPlatform.value === 'all') return rankings.value
  return rankings.value.filter((game) => game.platform === selectedPlatform.value)
})

const platformBadgeClass = (platform) => {
  return platformBadgeClasses[platform] ?? 'bg-[rgba(167,229,211,0.4)]'
}

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

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

  isLoading.value = true
  errorMessage.value = ''

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

    rankings.value = Array.isArray(data?.data) ? 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 por plataforma. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

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