<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { tenantPath } from "../utils/tenant";
import { contentApi } from "../api/content";

const route = useRoute();
const router = useRouter();
const tenantRoute = (path) => tenantPath(path, route);

const STATIC_TOPICS = [
  {
    id: 1,
    title: "程派艺术赏析：幽咽婉转后的风骨",
    desc: "程砚秋先生创立的“程派”艺术，以其独特的发音技巧和深沉的情感表达著称。本专题精选《锁麟囊》、《荒山泪》等代表剧目，带您领略程腔的无穷魅力。",
    cover:
      "https://images.unsplash.com/photo-1514306191717-452ec28c7f31?ixlib=rb-1.2.1&auto=format&fit=crop&w=1200&q=80",
    tag: "流派精选",
    date: "2025-01-01",
    count: 12,
  },
  {
    id: 2,
    title: "零基础戏曲身段教学：手眼身法步",
    desc: "戏曲表演讲究“四功五法”。本专题专为初学者打造，从最基础的云手、台步开始，由名家亲自示范，助您打好戏曲表演的基本功。",
    cover:
      "https://images.unsplash.com/photo-1533174072545-e8d4aa97edf9?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    tag: "名家教学",
    date: "2024-12-28",
    count: 24,
  },
  {
    id: 3,
    title: "昆曲《牡丹亭》：跨越四百年的爱恋",
    desc: "“情不知所起，一往而深。” 汤显祖笔下的杜丽娘与柳梦梅，演绎了一段传颂千古的爱情神话。本专题汇集不同版本的高清全本实录。",
    cover:
      "https://images.unsplash.com/photo-1469571486292-0ba58a3f068b?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    tag: "经典剧目",
    date: "2024-12-15",
    count: 8,
  },
  {
    id: 4,
    title: "京剧打击乐：锣鼓经入门",
    desc: "锣鼓是戏曲的灵魂。本专题将带您认识单皮鼓、大锣、铙钹等打击乐器，解析常见的锣鼓经及其在表演中的作用。",
    cover:
      "https://images.unsplash.com/photo-1516450360452-9312f5e86fc7?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    tag: "器乐知识",
    date: "2024-12-10",
    count: 6,
  },
  {
    id: 5,
    title: "地方戏曲巡礼：秦腔的高亢与悲壮",
    desc: "秦腔是中国最古老的剧种之一，以其粗犷豪放的风格著称。让我们走进黄土高原，感受秦腔艺术的独特魅力。",
    cover:
      "https://images.unsplash.com/photo-1557683316-973673baf926?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80",
    tag: "地方戏曲",
    date: "2024-12-05",
    count: 15,
  },
];

const topics = ref([...STATIC_TOPICS]);

const KNOWN_GENRES = [
  "京剧",
  "昆曲",
  "越剧",
  "黄梅戏",
  "豫剧",
  "评剧",
  "秦腔",
  "河北梆子",
];

const findGenre = (topic) => {
  const text = (topic.title + topic.tag).toLowerCase();
  return KNOWN_GENRES.find((g) => text.includes(g));
};

const navigateToTopic = (topic) => {
  const genre = findGenre(topic);
  const target = tenantRoute("/explore");

  if (genre) {
    router.push({ path: target, query: { genre } });
  } else {
    // Fallback: navigate to explore without specific genre if no match found
    router.push(target);
  }
};

onMounted(async () => {
  try {
    const res = await contentApi.listTopics();
    if (res && Array.isArray(res) && res.length > 0) {
      topics.value = res.map((item, index) => ({
        id: item.id || index + 100, // Safe ID
        title: item.title || "未命名专题",
        desc: item.desc || `探索${item.title || "精彩内容"}的更多详情。`,
        cover:
          item.cover ||
          "https://images.unsplash.com/photo-1514306191717-452ec28c7f31?auto=format&fit=crop&w=800",
        tag: item.tag || "精选",
        date: item.date || new Date().toISOString().split("T")[0],
        count: item.count || 0,
      }));
    }
  } catch (err) {
    console.warn("Failed to load topics, using fallback:", err);
    // Keep STATIC_TOPICS
  }
});
</script>

<template>
  <div class="mx-auto max-w-screen-xl py-8 min-h-screen px-4 sm:px-6 lg:px-8">
    <div class="flex items-center justify-between mb-8">
      <h1 class="text-2xl font-bold text-slate-900">精选专题</h1>
      <div class="text-sm text-slate-500">共 {{ topics.length }} 个专题</div>
    </div>

    <!-- 1. Hero Topic -->
    <div
      v-if="topics.length > 0"
      class="relative w-full h-[400px] rounded-2xl overflow-hidden mb-12 group cursor-pointer shadow-lg"
      @click="navigateToTopic(topics[0])"
    >
      <img
        :src="topics[0].cover"
        class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
      />
      <div
        class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent"
      ></div>
      <div class="absolute bottom-0 left-0 p-10 max-w-3xl text-white">
        <div class="flex items-center gap-3 mb-4">
          <span
            class="px-3 py-1 bg-red-600 text-white text-xs font-bold rounded uppercase tracking-wider"
            >本周主打</span
          >
          <span class="text-sm font-medium opacity-80"
            ># {{ topics[0].tag }}</span
          >
        </div>
        <h2 class="text-4xl font-bold mb-4 leading-tight">
          {{ topics[0].title }}
        </h2>
        <p class="text-lg text-slate-200 line-clamp-2 mb-6 opacity-90">
          {{ topics[0].desc }}
        </p>
        <div class="flex items-center gap-4">
          <div class="flex -space-x-2">
            <img
              v-for="i in 3"
              :key="i"
              :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${topics[0].id + i}`"
              class="w-8 h-8 rounded-full border-2 border-white/20 bg-white/10 backdrop-blur-sm"
            />
          </div>
          <span class="text-sm font-medium"
            >收录 {{ topics[0].count }} 篇精选内容
            <i class="pi pi-arrow-right ml-1 text-xs"></i
          ></span>
        </div>
      </div>
    </div>

    <!-- 2. Masonry-like Grid -->
    <div
      class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
      v-if="topics.length > 1"
    >
      <div
        v-for="(topic, idx) in topics.slice(1)"
        :key="topic.id"
        class="group bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden hover:shadow-xl transition-all cursor-pointer flex flex-col"
        :class="{ 'lg:col-span-2 flex-row': idx === 0 }"
        @click="navigateToTopic(topic)"
      >
        <!-- Cover -->
        <div
          class="relative overflow-hidden"
          :class="idx === 0 ? 'w-1/2' : 'h-48'"
        >
          <img
            :src="topic.cover"
            class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
          />
          <div
            class="absolute inset-0 bg-black/10 group-hover:bg-transparent transition-colors"
          ></div>
          <div class="absolute top-4 left-4">
            <span
              class="px-2 py-1 bg-white/90 backdrop-blur text-slate-800 text-xs font-bold rounded shadow-sm"
              ># {{ topic.tag }}</span
            >
          </div>
        </div>

        <!-- Info -->
        <div
          class="p-6 flex flex-col flex-1"
          :class="idx === 0 ? 'w-1/2 justify-center' : ''"
        >
          <div
            class="flex items-center justify-between mb-3 text-xs text-slate-400"
          >
            <span>更新于 {{ topic.date }}</span>
            <span>{{ topic.count }} 篇内容</span>
          </div>
          <h3
            class="text-xl font-bold text-slate-900 mb-3 group-hover:text-primary-600 transition-colors line-clamp-2"
          >
            {{ topic.title }}
          </h3>
          <p
            class="text-slate-500 text-sm leading-relaxed line-clamp-2 mb-6 flex-1"
          >
            {{ topic.desc }}
          </p>

          <!-- Preview Thumbs (For large cards) -->
          <div v-if="idx === 0" class="flex gap-2 mt-auto">
            <div
              v-for="n in 3"
              :key="n"
              class="w-12 h-8 rounded bg-slate-100 overflow-hidden"
            >
              <img
                :src="`https://images.unsplash.com/photo-1514306191717-452ec28c7f31?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=60`"
                class="w-full h-full object-cover opacity-80"
              />
            </div>
          </div>

          <!-- Footer (For small cards) -->
          <div
            v-else
            class="flex items-center justify-between pt-4 border-t border-slate-50 mt-auto"
          >
            <div class="flex -space-x-2">
              <img
                v-for="n in 2"
                :key="n"
                :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${topic.id + n}`"
                class="w-6 h-6 rounded-full border border-white bg-slate-50"
              />
            </div>
            <span
              class="text-primary-600 text-sm font-bold group-hover:translate-x-1 transition-transform"
              >浏览专题 <i class="pi pi-angle-right"></i
            ></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
