<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../lib/api'
import { toApiUrl } from '../lib/runtime'
import { useToast } from '../composables/useToast'

const router = useRouter()
const toast = useToast()

const favorites = ref([])
const query = ref('')
const sort = ref('favorited')
const sortLabel = computed(() =>
  sort.value === 'favorited' ? '즐겨찾기한 날짜' : sort.value === 'updated' ? '최종 업데이트' : '즐겨찾기 수'
)

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) : ''
}

async function loadFavorites() {
  try {
    const data = await api.listMyFavoriteTierLists({ q: query.value, sort: sort.value })
    favorites.value = data.tierLists || []
  } catch (e) {
    toast.error('로그인이 필요해요.')
    router.push('/login?redirect=/favorites')
  }
}

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

onMounted(loadFavorites)
</script>

<template>
  <section class="wrap">
    <div class="head">
      <div>
        <div class="head__eyebrow">Collection</div>
        <h2 class="title">내 즐겨찾기</h2>
        <div class="desc">마음에 드는 티어표를 모아보고, 원하는 기준으로 정렬할 수 있어요.</div>
      </div>
      <div class="toolbar">
        <input v-model="query" class="input" placeholder="제목, 게임, 작성자 검색" @keydown.enter.prevent="loadFavorites" />
        <select v-model="sort" class="select" @change="loadFavorites">
          <option value="favorited">즐겨찾기한 순</option>
          <option value="updated">최신 업데이트순</option>
          <option value="favorites">인기순</option>
        </select>
        <button class="btn" @click="loadFavorites">검색</button>
      </div>
    </div>

    <div v-if="favorites.length === 0" class="empty">즐겨찾기한 티어표가 없어요.</div>
    <div v-else class="list">
      <article v-for="tierList in favorites" :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__title">{{ tierList.title }}</div>
            <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>by {{ displayNameOf(tierList) }}</span>
            </div>
          </div>
        </button>
        <div class="boardCard__foot">
          <div class="boardCard__meta">
            <div>{{ tierList.gameName || tierList.gameId }}</div>
            <div>{{ sortLabel }}: {{ fmt(sort === 'favorited' ? tierList.favoritedAt : tierList.updatedAt) }}</div>
          </div>
          <div class="favoriteStat">★ {{ tierList.favoriteCount || 0 }}</div>
        </div>
      </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: rgba(255, 255, 255, 0.42);
}
.title {
  margin: 4px 0 0;
  font-size: 32px;
  color: rgba(255, 255, 255, 0.96);
  letter-spacing: -0.04em;
}
.desc {
  margin-top: 6px;
  color: rgba(255, 255, 255, 0.58);
}
.toolbar {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.input,
.select {
  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);
}
.btn {
  padding: 11px 13px;
  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.76;
}
.list {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 18px;
}
.boardCard {
  border-radius: 22px;
  border: 1px solid rgba(255, 255, 255, 0.16);
  background: rgba(62, 62, 62, 0.82);
  overflow: hidden;
  display: grid;
  gap: 10px;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
  transition:
    transform 0.16s ease,
    background 0.16s ease;
}
.boardCard:hover {
  transform: translateY(-2px);
  background: rgba(70, 70, 70, 0.96);
}
.boardCard__body {
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  text-align: left;
  cursor: pointer;
  display: grid;
  gap: 10px;
}
.boardCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  background: #555;
  display: grid;
  place-items: center;
}
.boardCard__thumb,
.boardCard__thumbPlaceholder {
  width: 100%;
  height: 100%;
  display: block;
}
.boardCard__thumb {
  object-fit: cover;
}
.boardCard__thumbPlaceholder {
  background: #555;
  display: grid;
  place-items: center;
  color: rgba(255, 255, 255, 0.4);
  font-size: 13px;
  font-weight: 700;
}
.boardCard__head {
  padding: 14px 14px 0;
  display: grid;
  gap: 10px;
}
.boardCard__title {
  font-weight: 800;
  font-size: 18px;
}
.boardCard__author {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  opacity: 0.86;
}
.boardCard__avatar {
  width: 28px;
  height: 28px;
  border-radius: 999px;
  object-fit: cover;
  background: rgba(255, 255, 255, 0.08);
}
.boardCard__avatar--fallback {
  display: grid;
  place-items: center;
  font-size: 12px;
  font-weight: 900;
}
.boardCard__foot {
  padding: 0 14px 14px;
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}
.boardCard__meta {
  display: grid;
  gap: 4px;
  opacity: 0.78;
  font-size: 13px;
}
.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: 960px) {
  .list {
    grid-template-columns: 1fr;
  }
}
@media (max-width: 720px) {
  .list {
    grid-template-columns: 1fr;
  }
  .toolbar {
    width: 100%;
  }
  .input,
  .select,
  .btn {
    width: 100%;
  }
}
</style>
