<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../lib/api'
import { editorPath } from '../lib/paths'
import { toApiUrl } from '../lib/runtime'
import { displayInitialFrom } from '../lib/display'

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

const featuredTierLists = ref([])
const tierLists = ref([])
const error = ref('')
const query = computed(() => (typeof route.query.q === 'string' ? route.query.q.trim() : ''))
const isListView = computed(() => route.query.view === 'list')
const brokenThumbnailIds = ref({})

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) {
  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 loadHomeFeed() {
  try {
    const data = await api.searchAllPublicTierLists(query.value)
    brokenThumbnailIds.value = {}
    featuredTierLists.value = data.featuredTierLists || []
    tierLists.value = data.tierLists || []
  } catch (e) {
    error.value = '공개 티어표를 불러오지 못했어요.'
  }
}

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

onMounted(loadHomeFeed)
watch(() => route.query.q, loadHomeFeed)
</script>

<template>
  <section class="pageWrap">
    <section class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Feed</div>
        <h1 class="pageHead__title">홈</h1>
        <div class="pageHead__desc">사용자가 공개한 티어표를 최신순으로 살펴보고, 추천 티어표는 상단에서 바로 볼 수 있어요.</div>
        <div v-if="query" class="pageHead__searchState">"{{ query }}"에 맞는 공개 티어표만 보고 있어요.</div>
      </div>
    </section>

    <div v-if="error" class="error">{{ error }}</div>

    <section v-if="featuredTierLists.length" class="featuredPanel">
      <div class="featuredHead">
        <div>
          <div class="featuredHead__eyebrow">Featured</div>
          <h3 class="featuredHead__title">추천 티어표</h3>
        </div>
        <div class="featuredHead__count">{{ featuredTierLists.length }}개</div>
      </div>
      <div class="list" :class="{ 'list--table': isListView }">
        <article v-for="tierList in featuredTierLists" :key="`featured-${tierList.id}`" class="boardCard boardCard--featured" :class="{ 'boardCard--list': isListView }">
          <button class="boardCard__body" :class="{ 'boardCard__body--list': isListView }" 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.topicSlug || tierList.topicId }}</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>

    <section class="panel">
      <div class="sectionLabel">최신 공개 티어표</div>
      <div v-if="tierLists.length === 0" class="empty">{{ query ? '검색어에 맞는 공개 티어표가 없어요.' : '아직 공개 티어표가 없어요.' }}</div>
      <div v-else class="list" :class="{ 'list--table': isListView }">
        <article v-for="tierList in tierLists" :key="tierList.id" class="boardCard" :class="{ 'boardCard--list': isListView }">
          <button class="boardCard__body" :class="{ 'boardCard__body--list': isListView }" 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.topicSlug || tierList.topicId }}</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>
  </section>
</template>

<style scoped>
.pageHead__searchState {
  margin-top: 8px;
  color: var(--theme-text-muted);
}
.error {
  margin: 0 0 16px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid var(--theme-danger-border);
  background: var(--theme-danger-bg);
  color: var(--theme-text);
}
.panel {
  background: transparent;
  border-radius: 0;
  padding: 0;
}
.featuredPanel {
  margin-bottom: 28px;
  padding: 24px;
  border-radius: 28px;
  border: 1px solid var(--theme-card-border);
  background: linear-gradient(180deg, var(--theme-surface-soft) 0%, var(--theme-surface) 100%);
  box-shadow: inset 0 1px 0 var(--theme-card-shadow);
}
.featuredHead {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
}
.featuredHead__eyebrow,
.sectionLabel {
  font-size: 11px;
  font-weight: 900;
  letter-spacing: 0.16em;
  text-transform: uppercase;
  color: var(--theme-text-faint);
}
.featuredHead__title {
  margin: 6px 0 0;
  font-size: 22px;
  font-weight: 900;
  color: var(--theme-text);
}
.featuredHead__count {
  flex: 0 0 auto;
  font-size: 13px;
  font-weight: 800;
  color: var(--theme-text-muted);
}
.sectionLabel {
  margin-bottom: 14px;
}
.empty {
  opacity: 0.76;
}
.list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.list--table {
  grid-template-columns: 1fr;
}
.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 {
  width: 100%;
  min-width: 0;
  text-align: left;
  cursor: pointer;
  border: 0;
  background: transparent;
  color: inherit;
  padding: 0;
  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,
.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: 8px;
  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;
}
.boardCard__titleRow {
  align-items: flex-start;
}
.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__topic {
  min-width: 0;
  color: var(--theme-text-soft);
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.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: 800;
  color: var(--theme-text);
}
.boardCard__date,
.favoriteStat {
  flex: 0 0 auto;
  font-size: 12px;
  color: var(--theme-text-soft);
}
.favoriteStat {
  font-weight: 800;
}
@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: minmax(0, 1fr);
  }

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

  .boardCard--list .boardCard__head {
    padding: 16px 18px 18px;
  }
}
</style>
