<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, 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'
import { displayInitialFrom } from '../lib/display'

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

const favorites = ref([])
const query = ref('')
const sort = ref('favorited')
const busyTierListId = ref('')
const isListView = computed(() => route.query.view === 'list')

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 displayInitialFrom(tierList.authorName, tierList.authorAccountName, '?')
}

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(loginPath('/favorites'))
  }
}

function openTierList(tierList) {
  router.push(editorPath(tierList.topicSlug || tierList.topicId, tierList.id))
}

async function removeFavorite(tierListId) {
  if (!tierListId || busyTierListId.value) return
  busyTierListId.value = tierListId
  const original = favorites.value.slice()
  favorites.value = favorites.value.filter((tierList) => tierList.id !== tierListId)
  try {
    await api.unfavoriteTierList(tierListId)
    toast.success('즐겨찾기에서 제거했어요.')
  } catch (error) {
    favorites.value = original
    toast.error('즐겨찾기 해제에 실패했어요.')
  } finally {
    busyTierListId.value = ''
  }
}

onMounted(loadFavorites)
</script>

<template>
  <section class="pageWrap">
    <div class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Collection</div>
        <h2 class="pageHead__title">즐겨찾기</h2>
        <div class="pageHead__desc">마음에 드는 티어표를 모아보고, 원하는 기준으로 정렬할 수 있어요.</div>
      </div>
      <div class="pageHead__aside 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" :class="{ 'list--table': isListView }">
      <article v-for="tierList in favorites" :key="tierList.id" class="boardCard" :class="{ 'boardCard--list': isListView }">
        <button
          class="boardCard__favoriteAction"
          type="button"
          :disabled="!!busyTierListId"
          @click.stop="removeFavorite(tierList.id)"
        >
          {{ busyTierListId === tierList.id ? '처리 중...' : '즐겨찾기 해제' }}
        </button>
        <button class="boardCard__body" :class="{ 'boardCard__body--list': isListView }" @click="openTierList(tierList)">
          <div class="boardCard__thumbWrap">
            <img v-if="tierListThumbnailUrl(tierList)" class="boardCard__thumb" :src="tierListThumbnailUrl(tierList)" :alt="tierList.title" draggable="false" />
            <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">♡ {{ 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)" draggable="false" />
                <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>
.toolbar {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.input,
.select {
  padding: 11px 13px;
  border-radius: 14px;
  border: 1px solid var(--theme-border);
  background: var(--theme-surface-soft);
  color: var(--theme-text);
}
.btn {
  padding: 11px 13px;
  border-radius: 14px;
  border: 1px solid var(--theme-border);
  background: var(--theme-surface-soft-2);
  color: var(--theme-text);
  font-weight: 800;
  cursor: pointer;
}
.empty {
  opacity: 0.76;
}
.list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.list--table {
  grid-template-columns: 1fr;
}
.boardCard {
  position: relative;
  min-width: 0;
  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 {
  min-width: 0;
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  text-align: left;
  cursor: pointer;
  display: grid;
  width: 100%;
  overflow: hidden;
}
.boardCard__favoriteAction {
  position: absolute;
  top: 14px;
  right: 14px;
  z-index: 1;
  min-height: 32px;
  padding: 0 12px;
  border-radius: 999px;
  border: 1px solid color-mix(in srgb, var(--theme-danger-border) 70%, var(--theme-border));
  background: color-mix(in srgb, var(--theme-surface) 92%, var(--theme-danger-bg));
  color: var(--theme-text);
  font-size: 12px;
  font-weight: 800;
  cursor: pointer;
}
.boardCard__favoriteAction:disabled {
  cursor: default;
  opacity: 0.72;
}
.boardCard__thumbWrap {
  min-width: 0;
  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 {
  min-width: 0;
  padding: 16px 18px 18px;
  display: grid;
  gap: 6px;
  overflow: hidden;
}
.boardCard--list .boardCard__head {
  align-content: center;
  padding: 16px 18px 16px 0;
}
.boardCard__body--list {
  grid-template-columns: 200px minmax(0, 1fr);
  align-items: stretch;
}
.boardCard__body--list .boardCard__thumbWrap {
  height: 100%;
  padding: 14px;
}
.boardCard__body--list .boardCard__thumb,
.boardCard__body--list .boardCard__thumbPlaceholder {
  min-height: 100%;
}
.boardCard__titleRow,
.boardCard__metaRow {
  min-width: 0;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
}

.boardCard__metaRow {
  align-items: flex-end;
}
.boardCard__title {
  min-width: 0;
  font-weight: 800;
  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__author {
  min-width: 0;
  max-width: 100%;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  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: 1024px) {
  .list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 720px) {
  .list {
    grid-template-columns: 1fr;
  }

  .boardCard__body--list {
    grid-template-columns: 1fr;
  }

  .boardCard--list .boardCard__head {
    padding: 16px 18px 18px;
  }

  .toolbar {
    width: 100%;
  }
  .input,
  .select,
  .btn {
    width: 100%;
  }
}
</style>
