<script setup>
import { computed, onMounted, ref } 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 gameId = computed(() => route.params.gameId)

const gameName = ref('')
const tierLists = ref([])
const error = ref('')
const query = ref('')

function fmt(ts) {
  return new Date(ts).toLocaleString(undefined, {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function displayNameOf(tierList) {
  return tierList.authorName || '알 수 없음'
}

function avatarSrcOf(tierList) {
  return tierList.authorAvatarSrc ? toApiUrl(tierList.authorAvatarSrc) : ''
}

function avatarFallbackOf(tierList) {
  return (tierList.authorAccountName || 'u').trim().charAt(0).toUpperCase() || '?'
}

function tierListThumbnailUrl(tierList) {
  return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}

onMounted(async () => {
  await loadTierLists()
})

async function loadTierLists() {
  try {
    const [gameRes, listRes] = await Promise.all([
      api.getGame(gameId.value),
      api.searchPublicTierLists(gameId.value, query.value),
    ])
    gameName.value = gameRes.game?.name || gameId.value
    tierLists.value = listRes.tierLists || []
  } catch (e) {
    error.value = '게임 정보를 불러오지 못했어요.'
  }
}

function createNew() {
  if (!auth.user) {
    router.push(`/login?redirect=/editor/${gameId.value}/new`)
    return
  }
  router.push(`/editor/${gameId.value}/new`)
}

function openTierList(id) {
  router.push(`/editor/${gameId.value}/${id}`)
}

function submitSearch() {
  loadTierLists()
}
</script>

<template>
  <section class="head">
    <div class="head__left">
      <div class="kicker">게임</div>
      <h2 class="title">{{ gameName || gameId }}</h2>
      <p class="desc">새 티어표를 만들거나, 다른 사람들이 올린 티어표를 확인하세요.</p>
    </div>
    <div class="head__right">
      <button class="primary" @click="createNew">{{ auth.user ? '새로운 티어표 만들기' : '로그인 후 새 티어표 만들기' }}</button>
    </div>
  </section>

  <div v-if="error" class="error">{{ error }}</div>
  <section class="panel">
    <div class="panel__head">
      <div class="panel__title">공개 티어표</div>
      <div class="searchBar">
        <input v-model="query" class="searchBar__input" placeholder="제목 또는 작성자 검색" @keydown.enter.prevent="submitSearch" />
        <button class="searchBar__button" @click="submitSearch">검색</button>
      </div>
    </div>
    <div v-if="tierLists.length === 0" class="empty">아직 공개 티어표가 없어요.</div>
    <div v-else class="list">
      <article v-for="t in tierLists" :key="t.id" class="row">
        <button class="row__body" @click="openTierList(t.id)">
          <div class="row__thumbWrap">
            <img v-if="tierListThumbnailUrl(t)" class="row__thumb" :src="tierListThumbnailUrl(t)" :alt="t.title" />
            <div v-else class="row__thumbPlaceholder"></div>
          </div>
          <div class="row__head">
            <div class="row__title">{{ t.title }}</div>
            <div class="row__author">
              <img v-if="avatarSrcOf(t)" class="row__avatar" :src="avatarSrcOf(t)" :alt="displayNameOf(t)" />
              <div v-else class="row__avatar row__avatar--fallback">{{ avatarFallbackOf(t) }}</div>
              <span>by {{ displayNameOf(t) }}</span>
            </div>
          </div>
        </button>
        <div class="row__foot">
          <div class="row__meta">{{ fmt(t.updatedAt) }}</div>
          <div class="favoriteStat" :title="t.isFavorited ? '이미 즐겨찾기한 티어표' : '즐겨찾기 수'">
            {{ t.isFavorited ? '★' : '☆' }} {{ t.favoriteCount || 0 }}
          </div>
        </div>
      </article>
    </div>
  </section>
</template>

<style scoped>
.head {
  display: flex;
  gap: 14px;
  align-items: flex-end;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 6px 2px 14px;
}
.kicker {
  font-size: 12px;
  opacity: 0.7;
}
.title {
  margin: 4px 0 6px;
  font-size: 26px;
  letter-spacing: -0.02em;
}
.desc {
  margin: 0;
  opacity: 0.84;
}
.primary {
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(96, 165, 250, 0.2);
  color: rgba(255, 255, 255, 0.92);
  cursor: pointer;
  font-weight: 700;
}
.primary:hover {
  background: rgba(96, 165, 250, 0.26);
}
.panel {
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.04);
  border-radius: 16px;
  padding: 14px;
}
.error {
  margin: 10px 0 14px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(239, 68, 68, 0.3);
  background: rgba(239, 68, 68, 0.12);
}
.panel__title {
  font-weight: 800;
}
.panel__head {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.searchBar {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
.searchBar__input {
  min-width: 240px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(0, 0, 0, 0.18);
  color: rgba(255, 255, 255, 0.92);
}
.searchBar__button {
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.92);
  font-weight: 800;
  cursor: pointer;
}
.empty {
  opacity: 0.75;
}
.list {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 14px;
}
.row {
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.04);
  color: rgba(255, 255, 255, 0.92);
  display: grid;
  gap: 10px;
  align-content: start;
  min-height: 168px;
  overflow: hidden;
}
.row:hover {
  background: rgba(255, 255, 255, 0.05);
}
.row__body {
  text-align: left;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  cursor: pointer;
  width: 100%;
  display: grid;
  gap: 10px;
}
.row__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  background: rgba(255, 255, 255, 0.03);
}
.row__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.row__thumbPlaceholder {
  width: 100%;
  height: 100%;
  background:
    linear-gradient(135deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
}
.row__title {
  font-weight: 800;
  min-width: 0;
  font-size: 18px;
  line-height: 1.35;
}
.row__head {
  padding: 14px 14px 0;
  display: grid;
  gap: 12px;
  align-content: start;
}
.row__author {
  display: inline-flex;
  gap: 8px;
  align-items: center;
  font-size: 13px;
  opacity: 0.86;
  flex: 0 0 auto;
}
.row__avatar {
  width: 28px;
  height: 28px;
  border-radius: 999px;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.08);
}
.row__avatar--fallback {
  display: grid;
  place-items: center;
  font-size: 12px;
  font-weight: 900;
}
.row__meta {
  opacity: 0.78;
  font-size: 13px;
}
.row__foot {
  padding: 0 14px 14px;
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  margin-top: auto;
}
.favoriteStat {
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.92);
  border-radius: 999px;
  padding: 7px 10px;
  font-weight: 800;
}
@media (max-width: 1100px) {
  .list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 720px) {
  .list {
    grid-template-columns: 1fr;
  }
  .searchBar__input {
    min-width: 0;
    width: 100%;
  }
}
</style>
