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

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

const tierLists = ref([])
const loading = ref(false)
const error = ref('')
const query = ref('')

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) {
  return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}

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

async function loadResults() {
  loading.value = true
  error.value = ''
  try {
    const data = await api.searchAllPublicTierLists(query.value)
    tierLists.value = data.tierLists || []
  } catch (e) {
    error.value = '검색 결과를 불러오지 못했어요.'
  } finally {
    loading.value = false
  }
}

watch(
  () => route.query.q,
  async (nextQuery) => {
    query.value = typeof nextQuery === 'string' ? nextQuery : ''
    await loadResults()
  },
  { immediate: true }
)
</script>

<template>
  <section class="wrap">
    <div class="head">
      <div>
        <div class="head__eyebrow">Search</div>
        <h2 class="title">전체 티어표 검색</h2>
        <div class="desc">공개된 모든 티어표를 제목과 작성자 기준으로 찾아볼 수 있어요.</div>
      </div>
    </div>

    <div v-if="error" class="error">{{ error }}</div>
    <div v-else-if="loading" class="empty">검색 중이에요.</div>
    <div v-else-if="tierLists.length === 0" class="empty">검색 결과가 없어요.</div>
    <div v-else class="list">
      <article v-for="tierList in tierLists" :key="tierList.id" class="boardCard">
        <button class="boardCard__body" @click="openTierList(tierList)">
          <div class="boardCard__thumbWrap">
            <img v-if="tierListThumbnailUrl(tierList)" class="boardCard__thumb" :src="tierListThumbnailUrl(tierList)" :alt="tierList.title" />
            <div v-else class="boardCard__thumbPlaceholder">대표 썸네일</div>
          </div>
          <div class="boardCard__head">
            <div class="boardCard__titleRow">
              <div class="boardCard__title">{{ tierList.title }}</div>
              <div class="favoriteStat" :title="tierList.isFavorited ? '이미 즐겨찾기한 티어표' : '즐겨찾기 수'">
                {{ tierList.isFavorited ? '♥' : '♡' }} {{ tierList.favoriteCount || 0 }}
              </div>
            </div>
            <div class="boardCard__metaRow">
              <div class="boardCard__author">
                <img v-if="avatarSrcOf(tierList)" class="boardCard__avatar" :src="avatarSrcOf(tierList)" :alt="displayNameOf(tierList)" />
                <div v-else class="boardCard__avatar boardCard__avatar--fallback">{{ avatarFallbackOf(tierList) }}</div>
                <span class="boardCard__authorName">{{ displayNameOf(tierList) }}</span>
              </div>
              <div class="boardCard__date">{{ fmt(tierList.updatedAt) }}</div>
            </div>
          </div>
        </button>
      </article>
    </div>
  </section>
</template>

<style scoped>
.wrap {
  display: grid;
  gap: 18px;
}
.head {
  display: flex;
  gap: 14px;
  justify-content: space-between;
  align-items: flex-end;
  flex-wrap: wrap;
  padding: 6px 2px 8px;
}
.head__eyebrow {
  font-size: 11px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--theme-text-soft);
}
.title {
  margin: 4px 0 0;
  font-size: 32px;
  color: var(--theme-text-strong);
  letter-spacing: -0.04em;
}
.desc {
  margin-top: 6px;
  color: var(--theme-text-muted);
}
.error {
  margin: 0 0 8px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid var(--theme-danger-border);
  background: var(--theme-danger-bg);
}
.empty {
  opacity: 0.76;
}
.list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.boardCard {
  border-radius: 22px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-card-bg);
  overflow: hidden;
  display: grid;
  box-shadow: inset 0 1px 0 var(--theme-card-shadow);
  transition: transform 0.16s ease, background 0.16s ease;
}
.boardCard:hover {
  transform: translateY(-2px);
  background: var(--theme-card-bg-hover);
}
.boardCard__body {
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  text-align: left;
  cursor: pointer;
  display: grid;
}
.boardCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  padding: 14px 14px 0;
  box-sizing: border-box;
}
.boardCard__thumb,
.boardCard__thumbPlaceholder {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 18px;
}
.boardCard__thumb {
  object-fit: cover;
}
.boardCard__thumbPlaceholder {
  background: var(--theme-thumb-fallback-bg);
  display: grid;
  place-items: center;
  color: var(--theme-text-faint);
  font-size: 13px;
  font-weight: 700;
}
.boardCard__head {
  padding: 16px 18px 18px;
  display: grid;
  gap: 6px;
}
.boardCard__titleRow,
.boardCard__metaRow {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: space-between;
}

.boardCard__metaRow {
  align-items: flex-end;
}
.boardCard__title {
  min-width: 0;
  font-weight: 800;
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.boardCard__author {
  min-width: 0;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  opacity: 0.86;
}
.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;
  background: var(--theme-border);
  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;
  font-size: 13px;
  color: var(--theme-text-faint);
  white-space: nowrap;
}

.boardCard__date {
  font-size: 10px;
}
.boardCard__date { 
  font-size: 10px;
}
@media (max-width: 1400px) {
  .list {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
@media (max-width: 1024px) {
  .list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 720px) {
  .list {
    grid-template-columns: 1fr;
  }
}
</style>
