<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../lib/api'
import SvgIcon from '../components/SvgIcon.vue'
import kidStarIcon from '../assets/icons/kid_star.svg'
import { toApiUrl } from '../lib/runtime'
import { loginPath, topicPath } from '../lib/paths'
import { useAuthStore } from '../stores/auth'

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

const templateRecords = ref([])
const error = ref('')
const isLoadingTemplates = ref(false)
const hasLoadedTemplates = ref(false)
const loadingFavoriteId = ref('')
const query = computed(() => (typeof route.query.q === 'string' ? route.query.q.trim().toLowerCase() : ''))
const templates = computed(() => {
  const filtered = templateRecords.value
    .filter((item) => item.id !== 'freeform')
    .filter((item) => {
      if (!query.value) return true
      const haystack = `${item.name || ''} ${item.slug || ''}`.toLowerCase()
      return haystack.includes(query.value)
    })

  return filtered.slice().sort((a, b) => {
    if (!!a.isFavorited !== !!b.isFavorited) return a.isFavorited ? -1 : 1
    const rankA = a.displayRank == null ? Number.MAX_SAFE_INTEGER : a.displayRank
    const rankB = b.displayRank == null ? Number.MAX_SAFE_INTEGER : b.displayRank
    if (rankA !== rankB) return rankA - rankB
    if (Number(a.createdAt || 0) !== Number(b.createdAt || 0)) {
      return Number(b.createdAt || 0) - Number(a.createdAt || 0)
    }
    return (a.name || '').localeCompare(b.name || '', 'ko')
  })
})

async function loadTemplates() {
  try {
    isLoadingTemplates.value = true
    error.value = ''
    const data = await api.listTopics()
    templateRecords.value = data.topics || []
  } catch (e) {
    error.value = '백엔드에 연결할 수 없어요. backend 서버가 실행 중인지 확인해주세요.'
  } finally {
    isLoadingTemplates.value = false
    hasLoadedTemplates.value = true
  }
}

onMounted(loadTemplates)
watch(() => auth.user?.id, loadTemplates)

function openTopic(template) {
  router.push(topicPath(template?.slug || template?.id || ''))
}

async function toggleFavorite(template, event) {
  event?.stopPropagation()
  if (!auth.user) {
    router.push(loginPath(route.fullPath || '/'))
    return
  }
  if (!template?.id || loadingFavoriteId.value === template.id) return

  try {
    loadingFavoriteId.value = template.id
    const res = template.isFavorited ? await api.unfavoriteTopic(template.id) : await api.favoriteTopic(template.id)
    templateRecords.value = templateRecords.value.map((entry) => (entry.id === template.id ? { ...entry, ...(res.topic || {}) } : entry))
  } catch (e) {
    error.value = '즐겨찾기 변경에 실패했어요.'
  } finally {
    loadingFavoriteId.value = ''
  }
}

function templateThumbUrl(template) {
  return template.thumbnailSrc ? toApiUrl(template.thumbnailSrc) : ''
}
</script>

<template>
  <section class="pageHead">
    <div class="pageHead__main">
      <div class="pageHead__eyebrow">Topic</div>
      <h1 class="pageHead__title">주제 선택</h1>
      <p class="pageHead__desc">자주 쓰는 주제 템플릿을 빠르게 고르고, 필요하면 바로 커스텀 티어표를 시작할 수 있어요.</p>
      <p v-if="query" class="pageHead__searchState">"{{ query }}"에 맞는 주제 템플릿만 보고 있어요.</p>
    </div>
  </section>

  <div v-if="error" class="error">{{ error }}</div>
  <section v-else-if="isLoadingTemplates && !hasLoadedTemplates" class="libraryLoading" aria-live="polite">
    <div class="libraryLoading__spinner" aria-hidden="true"></div>
    <div>
      <div class="libraryLoading__title">주제 템플릿을 불러오고 있어요.</div>
      <div class="libraryLoading__desc">처음 접속 시 서버 응답에 따라 잠시 걸릴 수 있어요.</div>
    </div>
  </section>
  <TransitionGroup v-else-if="templates.length" name="libraryCard" tag="section" class="libraryGrid">
    <article v-for="template in templates" :key="template.id" class="libraryCard">
      <button
        class="libraryCard__favorite"
        type="button"
        :class="{ 'libraryCard__favorite--active': template.isFavorited }"
        :disabled="loadingFavoriteId === template.id"
        @click.stop="toggleFavorite(template, $event)"
      >
        <SvgIcon class="libraryCard__favoriteIcon" :src="kidStarIcon" :size="18" />
      </button>
      <button class="libraryCard__main" type="button" @click="openTopic(template)">
        <div class="libraryCard__thumbWrap">
        <img v-if="templateThumbUrl(template)" class="libraryCard__thumb" :src="templateThumbUrl(template)" :alt="template.name" draggable="false" />
        <div v-else class="libraryCard__thumbFallback">대표 썸네일</div>
      </div>
        <div class="libraryCard__body">
          <div class="libraryCard__title">{{ template.name }}</div>
          <div class="libraryCard__meta">{{ template.slug || template.id }}</div>
        </div>
      </button>
    </article>
  </TransitionGroup>
  <div v-else-if="hasLoadedTemplates" class="libraryEmpty">{{ query ? '검색어에 맞는 주제 템플릿이 없어요.' : '표시할 주제 템플릿이 없어요.' }}</div>
</template>

<style scoped>
.libraryGrid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px;
}
.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);
}
.pageHead__searchState {
  margin-top: 8px;
  color: var(--theme-text-muted);
}
.libraryLoading {
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 28px;
  border-radius: 24px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-card-bg);
  color: var(--theme-text);
  box-shadow: inset 0 1px 0 var(--theme-card-shadow);
}
.libraryLoading__spinner {
  width: 34px;
  height: 34px;
  border-radius: 999px;
  border: 3px solid color-mix(in srgb, var(--theme-text-faint) 32%, transparent);
  border-top-color: var(--theme-accent);
  animation: libraryLoadingSpin 820ms linear infinite;
}
.libraryLoading__title {
  font-weight: 900;
  letter-spacing: -0.02em;
}
.libraryLoading__desc {
  margin-top: 4px;
  color: var(--theme-text-soft);
  font-size: 13px;
}
@keyframes libraryLoadingSpin {
  to {
    transform: rotate(360deg);
  }
}
.libraryCard {
  position: relative;
  text-align: left;
  padding: 14px;
  border-radius: 22px;
  border: 1px solid var(--theme-card-border);
  background: var(--theme-card-bg);
  color: var(--theme-text);
  cursor: pointer;
  display: grid;
  gap: 12px;
  box-shadow: inset 0 1px 0 var(--theme-card-shadow);
  transition: transform 0.16s ease, background 0.16s ease;
  will-change: transform, opacity;
}
.libraryCard:hover {
  background: var(--theme-card-bg-hover);
  transform: translateY(-2px);
}
.libraryCard__main {
  display: grid;
  gap: 12px;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  text-align: left;
  cursor: pointer;
}
.libraryCard__favorite {
  position: absolute;
  bottom: 24px;
  right: 14px;
  width: 34px;
  height: 34px;
  border-radius: 999px;
  border: 1px solid var(--theme-favorite-border);
  background: var(--theme-favorite-bg);
  color: var(--theme-favorite-icon);
  font-size: 17px;
  line-height: 1;
  cursor: pointer;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}
.libraryCard__favorite--active {
  background: var(--theme-favorite-active-bg);
  border-color: var(--theme-favorite-active-border);
}
.libraryCard__favoriteIcon {
  opacity: 0.76;
  color: var(--theme-favorite-icon);
}
.libraryCard__favorite--active .libraryCard__favoriteIcon {
  opacity: 1;
  color: var(--theme-favorite-active-icon);
}
.libraryCard__thumbWrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 14px;
  border: 1px solid var(--theme-surface-soft-2);
  background: var(--theme-thumb-fallback-bg);
  overflow: hidden;
  display: grid;
  place-items: center;
}
.libraryCard__thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.libraryCard__thumbFallback {
  font-size: 14px;
  color: var(--theme-text-faint);
}
.libraryCard__body {
  display: grid;
}
.libraryCard__title {
  font-weight: 800;
  letter-spacing: -0.02em;
  font-size: 18px;
}
.libraryCard__meta {
  color: var(--theme-text-soft);
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.libraryCard-move,
.libraryCard-enter-active,
.libraryCard-leave-active {
  transition: transform 280ms ease, opacity 220ms ease;
}

.libraryCard-enter-from,
.libraryCard-leave-to {
  opacity: 0;
  transform: translateY(10px) scale(0.985);
}

.libraryCard-leave-active {
  position: absolute;
  width: calc(100% - 0px);
  pointer-events: none;
}

.libraryEmpty {
  padding: 20px 0;
  color: var(--theme-text-muted);
}
@media (max-width: 1400px) {
  .libraryGrid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
@media (max-width: 1200px) {
  .libraryGrid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (max-width: 900px) {
  .libraryGrid {
    grid-template-columns: 1fr;
  }
}
@media (max-width: 720px) {
  .libraryGrid {
    grid-template-columns: 1fr;
  }
}
</style>
