<template>
  <view class="page">
    <!-- 搜索栏 -->
    <view class="search-bar" @click="goToSearch">
      <text class="search-icon">🔍</text>
      <text class="search-placeholder">搜索专辑...</text>
      <!-- 通知铃铛 -->
      <view class="notif-bell" @click.stop="showNotifications">
        <text class="bell-icon">🔔</text>
        <view v-if="notifStore.unreadCount > 0" class="bell-badge">{{ notifStore.unreadCount > 99 ? '99+' : notifStore.unreadCount }}</view>
      </view>
    </view>

    <!-- 骨架屏加载状态 -->
    <scroll-view scroll-y class="album-list" @scrolltolower="loadMore" v-if="loading && bookList.length === 0" :scroll-top="scrollTop">
      <!-- 最近收听骨架屏 -->
      <view v-if="userStore.isLoggedIn" class="recent-section">
        <view class="skeleton-section-title"></view>
        <scroll-view scroll-x class="recent-scroll" enable-flex>
          <view v-for="i in 4" :key="i" class="recent-card skeleton-recent-card">
            <view class="skeleton-recent-cover"></view>
            <view class="skeleton-recent-title"></view>
            <view class="skeleton-recent-progress"></view>
          </view>
        </scroll-view>
      </view>
      <view class="skeleton-grid">
        <view v-for="i in 6" :key="i" class="skeleton-card">
          <view class="skeleton-cover"></view>
          <view class="skeleton-info">
            <view class="skeleton-title"></view>
            <view class="skeleton-meta"></view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 书籍列表 -->
    <scroll-view scroll-y class="album-list" @scrolltolower="loadMore" v-else :scroll-top="scrollTop">
      <!-- 最近收听 -->
      <view v-if="userStore.isLoggedIn && recentAudios.length > 0" class="recent-section">
        <text class="section-title">最近收听</text>
        <scroll-view scroll-x class="recent-scroll" enable-flex>
          <view
            v-for="item in recentAudios"
            :key="item.id"
            class="recent-card"
            @click="goToPlayer(item)"
          >
            <view class="recent-cover" :style="{ background: getRecentGradient(item.id) }">
              <image v-if="item.coverUrl" :src="item.coverUrl" mode="aspectFill" class="cover-img" />
              <text v-else class="cover-icon">📖</text>
              <view class="recent-progress-bar">
                <view class="progress-fill" :style="{ width: item.progress + '%' }"></view>
              </view>
            </view>
            <text class="recent-title">{{ item.title }}</text>
            <text class="recent-progress">{{ formatProgress(item.progress) }}</text>
          </view>
        </scroll-view>
      </view>

      <!-- 冷启动引导（新用户无内容时） -->
      <view v-if="bookList.length === 0 && !loading && recentAudios.length === 0" class="onboarding">
        <view class="onboarding-card">
          <text class="onboarding-icon">🎧</text>
          <text class="onboarding-title">欢迎来到有声书 AI</text>
          <text class="onboarding-desc">AI 为你创作专属有声书，从选题到配音全自动完成</text>
          <button class="onboarding-btn" @click="quickCreateBook">
            ✨ 创建我的第一本有声书
          </button>
        </view>
        <view class="template-section">
          <text class="template-title">💡 快速模板</text>
          <view class="template-list">
            <view
              v-for="tpl in quickTemplates"
              :key="tpl.title"
              class="template-card"
              @click="useQuickTemplate(tpl)"
            >
              <text class="template-icon">{{ tpl.icon }}</text>
              <text class="template-name">{{ tpl.title }}</text>
              <text class="template-desc">{{ tpl.desc }}</text>
            </view>
          </view>
        </view>
      </view>

      <view v-else-if="bookList.length === 0 && !loading" class="empty">
        <text class="empty-icon">📚</text>
        <text class="empty-text">暂无书籍</text>
        <text class="empty-hint">点击下方按钮创建第一本书籍</text>
      </view>

      <view v-else class="album-grid">
        <view
          v-for="(item, index) in bookList"
          :key="item.id"
          class="album-card"
          :style="{ animationDelay: (index * 0.05) + 's' }"
          @click="goToAlbumDetail(item)"
        >
          <view class="album-cover" :style="{ background: getCoverGradient(item) }">
            <text class="cover-letter" :style="{ opacity: 0.15 }">{{ getTitleLetter(item.title) }}</text>
            <text class="cover-title-small">{{ item.title }}</text>
            <view class="album-count">{{ item.completedChapters || 0 }}/{{ item.totalChapters || 0 }}章</view>
          </view>
          <view class="album-info">
            <text class="album-title">{{ item.title }}</text>
            <text class="album-desc">{{ item.description || '暂无描述' }}</text>
            <text class="album-meta">进度 {{ item.progress || 0 }}%</text>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>

      <view v-if="!hasMore && bookList.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="bottom-bar">
      <button class="action-btn" @click="goToAlbums">
        <text class="btn-icon">📚</text>
        <text class="btn-text">管理书籍</text>
      </button>
      <button class="generate-btn" @click="goToBookGenerator">
        <text class="btn-icon">+</text>
        <text class="btn-text">生成书籍</text>
      </button>
    </view>

    <!-- 迷你播放器 -->
    <MiniPlayer />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getPublicBooks } from '../../utils/book-generator-api';
import { get } from '../../utils/request';
import { useUserStore } from '../../store/user';
import { useNotificationStore } from '../../store/notification';
import MiniPlayer from '../../components/MiniPlayer.vue';
import { getBookGradient, getTitleLetter } from '../../composables/useCoverStyle';

// scroll-top 用于避免 scrollTop 错误
const scrollTop = ref(0);

interface Book {
  id: number;
  title: string;
  subtitle?: string;
  description?: string;
  coverUrl?: string;
  genStage?: string;
  progress: number;
  totalChapters: number;
  completedChapters: number;
  createdAt: string;
}

const bookList = ref<Book[]>([]);
const page = ref(1);
const pageSize = 20;
const total = ref(0);
const loading = ref(false);
const hasMore = ref(true);

// 最近收听
interface RecentAudio {
  id: string;
  title: string;
  coverUrl: string;
  progress: number;
  updatedAt: string;
}
const recentAudios = ref<RecentAudio[]>([]);
const loadingRecent = ref(false);
const userStore = useUserStore();
const notifStore = useNotificationStore();

// 快速模板
const quickTemplates = [
  { icon: '🔬', title: '科普短文', desc: '用通俗语言解释一个科学概念，适合大众阅读', description: '用通俗易懂的语言，深入浅出地解释一个科学概念或自然现象。要求：逻辑清晰、例证生动、引发读者好奇心。' },
  { icon: '🌙', title: '睡前故事', desc: '温馨治愈的短篇故事，适合睡前收听', description: '创作一个温馨治愈的短篇故事，主题围绕友情、成长或奇幻冒险。要求：情节温暖、语言优美、有情感共鸣，适合睡前收听。' },
  { icon: '📝', title: '知识总结', desc: '系统梳理一个知识领域的核心要点', description: '系统梳理一个知识领域的核心概念、发展脉络和关键要点。要求：结构清晰、内容准确、重点突出，帮助读者快速建立知识框架。' },
];

function quickCreateBook() {
  uni.navigateTo({ url: '/pages/book-generator/interactive' });
}

function useQuickTemplate(tpl: { title: string; description: string }) {
  // 将模板信息通过 globalData 传递到创建页
  const app = getApp();
  if (app) {
    app.globalData = app.globalData || {};
    app.globalData.quickTemplate = { title: tpl.title, description: tpl.description };
  }
  uni.navigateTo({ url: '/pages/book-generator/interactive' });
}

// 封面颜色映射
// 获取封面渐变色
function getCoverGradient(item: Book): string {
  return getBookGradient(item.id);
}

// 获取最近收听封面渐变色
function getRecentGradient(id: string | number): string {
  return getBookGradient(Number(id));
}

// 获取书籍列表
async function fetchBookList(isLoadMore = false) {
  if (loading.value) return;
  if (!isLoadMore) {
    page.value = 1;
  }

  loading.value = true;
  try {
    // 首页只显示公开的书籍
    const books = await getPublicBooks();

    if (isLoadMore) {
      bookList.value.push(...books);
    } else {
      bookList.value = books || [];
    }
    hasMore.value = false; // 暂时不支持分页
  } catch (error) {
    console.error('获取书籍列表失败:', error);
  } finally {
    loading.value = false;
  }
}

// 获取最近收听
async function fetchRecentAudios() {
  if (loadingRecent.value || !userStore.isLoggedIn) return;

  loadingRecent.value = true;
  try {
    const res = await get<{ list: RecentAudio[] }>('/player/recent');
    recentAudios.value = res?.list || [];
  } catch (error) {
    console.error('获取最近收听失败:', error);
    recentAudios.value = [];
  } finally {
    loadingRecent.value = false;
  }
}

// 格式化进度
function formatProgress(progress: number): string {
  if (!progress && progress !== 0) return '0%';
  return `${Math.round(progress)}%`;
}

// 跳转播放
function goToPlayer(item: RecentAudio) {
  uni.navigateTo({ url: `/pages/player/index?id=${item.id}` });
}

// 加载更多
function loadMore() {
  if (hasMore.value && !loading.value) {
    page.value++;
    fetchBookList(true);
  }
}

// 跳转书籍详情
function goToAlbumDetail(item: Book) {
  uni.navigateTo({ url: `/pages/album/index?id=${item.id}` });
}

// 跳转书籍管理页
function goToAlbums() {
  uni.switchTab({ url: '/pages/book-generator/index' });
}

// 跳转书籍生成页
function goToBookGenerator() {
  uni.switchTab({ url: '/pages/book-generator/index' });
}

// 跳转搜索页
function goToSearch() {
  uni.navigateTo({ url: '/pages/search/index' });
}

// 显示通知列表
function showNotifications() {
  if (notifStore.notifications.length === 0) {
    uni.showToast({ title: '暂无通知', icon: 'none' });
    return;
  }
  const items = notifStore.notifications.slice(0, 5).map((n, i) => {
    const prefix = n.read ? '' : '● ';
    return `${prefix}${n.title}`;
  });
  uni.showActionSheet({
    itemList: items.length > 0 ? items : ['暂无通知'],
    success: (res) => {
      const notif = notifStore.notifications[res.tapIndex];
      if (notif) {
        notifStore.markRead(notif.id);
        if (notif.bookId) {
          uni.navigateTo({ url: `/pages/book-generator/detail?id=${notif.bookId}` });
        }
      }
    },
  });
}

// 初始化
onMounted(async () => {
  console.log('首页加载了, platform:', uni.getSystemInfoSync().platform);
  uni.showToast({ title: '首页加载中', icon: 'none' });
  await fetchBookList();
  if (userStore.isLoggedIn) {
    fetchRecentAudios();
  }
});

// 页面显示时刷新
onShow(() => {
  fetchBookList();
  if (userStore.isLoggedIn) {
    fetchRecentAudios();
  }
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
  padding-bottom: calc(180rpx + env(safe-area-inset-bottom) + 120rpx);
}

.search-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  padding-top: env(safe-area-inset-top);
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  display: flex;
  align-items: center;
  padding-left: 24rpx;
  padding-right: 24rpx;
  z-index: 100;
}

.search-icon {
  font-size: 28rpx;
  margin-right: 12rpx;
}

.search-placeholder {
  flex: 1;
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
}

/* 通知铃铛 */
.notif-bell {
  position: relative;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-left: 12rpx;
}

.bell-icon {
  font-size: 36rpx;
}

.bell-badge {
  position: absolute;
  top: 4rpx;
  right: 0;
  min-width: 32rpx;
  height: 32rpx;
  background: #ef4444;
  color: #ffffff;
  font-size: 20rpx;
  font-weight: 600;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6rpx;
  border: 2rpx solid #ffffff;
}

/* 最近收听区域 */
.recent-section {
  padding: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20rpx;
  display: block;
}

.recent-scroll {
  white-space: nowrap;
  width: 100%;
}

.recent-card {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  vertical-align: top;
}

.recent-cover {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-img {
  width: 100%;
  height: 100%;
}

.recent-progress-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 8rpx;
  background: rgba(0, 0, 0, 0.3);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4f46e5 0%, #818cf8 100%);
  transition: width 0.3s ease;
}

.recent-title {
  font-size: 26rpx;
  color: #1f2937;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 12rpx;
}

.recent-progress {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
  margin-top: 4rpx;
}

.album-list {
  padding-top: 120rpx;
  height: calc(100vh - 120rpx);
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #6b7280;
  margin-bottom: 12rpx;
}

.empty-hint {
  font-size: 26rpx;
  color: #9ca3af;
}

/* 冷启动引导 */
.onboarding {
  padding: 32rpx 24rpx;
}

.onboarding-card {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  text-align: center;
  margin-bottom: 32rpx;
}

.onboarding-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.onboarding-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #ffffff;
  display: block;
  margin-bottom: 12rpx;
}

.onboarding-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.85);
  display: block;
  margin-bottom: 28rpx;
  line-height: 1.5;
}

.onboarding-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  padding: 0 40rpx;
  background: #ffffff;
  color: #4f46e5;
  font-size: 28rpx;
  font-weight: 600;
  border-radius: 40rpx;
  border: none;
}

.onboarding-btn::after { border: none; }

.template-section {
  margin-bottom: 24rpx;
}

.template-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 16rpx;
}

.template-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.template-card {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: transform 0.1s;
}

.template-card:active {
  transform: scale(0.98);
}

.template-icon {
  font-size: 40rpx;
  flex-shrink: 0;
}

.template-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  flex-shrink: 0;
  min-width: 120rpx;
}

.template-desc {
  font-size: 24rpx;
  color: #9ca3af;
  flex: 1;
}

.album-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 24rpx;
  gap: 20rpx;
}

.album-card {
  width: calc(50% - 10rpx);
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  animation: listItemIn 0.4s ease-out forwards;
  opacity: 0;
}

@keyframes listItemIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.album-cover {
  position: relative;
  width: 100%;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.cover-letter {
  position: absolute;
  font-size: 160rpx;
  font-weight: 800;
  color: #ffffff;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
}

.cover-title-small {
  position: absolute;
  bottom: 48rpx;
  left: 16rpx;
  right: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.95);
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.album-count {
  position: absolute;
  bottom: 12rpx;
  right: 12rpx;
  background: rgba(0, 0, 0, 0.6);
  color: #ffffff;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.album-info {
  padding: 20rpx;
}

.album-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #1f2937;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 8rpx;
}

.album-desc {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 8rpx;
}

.album-meta {
  font-size: 22rpx;
  color: #9ca3af;
}

.loading,
.no-more {
  text-align: center;
  padding: 32rpx;
}

.loading text,
.no-more text {
  font-size: 24rpx;
  color: #9ca3af;
}

/* 骨架屏样式 */
.skeleton-section-title {
  height: 32rpx;
  width: 120rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.skeleton-recent-card {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  vertical-align: top;
}

.skeleton-recent-cover {
  width: 200rpx;
  height: 200rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 16rpx;
}

.skeleton-recent-title {
  height: 26rpx;
  width: 80%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin-top: 12rpx;
}

.skeleton-recent-progress {
  height: 22rpx;
  width: 50%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin-top: 8rpx;
}

.skeleton-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 24rpx;
  gap: 20rpx;
}

.skeleton-card {
  width: calc(50% - 10rpx);
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.skeleton-cover {
  width: 100%;
  height: 200rpx;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-info {
  padding: 20rpx;
}

.skeleton-title {
  height: 28rpx;
  width: 80%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
  margin-bottom: 12rpx;
}

.skeleton-meta {
  height: 22rpx;
  width: 50%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 8rpx;
}

@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: calc(100rpx + env(safe-area-inset-bottom));
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx 32rpx;
  background: #ffffff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  background: #f5f5f5;
  border-radius: 44rpx;
  border: none;
  transition: transform 0.1s ease;
}

.action-btn:active {
  transform: scale(0.96);
}

.action-btn::after {
  border: none;
}

.generate-btn {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 44rpx;
  border: none;
  transition: transform 0.1s ease;
}

.generate-btn:active {
  transform: scale(0.96);
}

.generate-btn::after {
  border: none;
}

.btn-icon {
  font-size: 32rpx;
  color: #ffffff;
  margin-right: 8rpx;
}

.btn-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #ffffff;
}

.action-btn .btn-text {
  color: #333;
}

/* 夜间模式适配 */
.dark-mode .section-title {
  color: #f3f4f6;
}

.dark-mode .recent-title {
  color: #e5e7eb;
}

.dark-mode .recent-progress {
  color: #6b7280;
}

.dark-mode .album-card {
  background: #1f2937;
}

.dark-mode .album-title {
  color: #f3f4f6;
}

.dark-mode .album-desc {
  color: #9ca3af;
}

.dark-mode .album-meta {
  color: #6b7280;
}

.dark-mode .bottom-bar {
  background: #1f2937;
}

.dark-mode .action-btn {
  background: #374151;
}

.dark-mode .action-btn .btn-text {
  color: #e5e7eb;
}

.dark-mode .page {
  background: #111827;
}

.dark-mode .cover-title-small {
  color: rgba(255, 255, 255, 0.9);
}

/* 夜间模式骨架屏 */
.dark-mode .skeleton-section-title,
.dark-mode .skeleton-recent-cover,
.dark-mode .skeleton-recent-title,
.dark-mode .skeleton-recent-progress {
  background: linear-gradient(90deg, #374151 25%, #4b5563 50%, #374151 75%);
  background-size: 200% 100%;
}
</style>
