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

const router = useRouter()
const toast = useToast()
const myLists = ref([])
const error = ref('')
const brokenThumbnailIds = ref({})

watch(error, (message) => {
  if (!message) return
  toast.error(message)
  error.value = ''
})

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 () => {
  try {
    const data = await api.listMyTierLists()
    brokenThumbnailIds.value = {}
    myLists.value = data.tierLists || []
  } catch (e) {
    toast.error('로그인이 필요해요.')
    router.push(loginPath('/me'))
  }
})

function openList(t) {
  router.push(editorPath(t.topicSlug || t.topicId, t.id))
}
</script>

<template>
  <section class="pageHead">
    <div class="pageHead__main">
      <div class="pageHead__eyebrow">Tier Lists</div>
      <h2 class="pageHead__title">나의 티어표</h2>
      <div class="pageHead__desc">직접 저장한 티어표를 같은 카드 레이아웃으로 다시 열고 정리할 수 있어요.</div>
    </div>
  </section>

  <section class="panel">
    <div v-if="myLists.length === 0" class="empty">아직 저장한 티어표가 없어요.</div>
    <div v-else class="list">
      <article v-for="t in myLists" :key="t.id" class="boardCard">
        <button class="boardCard__body" @click="openList(t)">
          <div class="boardCard__thumbWrap">
            <img
              v-if="tierListThumbnailUrl(t)"
              class="boardCard__thumb"
              :src="tierListThumbnailUrl(t)"
              alt=""
              draggable="false"
              @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">♡ {{ 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)" draggable="false" />
                <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>
.panel {
  background: transparent;
  border-radius: 0;
  padding: 0;
}
.empty {
  opacity: 0.75;
}
.list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.boardCard {
  min-width: 0;
  border-radius: 22px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-card-bg);
  color: var(--theme-text);
  overflow: hidden;
  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 {
  min-width: 0;
  text-align: left;
  cursor: pointer;
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  width: 100%;
  display: grid;
  overflow: hidden;
}
.boardCard__thumbWrap {
  min-width: 0;
  width: 100%;
  aspect-ratio: 16 / 9;
  padding: 14px 14px 0;
  box-sizing: border-box;
}
.boardCard__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 18px;
}
.boardCard__thumbPlaceholder {
  width: 100%;
  height: 100%;
  background: var(--theme-thumb-fallback-bg);
  display: grid;
  place-items: center;
  color: var(--theme-text-faint);
  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;
  overflow: hidden;
}
.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 var(--theme-avatar-border);
  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;
  min-width: 0;
  max-width: 100%;
  font-size: 13px;
  color: var(--theme-text-faint);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.boardCard__date {
  font-size: 10px;
}
@media (max-width: 1400px) {
  .list {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
@media (max-width: 1200px) {
  .list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 900px) {
  .list {
    grid-template-columns: 1fr;
  }
}
</style>
