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

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

const tierLists = ref([])
const query = ref('')
const isLoading = ref(false)
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 }
}

async function loadFollowingFeed() {
  isLoading.value = true
  try {
    const data = await api.listFollowingFeed({ q: query.value })
    brokenThumbnailIds.value = {}
    tierLists.value = data.tierLists || []
  } catch (e) {
    toast.error('로그인이 필요해요.')
    router.push(loginPath('/following'))
  } finally {
    isLoading.value = false
  }
}

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

function openAuthorProfile(tierList) {
  if (!tierList?.authorId) return
  router.push(userProfilePath(tierList.authorId))
}

onMounted(loadFollowingFeed)
</script>

<template>
  <section class="pageWrap">
    <section class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Following</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="loadFollowingFeed" />
        <button class="btn" :disabled="isLoading" @click="loadFollowingFeed">{{ isLoading ? '검색중...' : '검색' }}</button>
      </div>
    </section>

    <section class="panel">
      <div v-if="isLoading" class="empty">팔로우 피드를 불러오고 있어요.</div>
      <div v-else-if="tierLists.length === 0" class="empty">아직 팔로우한 작성자의 공개 티어표가 없어요.</div>
      <div v-else class="list">
        <article v-for="tierList in tierLists" :key="tierList.id" class="boardCard">
          <button class="boardCard__body" type="button" @click="openTierList(tierList)">
            <div class="boardCard__thumbWrap">
              <img
                v-if="tierListThumbnailUrl(tierList)"
                class="boardCard__thumb"
                :src="tierListThumbnailUrl(tierList)"
                :alt="tierList.title"
                draggable="false"
                @error="handleThumbnailError(tierList.id)"
              />
              <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.isFavorited ? '♥' : '♡' }} {{ tierList.favoriteCount || 0 }}</div>
              </div>
              <div class="boardCard__topic">{{ tierList.topicName || tierList.topicId }}</div>
            </div>
          </button>

          <button class="authorLink" type="button" @click="openAuthorProfile(tierList)">
            <div class="authorLink__main">
              <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="authorLink__name">{{ displayNameOf(tierList) }}</span>
            </div>
            <span class="authorLink__date">{{ fmt(tierList.updatedAt) }}</span>
          </button>
        </article>
      </div>
    </section>
  </section>
</template>

<style scoped>
.panel {
  background: transparent;
  border-radius: 0;
  padding: 0;
}
.toolbar {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.input {
  min-width: 240px;
  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.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 {
  background: var(--theme-card-bg-hover);
  transform: translateY(-2px);
}
.boardCard__body {
  width: 100%;
  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,
.boardCard__thumbPlaceholder {
  width: 100%;
  height: 100%;
  border-radius: 18px;
  display: block;
}
.boardCard__thumb {
  object-fit: cover;
}
.boardCard__thumbPlaceholder {
  display: grid;
  place-items: center;
  background: var(--theme-thumb-fallback-bg);
  color: var(--theme-text-faint);
  font-size: 13px;
  font-weight: 700;
}
.boardCard__head {
  min-width: 0;
  padding: 16px 18px 0;
  display: grid;
  gap: 6px;
}
.boardCard__titleRow {
  min-width: 0;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
  align-items: flex-start;
}
.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__topic,
.favoriteStat {
  font-size: 13px;
  color: var(--theme-text-faint);
}
.favoriteStat {
  white-space: nowrap;
}
.authorLink {
  width: calc(100% - 28px);
  margin: 14px;
  padding: 12px 14px;
  border-radius: 16px;
  border: 1px solid var(--theme-border);
  background: var(--theme-surface-soft);
  color: inherit;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.authorLink__main {
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}
.authorLink__name {
  min-width: 0;
  font-size: 13px;
  font-weight: 800;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.authorLink__date {
  flex: 0 0 auto;
  font-size: 10px;
  color: var(--theme-text-faint);
}
.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;
}
@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: 720px) {
  .list {
    grid-template-columns: 1fr;
  }

  .input {
    min-width: 0;
    width: 100%;
  }
}
</style>
