<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../lib/api'
import { toApiUrl } from '../lib/runtime'
import { useAuthStore } from '../stores/auth'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

const items = ref([])
const error = ref('')
const loadingFavoriteId = ref('')
const query = computed(() => (typeof route.query.q === 'string' ? route.query.q.trim().toLowerCase() : ''))
const games = computed(() => {
  const filtered = items.value
    .filter((item) => item.id !== 'freeform')
    .filter((item) => {
      if (!query.value) return true
      const haystack = `${item.name || ''} ${item.id || ''}`.toLowerCase()
      return haystack.includes(query.value)
    })

  return filtered.slice().sort((a, b) => {
    if (!!a.isFavorited !== !!b.isFavorited) return a.isFavorited ? -1 : 1
    const rankA = a.displayRank == null ? Number.MAX_SAFE_INTEGER : a.displayRank
    const rankB = b.displayRank == null ? Number.MAX_SAFE_INTEGER : b.displayRank
    if (rankA !== rankB) return rankA - rankB
    return (a.name || '').localeCompare(b.name || '', 'ko')
  })
})

async function loadGames() {
  try {
    const data = await api.listGames()
    items.value = data.games || []
  } catch (e) {
    error.value = '백엔드에 연결할 수 없어요. backend 서버가 실행 중인지 확인해주세요.'
  }
}

onMounted(loadGames)
watch(() => auth.user?.id, loadGames)

function goGame(gameId) {
  router.push(`/games/${gameId}`)
}

async function toggleFavorite(game, event) {
  event?.stopPropagation()
  if (!auth.user) {
    router.push(`/login?redirect=${encodeURIComponent(route.fullPath || '/')}`)
    return
  }
  if (!game?.id || loadingFavoriteId.value === game.id) return

  try {
    loadingFavoriteId.value = game.id
    const res = game.isFavorited ? await api.unfavoriteGame(game.id) : await api.favoriteGame(game.id)
    items.value = items.value.map((entry) => (entry.id === game.id ? { ...entry, ...res.game } : entry))
  } catch (e) {
    error.value = '즐겨찾기 변경에 실패했어요.'
  } finally {
    loadingFavoriteId.value = ''
  }
}

function thumbUrl(g) {
  return g.thumbnailSrc ? toApiUrl(g.thumbnailSrc) : ''
}
</script>

<template>
  <section class="pageHead">
    <div class="pageHead__main">
      <div class="pageHead__eyebrow">Workspace</div>
      <h1 class="pageHead__title">Game Library</h1>
      <p class="pageHead__desc">자주 쓰는 게임 템플릿을 빠르게 고르고, 필요하면 바로 커스텀 티어표를 시작할 수 있어요.</p>
      <p v-if="query" class="pageHead__searchState">"{{ query }}"에 맞는 게임 템플릿만 보고 있어요.</p>
    </div>
  </section>

  <div v-if="error" class="error">{{ error }}</div>
  <TransitionGroup v-if="games.length" name="libraryCard" tag="section" class="libraryGrid">
    <article v-for="g in games" :key="g.id" class="libraryCard">
      <button
        class="libraryCard__favorite"
        type="button"
        :class="{ 'libraryCard__favorite--active': g.isFavorited }"
        :disabled="loadingFavoriteId === g.id"
        @click.stop="toggleFavorite(g, $event)"
      >
        {{ g.isFavorited ? '★' : '☆' }}
      </button>
      <button class="libraryCard__main" type="button" @click="goGame(g.id)">
        <div class="libraryCard__thumbWrap">
        <img v-if="thumbUrl(g)" class="libraryCard__thumb" :src="thumbUrl(g)" :alt="g.name" />
        <div v-else class="libraryCard__thumbFallback">대표 썸네일</div>
      </div>
        <div class="libraryCard__body">
          <div class="libraryCard__title">{{ g.name }}</div>
          <div class="libraryCard__meta">{{ g.id }}</div>
        </div>
      </button>
    </article>
  </TransitionGroup>
  <div v-else class="libraryEmpty">{{ query ? '검색어에 맞는 게임 템플릿이 없어요.' : '표시할 게임 템플릿이 없어요.' }}</div>
</template>

<style scoped>
.libraryGrid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.error {
  margin: 0 0 16px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(239, 68, 68, 0.18);
  background: rgba(239, 68, 68, 0.1);
  color: rgba(255, 255, 255, 0.92);
}
.pageHead__searchState {
  margin-top: 8px;
  color: rgba(255, 255, 255, 0.62);
}
.libraryCard {
  position: relative;
  text-align: left;
  padding: 14px;
  border-radius: 22px;
  border: 1px solid rgba(255, 255, 255, 0.16);
  background: rgba(62, 62, 62, 0.82);
  color: rgba(255, 255, 255, 0.92);
  cursor: pointer;
  display: grid;
  gap: 12px;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
  transition: transform 0.16s ease, background 0.16s ease;
  will-change: transform, opacity;
}
.libraryCard:hover {
  background: rgba(70, 70, 70, 0.96);
  transform: translateY(-2px);
}
.libraryCard__main {
  display: grid;
  gap: 12px;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  text-align: left;
  cursor: pointer;
}
.libraryCard__favorite {
  position: absolute;
  bottom: 24px;
  right: 14px;
  width: 34px;
  height: 34px;
  border-radius: 999px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(15, 15, 15, 0.72);
  color: rgba(255, 255, 255, 0.82);
  font-size: 17px;
  line-height: 1;
  cursor: pointer;
  z-index: 2;
}
.libraryCard__favorite--active {
  color: #ffd86b;
}
.libraryCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.06);
  background: #555;
  overflow: hidden;
  display: grid;
  place-items: center;
}
.libraryCard__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.libraryCard__thumbFallback {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.4);
}
.libraryCard__body {
  display: grid;
}
.libraryCard__title {
  font-weight: 800;
  letter-spacing: -0.02em;
  font-size: 18px;
}
.libraryCard__meta {
  color: rgba(255, 255, 255, 0.6);
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.libraryCard-move,
.libraryCard-enter-active,
.libraryCard-leave-active {
  transition: transform 280ms ease, opacity 220ms ease;
}

.libraryCard-enter-from,
.libraryCard-leave-to {
  opacity: 0;
  transform: translateY(10px) scale(0.985);
}

.libraryCard-leave-active {
  position: absolute;
  width: calc(100% - 0px);
  pointer-events: none;
}

.libraryEmpty {
  padding: 20px 0;
  color: rgba(255, 255, 255, 0.62);
}
@media (max-width: 1400px) {
  .libraryGrid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
@media (max-width: 1200px) {
  .libraryGrid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 900px) {
  .libraryGrid {
    grid-template-columns: 1fr;
  }
}
@media (max-width: 720px) {
  .libraryGrid {
    grid-template-columns: 1fr;
  }
}
</style>
