<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.6),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(244,197,168,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="catalogo-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.6)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Catálogo
          </p>
          <h1 id="catalogo-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]">
            Catálogo de jogos
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Explore o catálogo completo de jogos, filtre por gênero e plataforma.
          </p>
        </div>

        <div class="flex min-w-0 shrink-0 flex-col gap-3 sm:flex-row sm:items-center">
          <NuxtLink to="/catalogo/criar"
            class="inline-flex min-h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 py-2 text-[15px] font-medium leading-none text-white transition hover:bg-[#0c0a09]">
            <Icon name="mdi:plus" class="text-base" />
            Novo jogo
          </NuxtLink>
        </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 do catálogo de jogos">
        <div class="grid min-w-0 gap-5 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] xl:items-end">
          <AppSelect id="genre-filter" v-model="selectedGenre" label="Gênero" :options="genreOptions"
            :disabled="isLoading" />
          <AppSelect id="platform-filter" v-model="selectedPlatform" label="Plataforma" :options="platformOptions"
            :disabled="isLoading" />
        </div>

        <div v-if="isLoading" class="grid min-w-0 gap-4 md:grid-cols-2 2xl:grid-cols-3" role="status"
          aria-live="polite">
          <div v-for="item in 6" :key="item" class="h-56 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="!filteredGames.length"
          class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-8 text-center" role="status">
          <Icon name="mdi:gamepad-variant-outline" class="mb-3 text-4xl text-[#d6d3d1]" />
          <p class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            Nenhum jogo encontrado com esses filtros.
          </p>
        </div>

        <div v-else class="grid min-w-0 gap-4 md:grid-cols-2 2xl:grid-cols-3">
          <article v-for="game in filteredGames" :key="game.id"
            class="flex min-w-0 flex-col overflow-hidden rounded-xl border border-[#e7e5e4] bg-white transition hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)]">
            <div class="relative h-36 bg-[#f0efed]">
              <img v-if="game.images?.thumbnail" :src="game.images.thumbnail" :alt="game.title"
                class="h-full w-full object-cover" />
              <div v-else class="flex h-full w-full items-center justify-center">
                <Icon name="mdi:gamepad-variant-outline" class="text-4xl text-[#d6d3d1]" />
              </div>

              <button type="button" :disabled="togglingId === game.title" :aria-label="favoriteIds.has(game.title) ? 'Remover dos favoritos' : 'Adicionar aos favoritos'
                " @click="toggleFavorite(game)"
                class="absolute right-2 top-2 inline-flex h-8 w-8 items-center justify-center rounded-full bg-white/80 shadow backdrop-blur-sm transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-50">
                <Icon :name="togglingId === game.title
                  ? 'mdi:loading'
                  : favoriteIds.has(game.title)
                    ? 'mdi:heart'
                    : 'mdi:heart-outline'
                  " :class="[
                    'text-base',
                    togglingId === game.title
                      ? 'animate-spin text-[#777169]'
                      : favoriteIds.has(game.title)
                        ? 'text-rose-500'
                        : 'text-[#777169]'
                  ]" />
              </button>
            </div>

            <div class="flex flex-1 flex-col gap-3 p-4">
              <div class="grid gap-1">
                <h3 class="min-w-0 break-words text-base font-medium leading-6 tracking-[0.16px] text-[#0c0a09]">
                  {{ game.title }}
                </h3>
                <p class="text-xs leading-[1.4] tracking-[0.16px] text-[#777169]">
                  {{ game.developer }}
                </p>
              </div>

              <div class="flex flex-wrap gap-1.5">
                <span v-for="genre in game.genres?.slice(0, 3)" :key="genre"
                  class="inline-flex items-center rounded-full bg-[rgba(196,184,232,0.4)] px-2 py-0.5 text-[11px] font-semibold uppercase leading-none tracking-[0.8px] text-[#0c0a09]">
                  {{ genre }}
                </span>
              </div>

              <p class="line-clamp-2 flex-1 text-[13px] leading-[1.5] tracking-[0.13px] text-[#4e4e4e]">
                {{ game.description }}
              </p>

              <div
                class="flex min-w-0 flex-col gap-2 border-t border-[#f0efed] pt-3 sm:flex-row sm:items-center sm:justify-between">
                <div v-if="confirmingDeleteId === game.id" class="flex flex-wrap gap-2">
                  <button type="button" :disabled="deletingId === game.id" @click="confirmDelete(game)"
                    class="inline-flex h-7 items-center justify-center gap-1 rounded-full bg-red-50 px-3 text-[12px] font-medium text-red-600 transition hover:bg-red-100 disabled:opacity-50">
                    <Icon :name="deletingId === game.id ? 'mdi:loading' : 'mdi:check'" class="text-xs"
                      :class="deletingId === game.id && 'animate-spin'" />
                    Confirmar
                  </button>
                  <button type="button" @click="confirmingDeleteId = null"
                    class="inline-flex h-7 items-center justify-center rounded-full border border-[#e7e5e4] px-3 text-[12px] font-medium text-[#777169] transition hover:border-[#0c0a09]">
                    Cancelar
                  </button>
                </div>

                <button v-else type="button" :aria-label="`Deletar ${game.title}`" @click="confirmingDeleteId = game.id"
                  class="inline-flex h-7 w-7 items-center justify-center rounded-full transition hover:bg-red-50 hover:text-red-500">
                  <Icon name="mdi:trash-can-outline" class="text-sm text-[#777169]" />
                </button>

                <NuxtLink :to="`/catalogo/${game.id}`"
                  class="inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-[#e7e5e4] px-3 py-1 text-center text-[12px] font-medium text-[#0c0a09] transition hover:border-[#0c0a09]">
                  Ver detalhes
                  <Icon name="mdi:arrow-right" class="text-xs" />
                </NuxtLink>
              </div>
            </div>
          </article>
        </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://catalogo-jogos-sd-production.up.railway.app</span>
          &nbsp;·&nbsp; Feito por Lucas Kauã
        </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: 'Catálogo de jogos | GameVerse',
  meta: [
    {
      name: 'description',
      content: 'Explore o catálogo completo de jogos e filtre por gênero e plataforma.'
    }
  ]
})

const CATALOG_API_BASE_URL = 'https://catalogo-jogos-sd-production.up.railway.app'
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 games = ref([])
const isLoading = ref(false)
const errorMessage = ref('')
const favoriteIds = ref(new Set())
const togglingId = ref(null)
const confirmingDeleteId = ref(null)
const deletingId = ref(null)
const selectedGenre = ref('')
const selectedPlatform = ref('')

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

const uniqueGenres = computed(() => {
  const all = games.value.flatMap((g) => g.genres ?? [])
  return [...new Set(all)].sort()
})

const uniquePlatforms = computed(() => {
  const all = games.value.flatMap((g) => g.platforms ?? [])
  return [...new Set(all)].sort()
})

const genreOptions = computed(() => [
  { label: 'Todos os gêneros', value: '' },
  ...uniqueGenres.value.map((g) => ({ label: g, value: g }))
])

const platformOptions = computed(() => [
  { label: 'Todas as plataformas', value: '' },
  ...uniquePlatforms.value.map((p) => ({ label: p, value: p }))
])

const filteredGames = computed(() => {
  return games.value
    .filter((g) => !selectedGenre.value || g.genres?.includes(selectedGenre.value))
    .filter((g) => !selectedPlatform.value || g.platforms?.includes(selectedPlatform.value))
})

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

  isLoading.value = true
  errorMessage.value = ''

  try {
    const data = await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games`, {
      headers: { Authorization: `Bearer ${token.value}` }
    })
    games.value = data?.data ?? []
  } catch (error) {
    errorMessage.value = error?.data?.message ?? 'Erro ao carregar o catálogo. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

async function fetchFavorites() {
  if (!token.value) return

  try {
    const data = await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist`, {
      headers: { Authorization: `Bearer ${token.value}` }
    })
    favoriteIds.value = new Set(
      (data?.data ?? [])
        .filter((item) => item.is_favorite === 1 || item.is_favorite === true)
        .map((item) => item.game_id)
    )
  } catch {
    // falha silenciosa
  }
}

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

  const gameId = game.title
  togglingId.value = gameId

  try {
    if (favoriteIds.value.has(gameId)) {
      await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist/${encodeURIComponent(gameId)}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token.value}` }
      })
      favoriteIds.value = new Set([...favoriteIds.value].filter((id) => id !== gameId))
      $toast.success(`${gameId} removido dos favoritos.`, { duration: 4000 })
    } else {
      await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token.value}` },
        body: { game_id: gameId, is_wishlist: false, is_favorite: true, price_alert: false }
      })
      favoriteIds.value = new Set([...favoriteIds.value, gameId])
      $toast.success(`${gameId} adicionado aos 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 atualizar favoritos. Tente novamente.', { duration: 6000 })
  } finally {
    togglingId.value = null
  }
}

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

  deletingId.value = game.id

  try {
    await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games/${game.id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token.value}` }
    })
    games.value = games.value.filter((g) => g.id !== game.id)
    confirmingDeleteId.value = null
    $toast.success(`${game.title} removido do catálogo.`, { duration: 4000 })
  } catch (error) {
    $toast.error(error?.data?.message ?? 'Erro ao remover o jogo. Tente novamente.', {
      duration: 6000
    })
  } finally {
    deletingId.value = null
  }
}

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