<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-[800px] gap-6 md:gap-8">
      <header class="flex flex-col gap-4">
        <div class="flex flex-col gap-4 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]">
            Reviews
          </p>
          <button type="button" @click="showCreateForm = !showCreateForm"
            class="inline-flex min-h-9 items-center justify-center gap-2 self-start rounded-full bg-[#292524] px-4 py-2 text-[13px] font-medium text-white transition hover:bg-[#0c0a09] sm:self-auto">
            <Icon :name="showCreateForm ? 'mdi:close' : 'mdi:pencil-plus-outline'" class="text-sm" />
            {{ showCreateForm ? 'Cancelar' : 'Escrever review' }}
          </button>
        </div>

        <!-- Toggle Meus reviews / Todos -->
        <div class="inline-flex rounded-full border border-[#e7e5e4] bg-white p-1 shadow-[0_2px_8px_rgba(0,0,0,0.04)]">
          <button type="button" @click="setView(true)" :class="[
            'inline-flex min-h-8 items-center gap-2 rounded-full px-4 py-1.5 text-[13px] font-medium transition',
            showOnlyMine ? 'bg-[#292524] text-white' : 'text-[#777169] hover:text-[#0c0a09]'
          ]">
            <Icon name="mdi:account-outline" class="text-sm" />
            Meus reviews
          </button>
          <button type="button" @click="setView(false)" :class="[
            'inline-flex min-h-8 items-center gap-2 rounded-full px-4 py-1.5 text-[13px] font-medium transition',
            !showOnlyMine ? 'bg-[#292524] text-white' : 'text-[#777169] hover:text-[#0c0a09]'
          ]">
            <Icon name="mdi:earth" class="text-sm" />
            Todos os reviews
          </button>
        </div>
      </header>

      <!-- Formulário de criar review -->
      <div v-if="showCreateForm"
        class="overflow-hidden rounded-2xl border border-[#e7e5e4] bg-white shadow-[0_4px_16px_rgba(0,0,0,0.04)]">
        <div class="grid gap-5 p-4 sm:p-5 md:p-6">
          <h2 class="font-serif text-[22px] font-light leading-[1.2] tracking-[-0.32px] text-[#0c0a09]">
            Novo review
          </h2>

          <div v-if="createError"
            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">
            {{ createError }}
          </div>

          <form class="grid gap-4" @submit.prevent="createReview">
            <div class="grid gap-1.5">
              <label class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                ID do jogo
              </label>
              <input v-model="createForm.idJogo" type="number" min="1" placeholder="Ex: 123" required
                class="w-full min-w-0 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]">
                Nota
              </label>
              <div class="flex gap-2">
                <button v-for="n in 5" :key="n" type="button" @click="createForm.nota = n" :class="[
                  'inline-flex h-10 w-10 items-center justify-center rounded-xl border text-[15px] font-semibold transition',
                  createForm.nota === n
                    ? 'border-[#292524] bg-[#292524] text-white'
                    : 'border-[#e7e5e4] bg-[#fafafa] text-[#777169] hover:border-[#0c0a09]'
                ]">
                  {{ n }}
                </button>
              </div>
            </div>

            <div class="grid gap-1.5">
              <label class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Comentário
              </label>
              <textarea v-model="createForm.comentario" rows="3" placeholder="Escreva seu review..." required
                class="w-full min-w-0 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="flex justify-end">
              <button type="submit" :disabled="isCreating || !createForm.nota"
                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] disabled:cursor-not-allowed disabled:opacity-70">
                <Icon v-if="isCreating" name="mdi:loading" class="animate-spin text-base" />
                <span>{{ isCreating ? 'Publicando...' : 'Publicar review' }}</span>
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Filtros -->
      <div class="overflow-hidden rounded-2xl border border-[#e7e5e4] bg-white shadow-[0_4px_16px_rgba(0,0,0,0.04)]">
        <div class="grid gap-4 p-4 sm:p-5 md:p-6">
          <div class="flex flex-col gap-3 sm:flex-row sm:items-end">
            <div class="grid flex-1 gap-1.5">
              <label class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Filtrar por ID do jogo
              </label>
              <input v-model="filterIdJogo" type="number" min="1" placeholder="Deixe em branco para ver todos"
                class="w-full min-w-0 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"
                @keydown.enter.prevent="applyFilter" />
            </div>
            <button type="button" @click="applyFilter"
              class="inline-flex min-h-10 shrink-0 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 py-2 text-[13px] font-medium text-[#0c0a09] transition hover:bg-[#f0efed]">
              <Icon name="mdi:magnify" class="text-sm" />
              Buscar
            </button>
            <button v-if="activeFilter" type="button" @click="clearFilter"
              class="inline-flex min-h-10 shrink-0 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 py-2 text-[13px] font-medium text-[#777169] transition hover:border-[#0c0a09]">
              <Icon name="mdi:close" class="text-sm" />
              Limpar
            </button>
          </div>

          <!-- Nota média -->
          <div v-if="activeFilter && mediaData" class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] p-4">
            <div v-if="isLoadingMedia" class="flex items-center gap-2">
              <div class="h-4 w-4 animate-spin rounded-full border-2 border-[#d6d3d1] border-t-[#0c0a09]"></div>
              <span class="text-[13px] text-[#777169]">Carregando média...</span>
            </div>
            <div v-else class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  Nota média — Jogo #{{ activeFilter }}
                </p>
                <div class="mt-2 flex items-baseline gap-2">
                  <span class="font-serif text-[32px] font-light leading-none tracking-[-0.64px] text-[#0c0a09]">
                    {{ mediaData.media !== null ? mediaData.media.toFixed(1) : '—' }}
                  </span>
                  <span class="text-[15px] text-[#777169]">/ 5</span>
                </div>
              </div>
              <div class="text-right">
                <p class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  Avaliações
                </p>
                <p class="mt-1 text-[22px] font-medium leading-none text-[#0c0a09]">
                  {{ mediaData.numeroAvaliacoes.toLocaleString('pt-BR') }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Lista de reviews -->
      <div v-if="isLoading" class="grid gap-3" role="status" aria-live="polite">
        <div v-for="i in 4" :key="i" class="h-28 animate-pulse rounded-2xl 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>
        <div v-if="reviews.length === 0"
          class="rounded-2xl border border-[#e7e5e4] bg-white px-6 py-12 text-center shadow-[0_4px_16px_rgba(0,0,0,0.04)]">
          <Icon name="mdi:star-off-outline" class="mb-3 text-4xl text-[#d6d3d1]" />
          <p class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#777169]">
            {{ showOnlyMine ? 'Você ainda não escreveu nenhum review.' : 'Nenhum review encontrado.' }}
          </p>
        </div>

        <div v-else class="grid gap-3">
          <div v-for="review in reviews" :key="review.idReview"
            class="overflow-hidden rounded-2xl border border-[#e7e5e4] bg-white shadow-[0_4px_16px_rgba(0,0,0,0.04)]">

            <!-- Modo visualização -->
            <div v-if="editingReviewId !== review.idReview" class="grid gap-4 p-4 sm:p-5">
              <div class="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                <div class="flex min-w-0 items-center gap-3">
                  <span :class="[
                    'inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-sm font-bold',
                    review.nota >= 4
                      ? 'bg-emerald-50 text-emerald-700'
                      : review.nota === 3
                        ? 'bg-amber-50 text-amber-700'
                        : 'bg-red-50 text-red-700'
                  ]">
                    {{ review.nota }}
                  </span>
                  <div class="min-w-0">
                    <p class="min-w-0 truncate text-[15px] font-medium leading-[1.47] tracking-[0.15px] text-[#0c0a09]">
                      {{ displayNames[String(review.idUsuario)] ?? review.nomeUsuario ?? '...' }}
                    </p>
                    <p class="text-[13px] leading-[1.5] tracking-[0.13px] text-[#777169]">
                      Jogo #{{ review.idJogo }} · {{ formatDate(review.dataCriacao) }}
                    </p>
                  </div>
                </div>

                <div v-if="userId && String(review.idUsuario) === String(userId)" class="flex shrink-0 gap-2">
                  <button type="button" @click="startEdit(review)"
                    class="inline-flex min-h-8 items-center justify-center gap-1.5 rounded-full border border-[#e7e5e4] px-3 py-1.5 text-[12px] font-medium text-[#0c0a09] transition hover:bg-[#f0efed]">
                    <Icon name="mdi:pencil-outline" class="text-xs" />
                    Editar
                  </button>

                  <div v-if="confirmingDeleteId === review.idReview" class="flex gap-1.5">
                    <button type="button" :disabled="isDeleting" @click="deleteReview(review.idReview)"
                      class="inline-flex min-h-8 items-center justify-center gap-1 rounded-full bg-red-50 px-3 py-1.5 text-[12px] font-medium text-red-600 transition hover:bg-red-100 disabled:opacity-50">
                      <Icon :name="isDeleting ? 'mdi:loading' : 'mdi:check'" class="text-xs"
                        :class="isDeleting && 'animate-spin'" />
                      Confirmar
                    </button>
                    <button type="button" @click="confirmingDeleteId = null"
                      class="inline-flex min-h-8 items-center justify-center rounded-full border border-[#e7e5e4] px-3 py-1.5 text-[12px] font-medium text-[#777169] transition hover:border-[#0c0a09]">
                      Cancelar
                    </button>
                  </div>
                  <button v-else type="button" @click="confirmingDeleteId = review.idReview"
                    class="inline-flex min-h-8 items-center justify-center gap-1.5 rounded-full border border-[#e7e5e4] px-3 py-1.5 text-[12px] font-medium text-[#777169] transition hover:border-red-300 hover:text-red-600">
                    <Icon name="mdi:trash-can-outline" class="text-xs" />
                    Deletar
                  </button>
                </div>
              </div>

              <p class="text-[15px] leading-[1.6] tracking-[0.15px] text-[#0c0a09]">
                {{ review.comentario }}
              </p>
            </div>

            <!-- Modo edição inline -->
            <form v-else class="grid gap-4 p-4 sm:p-5" @submit.prevent="saveEdit(review.idReview)">
              <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]">
                  Nota
                </label>
                <div class="flex gap-2">
                  <button v-for="n in 5" :key="n" type="button" @click="editForm.nota = n" :class="[
                    'inline-flex h-10 w-10 items-center justify-center rounded-xl border text-[15px] font-semibold transition',
                    editForm.nota === n
                      ? 'border-[#292524] bg-[#292524] text-white'
                      : 'border-[#e7e5e4] bg-[#fafafa] text-[#777169] hover:border-[#0c0a09]'
                  ]">
                    {{ n }}
                  </button>
                </div>
              </div>

              <div class="grid gap-1.5">
                <label class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                  Comentário
                </label>
                <textarea v-model="editForm.comentario" rows="3" required
                  class="w-full min-w-0 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="flex justify-end gap-3">
                <button type="button" @click="cancelEdit"
                  class="inline-flex min-h-10 items-center justify-center rounded-full border border-[#d6d3d1] bg-transparent px-5 py-2 text-[15px] font-medium leading-none text-[#0c0a09] transition hover:border-[#0c0a09]">
                  Cancelar
                </button>
                <button type="submit" :disabled="isSaving || !editForm.nota"
                  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] 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>

        <!-- Paginação -->
        <div v-if="total > tamanhoPagina" class="flex items-center justify-between gap-3">
          <button type="button" :disabled="pagina <= 1" @click="goToPage(pagina - 1)"
            class="inline-flex min-h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 py-2 text-[13px] font-medium text-[#0c0a09] transition hover:bg-[#f0efed] disabled:cursor-not-allowed disabled:opacity-40">
            <Icon name="mdi:chevron-left" class="text-sm" />
            Anterior
          </button>
          <span class="text-[13px] leading-[1.5] tracking-[0.13px] text-[#777169]">
            Página {{ pagina }} · {{ total }} resultado{{ total !== 1 ? 's' : '' }}
          </span>
          <button type="button" :disabled="pagina * tamanhoPagina >= total" @click="goToPage(pagina + 1)"
            class="inline-flex min-h-9 items-center justify-center gap-2 rounded-full border border-[#e7e5e4] px-4 py-2 text-[13px] font-medium text-[#0c0a09] transition hover:bg-[#f0efed] disabled:cursor-not-allowed disabled:opacity-40">
            Próxima
            <Icon name="mdi:chevron-right" class="text-sm" />
          </button>
        </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://temp-reviews.onrender.com</span>
            &nbsp;·&nbsp; Feito por Kate/Luan
          </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'
})

useHead({
  title: 'Reviews | GameVerse',
  meta: [
    {
      name: 'description',
      content: 'Veja, crie e gerencie reviews de jogos do catálogo GameVerse.'
    }
  ]
})

const REVIEWS_API_BASE_URL = 'https://temp-reviews.onrender.com'

const { $toast } = useNuxtApp()

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

const reviews = ref([])
const total = ref(0)
const isLoading = ref(false)
const errorMessage = ref('')

// Mapa de idUsuario → nome de exibição, populado após cada fetch
const displayNames = ref({})

async function resolveDisplayNames(items) {
  const uniqueIds = [...new Set(items.map((r) => String(r.idUsuario)))]
  const toFetch = uniqueIds.filter((id) => !(id in displayNames.value))
  if (!toFetch.length) return

  const results = await Promise.allSettled(
    toFetch.map((id) =>
      $fetch(`/api/profile/${id}`, {
        headers: { Authorization: `Bearer ${token.value}` }
      })
    )
  )

  const patch = {}
  toFetch.forEach((id, i) => {
    const result = results[i]
    patch[id] =
      result.status === 'fulfilled' && result.value?.displayName
        ? result.value.displayName
        : 'Usuário Anônimo (externo)'
  })

  displayNames.value = { ...displayNames.value, ...patch }
}

const mediaData = ref(null)
const isLoadingMedia = ref(false)

const filterIdJogo = ref('')
const activeFilter = ref('')
const pagina = ref(1)
const tamanhoPagina = 10

const userId = ref(null)
const showOnlyMine = ref(true)

const showCreateForm = ref(false)
const createForm = reactive({ idJogo: '', nota: 0, comentario: '' })
const isCreating = ref(false)
const createError = ref('')

const editingReviewId = ref(null)
const editForm = reactive({ nota: 0, comentario: '' })
const isSaving = ref(false)
const editError = ref('')

const isDeleting = ref(false)
const confirmingDeleteId = ref(null)

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

function formatDate(iso) {
  if (!iso) return ''
  return new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(
    new Date(iso)
  )
}

async function fetchProfile() {
  if (!token.value) {
    await navigateTo('/login')
    return
  }
  try {
    const data = await $fetch('/profile/me', {
      headers: { Authorization: `Bearer ${token.value}` }
    })
    userId.value = data?.user_id ?? data?.id ?? null
    console.log('[Reviews] userId carregado:', userId.value)
  } catch (e) {
    console.warn('[Reviews] Falha ao carregar perfil:', e)
    // falha silenciosa — usuário ainda pode visualizar reviews
  }
}

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

  isLoading.value = true
  errorMessage.value = ''

  try {
    const query = {
      pagina: pagina.value,
      tamanho_pagina: tamanhoPagina
    }
    if (showOnlyMine.value && userId.value) query.id_usuario = userId.value
    if (activeFilter.value) query.id_jogo = Number(activeFilter.value)

    const data = await $fetch(`${REVIEWS_API_BASE_URL}/api/v1/reviews`, {
      query,
      headers: { Authorization: `Bearer ${token.value}` }
    })

    reviews.value = data?.itens ?? []
    total.value = data?.total ?? 0
    resolveDisplayNames(reviews.value)
  } 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 reviews. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

async function fetchMedia() {
  if (!activeFilter.value) {
    mediaData.value = null
    return
  }

  isLoadingMedia.value = true
  try {
    const data = await $fetch(
      `${REVIEWS_API_BASE_URL}/api/v1/reviews/jogo/${activeFilter.value}/media`,
      { headers: { Authorization: `Bearer ${token.value}` } }
    )
    mediaData.value = data
  } catch {
    mediaData.value = null
  } finally {
    isLoadingMedia.value = false
  }
}

async function setView(onlyMine) {
  showOnlyMine.value = onlyMine
  pagina.value = 1
  filterIdJogo.value = ''
  activeFilter.value = ''
  mediaData.value = null
  await fetchReviews()
}

async function applyFilter() {
  activeFilter.value = filterIdJogo.value
  pagina.value = 1
  await fetchReviews()
  await fetchMedia()
}

async function clearFilter() {
  filterIdJogo.value = ''
  activeFilter.value = ''
  mediaData.value = null
  pagina.value = 1
  await fetchReviews()
}

async function goToPage(n) {
  pagina.value = n
  await fetchReviews()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

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

  isCreating.value = true
  createError.value = ''

  try {
    await $fetch(`${REVIEWS_API_BASE_URL}/api/v1/reviews`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token.value}` },
      body: {
        idUsuario: userId.value,
        idJogo: Number(createForm.idJogo),
        nota: createForm.nota,
        comentario: createForm.comentario
      }
    })

    $toast.success('Review publicado com sucesso!', { duration: 4000 })
    showCreateForm.value = false
    createForm.idJogo = ''
    createForm.nota = 0
    createForm.comentario = ''
    pagina.value = 1
    await fetchReviews()
    if (activeFilter.value) await fetchMedia()
  } 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
    }
    if (statusCode === 409) {
      createError.value = error?.data?.mensagem ?? 'Você já realizou um review deste jogo.'
      return
    }
    createError.value = error?.data?.mensagem ?? error?.data?.message ?? 'Erro ao publicar review. Tente novamente.'
  } finally {
    isCreating.value = false
  }
}

function startEdit(review) {
  editingReviewId.value = review.idReview
  editForm.nota = review.nota
  editForm.comentario = review.comentario
  editError.value = ''
  confirmingDeleteId.value = null
}

function cancelEdit() {
  editingReviewId.value = null
  editError.value = ''
}

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

  isSaving.value = true
  editError.value = ''

  try {
    const updated = await $fetch(`${REVIEWS_API_BASE_URL}/api/v1/reviews/${idReview}`, {
      method: 'PUT',
      headers: { Authorization: `Bearer ${token.value}` },
      body: { nota: editForm.nota, comentario: editForm.comentario }
    })

    const idx = reviews.value.findIndex((r) => r.idReview === idReview)
    if (idx !== -1) reviews.value[idx] = updated

    editingReviewId.value = null
    $toast.success('Review atualizado com sucesso!', { duration: 4000 })
    if (activeFilter.value) await fetchMedia()
  } 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?.mensagem ?? error?.data?.message ?? 'Erro ao salvar alterações. Tente novamente.'
    $toast.error(editError.value, { duration: 8000 })
  } finally {
    isSaving.value = false
  }
}

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

  isDeleting.value = true

  try {
    await $fetch(`${REVIEWS_API_BASE_URL}/api/v1/reviews/${idReview}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token.value}` }
    })

    reviews.value = reviews.value.filter((r) => r.idReview !== idReview)
    total.value = Math.max(0, total.value - 1)
    confirmingDeleteId.value = null
    $toast.success('Review removido com sucesso.', { duration: 4000 })
    if (activeFilter.value) await fetchMedia()
  } 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 remover review. Tente novamente.', { duration: 6000 })
  } finally {
    isDeleting.value = false
  }
}

onMounted(async () => {
  await fetchProfile()
  await fetchReviews()
})
</script>
