<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'

const router = useRouter()
const toast = useToast()
const myLists = ref([])
const error = 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) {
  return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}

onMounted(async () => {
  try {
    const data = await api.listMyTierLists()
    myLists.value = data.tierLists || []
  } catch (e) {
    toast.error('로그인이 필요해요.')
    router.push('/login?redirect=/me')
  }
})

function openList(t) {
  router.push(`/editor/${t.gameId}/${t.id}`)
}

async function removeList(t) {
  error.value = ''
  try {
    const ok = window.confirm(`"${t.title}" 티어표를 삭제할까요?`)
    if (!ok) return
    await api.deleteTierList(t.id)
    myLists.value = myLists.value.filter((entry) => entry.id !== t.id)
    toast.success('티어표를 삭제했어요.')
  } catch (e) {
    error.value = '티어표 삭제에 실패했어요.'
  }
}
</script>

<template>
  <section class="pageWrap">
    <header class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Library</div>
        <h2 class="pageHead__title">내 티어표</h2>
        <div class="pageHead__desc">직접 저장한 티어표를 같은 카드 레이아웃으로 다시 열고 정리할 수 있어요.</div>
      </div>
    </header>
    <div class="card">
      <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="t.title" />
              <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)" />
                  <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>
          <button class="link link--danger" @click="removeList(t)">삭제</button>
        </article>
      </div>
    </div>
  </section>
</template>

<style scoped>
.card {
  border: 0;
  background: transparent;
  border-radius: 0;
  padding: 0;
}
.link {
  padding: 10px 12px;
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.92);
  cursor: pointer;
  font-weight: 800;
}
.empty {
  opacity: 0.75;
}
.list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.boardCard {
  display: grid;
  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);
  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 {
  transform: translateY(-2px);
  background: rgba(70, 70, 70, 0.96);
}
.boardCard__body {
  flex: 1 1 auto;
  min-width: 0;
  text-align: left;
  cursor: pointer;
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  display: grid;
}
.boardCard__thumbWrap {
  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: #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: 900;
  min-width: 0;
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.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__author {
  min-width: 0;
  display: inline-flex;
  gap: 7px;
  align-items: center;
  font-size: 13px;
  opacity: 0.84;
}
.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;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.64);
  white-space: nowrap;
}
.boardCard__date {
  font-size: 10px;
}
.link--danger {
  background: rgba(239, 68, 68, 0.14);
  border-color: rgba(239, 68, 68, 0.28);
  margin: 0 18px 18px;
}
@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>
