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

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="wrap">
    <header class="head">
      <div>
        <div class="head__eyebrow">Library</div>
        <h2 class="title">내 티어표</h2>
        <div class="desc">직접 저장한 티어표를 같은 카드 레이아웃으로 다시 열고 정리할 수 있어요.</div>
      </div>
      <div class="head__stat">
        <span class="head__statLabel">Saved Lists</span>
        <strong class="head__statValue">{{ myLists.length }}</strong>
      </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__title">{{ t.title }}</div>
              <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>by {{ displayNameOf(t) }}</span>
              </div>
            </div>
            <div class="boardCard__meta">{{ fmt(t.updatedAt) }}</div>
          </button>
          <button class="link link--danger" @click="removeList(t)">삭제</button>
        </article>
      </div>
    </div>
  </section>
</template>

<style scoped>
.wrap {
  padding: 4px 2px;
}
.head {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 18px;
  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 6px;
  font-size: 32px;
  letter-spacing: -0.04em;
  color: rgba(255, 255, 255, 0.96);
}
.desc {
  color: rgba(255, 255, 255, 0.58);
}
.head__stat {
  display: grid;
  gap: 2px;
  min-width: 112px;
  padding: 12px 14px;
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.045);
}
.head__statLabel {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.48);
  text-transform: uppercase;
  letter-spacing: 0.08em;
}
.head__statValue {
  font-size: 18px;
  font-weight: 900;
}
.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(3, minmax(0, 1fr));
  gap: 18px;
}
.boardCard {
  display: grid;
  gap: 10px;
  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;
  gap: 10px;
}
.boardCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  background: #555;
  display: grid;
  place-items: center;
}
.boardCard__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.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;
}
.boardCard__title {
  font-weight: 900;
  min-width: 0;
}
.boardCard__head {
  padding: 0 14px;
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}
.boardCard__author {
  display: inline-flex;
  gap: 8px;
  align-items: center;
  font-size: 13px;
  opacity: 0.84;
}
.boardCard__avatar {
  width: 28px;
  height: 28px;
  border-radius: 999px;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.08);
}
.boardCard__avatar--fallback {
  display: grid;
  place-items: center;
  font-size: 12px;
  font-weight: 900;
}
.boardCard__meta {
  padding: 0 14px;
  margin-top: 6px;
  opacity: 0.76;
  font-size: 13px;
}
.link--danger {
  background: rgba(239, 68, 68, 0.14);
  border-color: rgba(239, 68, 68, 0.28);
  margin: 0 14px 14px;
}
@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) {
  .head__stat {
    width: 100%;
  }
  .list {
    grid-template-columns: 1fr;
  }
}
</style>
