<template>
  <view class="page projects-page">
    <view class="projects-head">
      <view>
        <text class="page-title">项目</text>
        <text class="page-subtitle">所有从小程序或网页创建的视频项目都会在这里汇总。</text>
      </view>
      <button class="projects-head__add" @tap="goCreate">+</button>
    </view>

    <view v-if="loading" class="empty panel projects-empty">
      <text class="empty__title">正在加载</text>
      <text class="empty__desc">项目列表马上就绪。</text>
    </view>
    <view v-else-if="projects.length" class="project-list">
      <ProjectCard v-for="(project, index) in projects" :key="project.id" :project="project" :index="index" @open="openProject(project.id)" />
    </view>
    <view v-else class="empty panel projects-empty">
      <text class="empty__title">暂无项目</text>
      <text class="empty__desc">创建第一个视频任务后，进度和结果会自动出现在这里。</text>
      <button class="primary-button empty__button" @tap="goCreate">创建任务</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import ProjectCard from "@/components/ProjectCard.vue";
import { listProjects } from "@/api/projects";
import type { ProjectSummary } from "@/types/api";
import { useAuthStore } from "@/stores/auth";

const auth = useAuthStore();
const projects = ref<ProjectSummary[]>([]);
const loading = ref(false);

onShow(() => {
  auth.hydrate();
  if (!auth.isLoggedIn) {
    uni.reLaunch({ url: "/pages/login/index" });
    return;
  }
  fetchProjects();
});

async function fetchProjects() {
  loading.value = true;
  try {
    projects.value = await listProjects();
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "项目读取失败", icon: "none" });
  } finally {
    loading.value = false;
  }
}

function openProject(projectId: string | number) {
  uni.navigateTo({ url: `/pages/project-progress/index?projectId=${projectId}` });
}

function goCreate() {
  uni.navigateTo({ url: "/pages/create/index" });
}
</script>

<style scoped lang="scss">
.projects-head {
  display: flex;
  justify-content: space-between;
  gap: 24rpx;
}

.projects-head__add {
  width: 80rpx;
  height: 80rpx;
  border-radius: 24rpx;
  background: rgba(255, 255, 255, 0.14);
  color: #ffffff;
  font-size: 42rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.project-list {
  display: flex;
  flex-direction: column;
  gap: 18rpx;
  margin-top: 34rpx;
}

.projects-empty {
  margin-top: 34rpx;
}

.empty__button {
  margin-top: 28rpx;
}
</style>
