<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(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 max-w-[800px] gap-8">
      <header class="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
        <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>
      </header>

      <div v-if="isLoading" class="grid gap-4" role="status" aria-live="polite">
        <div class="h-48 animate-pulse rounded-2xl bg-[#f0efed]"></div>
        <div class="h-8 w-2/3 animate-pulse rounded-xl bg-[#f0efed]"></div>
        <div class="h-4 w-1/3 animate-pulse rounded-xl bg-[#f0efed]"></div>
        <div class="h-24 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>

      <template v-else-if="game">
        <div class="overflow-hidden rounded-2xl border border-[#e7e5e4] bg-white shadow-[0_4px_16px_rgba(0,0,0,0.04)]">
          <div v-if="game.images?.header" class="relative h-48 w-full overflow-hidden bg-[#f0efed] sm:h-64">
            <img :src="game.images.header" :alt="game.title" class="h-full w-full object-cover" />
          </div>

          <div class="grid gap-6 p-6 md:p-8">
            <div class="flex flex-wrap items-start justify-between gap-4">
              <div class="grid gap-2">
                <h1 class="font-serif text-[32px] font-light leading-[1.1] tracking-[-0.64px] text-[#0c0a09]">
                  {{ game.title }}
                </h1>
                <p class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
                  {{ game.developer }}
                </p>
              </div>

              <div class="flex flex-wrap gap-2">
                <button type="button" :disabled="togglingFavorite"
                  :aria-label="isFavorited ? 'Remover dos favoritos' : 'Adicionar aos favoritos'"
                  @click="toggleFavorite"
                  class="inline-flex h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 text-[13px] font-medium transition hover:bg-[#f0efed] disabled:cursor-not-allowed disabled:opacity-50">
                  <Icon :name="togglingFavorite
                    ? 'mdi:loading'
                    : isFavorited
                      ? 'mdi:heart'
                      : 'mdi:heart-outline'
                    " :class="[
                      'text-sm',
                      togglingFavorite
                        ? 'animate-spin text-[#777169]'
                        : isFavorited
                          ? 'text-rose-500'
                          : 'text-[#777169]'
                    ]" />
                  <span>{{ isFavorited ? 'Favoritado' : 'Favoritar' }}</span>
                </button>

                <button v-if="!isEditing" type="button" @click="startEditing"
                  class="inline-flex h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 text-[13px] font-medium text-[#0c0a09] transition hover:bg-[#f0efed]">
                  <Icon name="mdi:pencil-outline" class="text-sm" />
                  Editar
                </button>

                <div v-if="confirmingDelete" class="flex gap-2">
                  <button type="button" :disabled="isDeleting" @click="deleteGame"
                    class="inline-flex h-9 items-center justify-center gap-1 rounded-full bg-red-50 px-4 text-[13px] font-medium text-red-600 transition hover:bg-red-100 disabled:opacity-50">
                    <Icon :name="isDeleting ? 'mdi:loading' : 'mdi:check'" class="text-sm"
                      :class="isDeleting && 'animate-spin'" />
                    Confirmar
                  </button>
                  <button type="button" @click="confirmingDelete = false"
                    class="inline-flex h-9 items-center justify-center rounded-full border border-[#e7e5e4] px-4 text-[13px] font-medium text-[#777169] transition hover:border-[#0c0a09]">
                    Cancelar
                  </button>
                </div>
                <button v-else type="button" @click="confirmingDelete = true"
                  class="inline-flex h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 text-[13px] font-medium text-[#777169] transition hover:border-red-300 hover:text-red-600">
                  <Icon name="mdi:trash-can-outline" class="text-sm" />
                  Deletar
                </button>
              </div>
            </div>

            <div v-if="!isEditing" class="grid gap-6">
              <div>
                <p class="mb-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  Descrição
                </p>
                <p class="text-[15px] leading-[1.6] tracking-[0.15px] text-[#0c0a09]">
                  {{ game.description }}
                </p>
              </div>

              <div class="grid gap-5 sm:grid-cols-2">
                <div>
                  <p class="mb-2 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                    Gêneros
                  </p>
                  <div class="flex flex-wrap gap-1.5">
                    <span v-for="genre in game.genres" :key="genre"
                      class="inline-flex items-center rounded-full bg-[rgba(196,184,232,0.4)] px-2.5 py-1 text-[12px] font-semibold uppercase leading-none tracking-[0.8px] text-[#0c0a09]">
                      {{ genre }}
                    </span>
                  </div>
                </div>

                <div>
                  <p class="mb-2 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                    Plataformas
                  </p>
                  <div class="flex flex-wrap gap-1.5">
                    <span v-for="platform in game.platforms" :key="platform"
                      class="inline-flex items-center rounded-full bg-[rgba(167,229,211,0.5)] px-2.5 py-1 text-[12px] font-semibold uppercase leading-none tracking-[0.8px] text-[#0c0a09]">
                      {{ platform }}
                    </span>
                  </div>
                </div>
              </div>

              <div v-if="
                game.system_requirements?.cpu ||
                game.system_requirements?.gpu ||
                game.system_requirements?.ram
              " class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] p-4">
                <p class="mb-3 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  Requisitos de sistema
                </p>
                <dl class="grid gap-2">
                  <div v-if="game.system_requirements.cpu" class="flex gap-3">
                    <dt class="w-10 shrink-0 text-[13px] font-semibold text-[#777169]">CPU</dt>
                    <dd class="text-[13px] text-[#0c0a09]">{{ game.system_requirements.cpu }}</dd>
                  </div>
                  <div v-if="game.system_requirements.gpu" class="flex gap-3">
                    <dt class="w-10 shrink-0 text-[13px] font-semibold text-[#777169]">GPU</dt>
                    <dd class="text-[13px] text-[#0c0a09]">{{ game.system_requirements.gpu }}</dd>
                  </div>
                  <div v-if="game.system_requirements.ram" class="flex gap-3">
                    <dt class="w-10 shrink-0 text-[13px] font-semibold text-[#777169]">RAM</dt>
                    <dd class="text-[13px] text-[#0c0a09]">{{ game.system_requirements.ram }}</dd>
                  </div>
                </dl>
              </div>

              <div class="flex items-center gap-2">
                <span :class="[
                  'inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.8px]',
                  game.active ? 'bg-emerald-50 text-emerald-700' : 'bg-[#f0efed] text-[#777169]'
                ]">
                  <span :class="[
                    'h-1.5 w-1.5 rounded-full',
                    game.active ? 'bg-emerald-500' : 'bg-[#d6d3d1]'
                  ]"></span>
                  {{ game.active ? 'Ativo' : 'Inativo' }}
                </span>
              </div>
            </div>

            <form v-else class="grid gap-5" @submit.prevent="saveEdit">
              <div v-if="editError"
                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">
                {{ editError }}
              </div>

              <div class="grid gap-1.5">
                <label
                  class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Título</label>
                <input v-model="editForm.title" type="text"
                  class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
              </div>

              <div class="grid gap-1.5">
                <label
                  class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Descrição</label>
                <textarea v-model="editForm.description" rows="3"
                  class="w-full resize-none rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white"></textarea>
              </div>

              <div class="grid gap-1.5">
                <label
                  class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Developer</label>
                <input v-model="editForm.developer" type="text"
                  class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
              </div>

              <div class="grid gap-5 md:grid-cols-2">
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Gêneros</label>
                  <input v-model="editForm.genresRaw" type="text" placeholder="Separe com vírgula"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Plataformas</label>
                  <input v-model="editForm.platformsRaw" type="text" placeholder="Separe com vírgula"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
              </div>

              <div class="grid gap-5 md:grid-cols-2">
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Thumbnail
                    URL</label>
                  <input v-model="editForm.thumbnail" type="url"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
                <div class="grid gap-1.5">
                  <label class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">Header
                    URL</label>
                  <input v-model="editForm.header" type="url"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
              </div>

              <div class="grid gap-5 md:grid-cols-3">
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">CPU</label>
                  <input v-model="editForm.cpu" type="text"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">GPU</label>
                  <input v-model="editForm.gpu" type="text"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
                <div class="grid gap-1.5">
                  <label
                    class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">RAM</label>
                  <input v-model="editForm.ram" type="text"
                    class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
                </div>
              </div>

              <div class="flex items-center gap-3">
                <input id="active-edit" v-model="editForm.active" type="checkbox"
                  class="h-4 w-4 rounded border-[#d6d3d1] accent-[#292524]" />
                <label for="active-edit" class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#0c0a09]">
                  Jogo ativo no catálogo
                </label>
              </div>

              <div class="flex justify-end gap-3 border-t border-[#e7e5e4] pt-5">
                <button type="button" @click="cancelEditing"
                  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]">
                  Cancelar
                </button>
                <button type="submit" :disabled="isSaving"
                  class="inline-flex h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 text-[15px] font-medium leading-none text-white transition hover:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70">
                  <Icon v-if="isSaving" name="mdi:loading" class="animate-spin text-base" />
                  <span>{{ isSaving ? 'Salvando...' : 'Salvar alterações' }}</span>
                </button>
              </div>
            </form>
          </div>
        </div>

        <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>
      </template>
    </main>
  </div>
</template>

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

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 route = useRoute()
const { $toast } = useNuxtApp()

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

const game = ref(null)
const isLoading = ref(false)
const errorMessage = ref('')
const isFavorited = ref(false)
const togglingFavorite = ref(false)
const confirmingDelete = ref(false)
const isDeleting = ref(false)
const isEditing = ref(false)
const isSaving = ref(false)
const editError = ref('')

const editForm = reactive({
  title: '',
  description: '',
  developer: '',
  genresRaw: '',
  platformsRaw: '',
  thumbnail: '',
  header: '',
  cpu: '',
  gpu: '',
  ram: '',
  active: true
})

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

function startEditing() {
  editForm.title = game.value.title ?? ''
  editForm.description = game.value.description ?? ''
  editForm.developer = game.value.developer ?? ''
  editForm.genresRaw = (game.value.genres ?? []).join(', ')
  editForm.platformsRaw = (game.value.platforms ?? []).join(', ')
  editForm.thumbnail = game.value.images?.thumbnail ?? ''
  editForm.header = game.value.images?.header ?? ''
  editForm.cpu = game.value.system_requirements?.cpu ?? ''
  editForm.gpu = game.value.system_requirements?.gpu ?? ''
  editForm.ram = game.value.system_requirements?.ram ?? ''
  editForm.active = game.value.active ?? true
  isEditing.value = true
}

function cancelEditing() {
  isEditing.value = false
  editError.value = ''
}

async function fetchGame() {
  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/${route.params.id_ou_slug}`,
      {
        headers: { Authorization: `Bearer ${token.value}` }
      }
    )
    game.value = data?.data ?? null

    if (!game.value) {
      errorMessage.value = 'Jogo não encontrado.'
    }
  } 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 o jogo. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

async function fetchFavoriteStatus() {
  if (!token.value || !game.value) return

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

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

  togglingFavorite.value = true
  const gameId = game.value.title

  try {
    if (isFavorited.value) {
      await $fetch(`${WISHLIST_API_BASE_URL}/api/wishlist/${encodeURIComponent(gameId)}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token.value}` }
      })
      isFavorited.value = false
      $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 }
      })
      isFavorited.value = true
      $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 {
    togglingFavorite.value = false
  }
}

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

  editError.value = ''
  isSaving.value = true

  const body = {
    title: editForm.title || undefined,
    description: editForm.description || undefined,
    developer: editForm.developer || undefined,
    genres: editForm.genresRaw
      ? editForm.genresRaw
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
      : undefined,
    platforms: editForm.platformsRaw
      ? editForm.platformsRaw
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
      : undefined,
    active: editForm.active
  }

  if (editForm.thumbnail || editForm.header) {
    body.images = {}
    if (editForm.thumbnail) body.images.thumbnail = editForm.thumbnail
    if (editForm.header) body.images.header = editForm.header
  }

  if (editForm.cpu || editForm.gpu || editForm.ram) {
    body.system_requirements = {}
    if (editForm.cpu) body.system_requirements.cpu = editForm.cpu
    if (editForm.gpu) body.system_requirements.gpu = editForm.gpu
    if (editForm.ram) body.system_requirements.ram = editForm.ram
  }

  try {
    const data = await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games/${game.value.id}`, {
      method: 'PATCH',
      headers: { Authorization: `Bearer ${token.value}` },
      body
    })
    game.value = data?.data ?? game.value
    isEditing.value = false
    $toast.success('Jogo atualizado com sucesso!', { 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
    }
    editError.value = error?.data?.message ?? 'Erro ao salvar alterações. Tente novamente.'
    $toast.error(editError.value, { duration: 8000 })
  } finally {
    isSaving.value = false
  }
}

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

  isDeleting.value = true

  try {
    await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games/${game.value.id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token.value}` }
    })
    $toast.success(`${game.value.title} removido do catálogo.`, { duration: 4000 })
    await navigateTo('/catalogo')
  } 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 deletar o jogo. Tente novamente.', { duration: 6000 })
  } finally {
    isDeleting.value = false
    confirmingDelete.value = false
  }
}

onMounted(async () => {
  await fetchGame()
  fetchFavoriteStatus()
})
</script>
