<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('')
const brokenThumbnailIds = ref({})
const isListView = computed(() => route.query.view === 'list')

function fmt(ts) {
  return new Date(ts).toLocaleDateString(undefined, {
    year: 'numeric',
    month: '2-digit',
    day: '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) {
  if (!tierList?.id || brokenThumbnailIds.value[tierList.id]) return ''
  return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}

function handleThumbnailError(tierListId) {
  if (!tierListId || brokenThumbnailIds.value[tierListId]) return
  brokenThumbnailIds.value = { ...brokenThumbnailIds.value, [tierListId]: true }
}

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
    brokenThumbnailIds.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="dashboardHero">
    <div class="dashboardHero__left">
      <div class="dashboardHero__eyebrow">Collection</div>
      <h2 class="dashboardHero__title">{{ gameName || gameId }}</h2>
      <p class="dashboardHero__desc">이 게임의 공개 티어표를 탐색하고, 바로 새 보드를 만들어 같은 흐름으로 이어갈 수 있어요.</p>
    </div>
  </section>

  <div v-if="error" class="error">{{ error }}</div>
  <section class="panel">
    <div class="panel__head">
      <div>
        <div class="panel__title">공개 티어표</div>
        <div class="panel__sub">제목이나 작성자로 빠르게 좁혀볼 수 있어요.</div>
      </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" :class="{ 'list--table': isListView }">
      <article v-for="t in tierLists" :key="t.id" class="boardCard" :class="{ 'boardCard--list': isListView }">
        <button class="boardCard__body" :class="{ 'boardCard__body--list': isListView }" @click="openTierList(t.id)">
          <div class="boardCard__thumbWrap">
            <img v-if="tierListThumbnailUrl(t)" class="boardCard__thumb" :src="tierListThumbnailUrl(t)" alt="" @error="handleThumbnailError(t.id)" />
            <div v-else class="boardCard__thumbPlaceholder">대표 썸네일</div>
          </div>
          <div class="boardCard__head">
            <div class="boardCard__titleRow">
              <div class="boardCard__title">{{ t.title }}</div>
              <div class="favoriteStat" :title="t.isFavorited ? '이미 즐겨찾기한 티어표' : '즐겨찾기 수'">
                {{ t.isFavorited ? '♥' : '♡' }} {{ t.favoriteCount || 0 }}
              </div>
            </div>
            <div class="boardCard__metaRow">
              <div class="boardCard__author">
                <img v-if="avatarSrcOf(t)" class="boardCard__avatar" :src="avatarSrcOf(t)" :alt="displayNameOf(t)" />
                <div v-else class="boardCard__avatar boardCard__avatar--fallback">{{ avatarFallbackOf(t) }}</div>
                <span class="boardCard__authorName">{{ displayNameOf(t) }}</span>
              </div>
              <div class="boardCard__date">{{ fmt(t.updatedAt) }}</div>
            </div>
          </div>
        </button>
      </article>
    </div>
  </section>
</template>

<style scoped>
.dashboardHero {
  display: flex;
  gap: 18px;
  align-items: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 6px 2px 18px;
}
.dashboardHero__left {
  display: grid;
  gap: 8px;
}
.dashboardHero__eyebrow {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.42);
  text-transform: uppercase;
  letter-spacing: 0.08em;
}
.dashboardHero__title {
  margin: 4px 0 6px;
  font-size: 32px;
  letter-spacing: -0.04em;
  color: rgba(255, 255, 255, 0.96);
}
.dashboardHero__desc {
  margin: 0;
  color: rgba(255, 255, 255, 0.58);
  max-width: 720px;
}
.panel {
  /* border: 1px solid rgba(255, 255, 255, 0.08); */
  background: transparent;
  border-radius: 0;
  padding: 0;
}
.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;
  font-size: 18px;
}
.panel__sub {
  margin-top: 6px;
  color: rgba(255, 255, 255, 0.56);
  font-size: 13px;
}
.panel__head {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 18px;
}
.searchBar {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
.searchBar__input {
  min-width: 240px;
  padding: 11px 13px;
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.92);
}
.searchBar__button {
  padding: 11px 14px;
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  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(auto-fit, minmax(min(100%, 280px), 1fr));
  gap: 18px;
}

.list--table {
  grid-template-columns: 1fr;
}
.boardCard {
  min-width: 0;
  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);
  display: grid;
  overflow: hidden;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
  transition:
    transform 0.16s ease,
    background 0.16s ease;
}
.boardCard:hover {
  background: rgba(70, 70, 70, 0.96);
  transform: translateY(-2px);
}
.boardCard__body {
  min-width: 0;
  text-align: left;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  cursor: pointer;
  width: 100%;
  display: grid;
}

.boardCard__body--list {
  grid-template-columns: 76px minmax(0, 1fr);
  align-items: center;
}
.boardCard__thumbWrap {
  min-width: 0;
  width: 100%;
  aspect-ratio: 16 / 9;
  padding: 14px 14px 0;
  box-sizing: border-box;
}

.boardCard--list .boardCard__thumbWrap {
  aspect-ratio: auto;
  height: 100%;
  padding: 14px 0 14px 14px;
}
.boardCard__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 18px;
}

.boardCard--list .boardCard__thumb,
.boardCard--list .boardCard__thumbPlaceholder {
  width: 48px;
  height: 48px;
  min-height: 48px;
  border-radius: 12px;
}
.boardCard__thumbPlaceholder {
  width: 100%;
  height: 100%;
  background: #555;
  display: grid;
  place-items: center;
  color: rgba(255, 255, 255, 0.4);
  font-size: 13px;
  font-weight: 700;
  border-radius: 18px;
}
.boardCard__title {
  font-weight: 800;
  min-width: 0;
  font-size: 18px;
  line-height: 1.35;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
}
.boardCard__head {
  min-width: 0;
  padding: 16px 18px 18px;
  display: grid;
  gap: 8px;
}

.boardCard--list .boardCard__head {
  height: 100%;
  padding: 14px 16px 14px 0;
  align-content: center;
}
.boardCard__titleRow,
.boardCard__metaRow {
  min-width: 0;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
}

.boardCard__titleRow {
  align-items: flex-start;
}

.boardCard__metaRow {
  align-items: flex-end;
}
.boardCard__author {
  min-width: 0;
  max-width: 100%;
  display: inline-flex;
  gap: 7px;
  align-items: center;
  font-size: 13px;
  opacity: 0.86;
  overflow: hidden;
}
.boardCard__authorName {
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.boardCard__avatar {
  width: 22px;
  height: 22px;
  border-radius: 9999px;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.08);
  flex: 0 0 auto;
}
.boardCard__avatar--fallback {
  display: grid;
  place-items: center;
  font-size: 11px;
  font-weight: 900;
}
.boardCard__date,
.favoriteStat {
  flex: 0 0 auto;
  min-width: 0;
  max-width: 100%;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.64);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.boardCard__date {
  font-size: 10px;
}
@media (max-width: 900px) {
  .boardCard__body--list {
    grid-template-columns: 1fr;
  }

  .boardCard--list .boardCard__head {
    padding: 0 18px 18px;
  }

  .boardCard--list .boardCard__thumbWrap {
    padding: 14px 14px 0;
  }
}

@media (max-width: 720px) {
  .list {
    grid-template-columns: 1fr;
  }

  .searchBar__input {
    min-width: 0;
    width: 100%;
  }
}
</style>
