<script setup lang="ts">
import { computed, ref, watch } from "vue";

import { marketApi, type MarketInsightData, type MarketWorkspaceData } from "../../shared/api/market";
import EmptyState from "../../shared/components/EmptyState.vue";
import { useMarketStore } from "../../shared/stores/market";
import EmotionPage from "./emotion/EmotionPage.vue";
import LadderPage from "./structure/LadderPage.vue";
import RotationPage from "./structure/RotationPage.vue";
import AuctionPage from "./insights/AuctionPage.vue";
import DragonPage from "./insights/DragonPage.vue";
import PopularityPage from "./insights/PopularityPage.vue";
import ThemesPage from "./insights/ThemesPage.vue";
import PerformancePage from "./pools/PerformancePage.vue";
import PoolPage from "./pools/PoolPage.vue";

const props = defineProps<{ workspaceKey: string }>();
const market = useMarketStore();
const data = ref<MarketWorkspaceData | MarketInsightData | null>(null);
const insightData = computed(() => data.value as MarketInsightData);
const loading = ref(false);
const error = ref("");
let sequence = 0;

async function load(): Promise<void> {
  const current = ++sequence;
  loading.value = true;
  error.value = "";
  try {
    const result = ["auction", "themes", "popularity", "dragon-list"].includes(props.workspaceKey)
      ? await marketApi.insight(props.workspaceKey, market.selectedDate)
      : await marketApi.workspace(props.workspaceKey, market.selectedDate);
    if (current === sequence) data.value = result;
  } catch (reason) {
    if (current === sequence) error.value = reason instanceof Error ? reason.message : "页面数据读取失败";
  } finally {
    if (current === sequence) loading.value = false;
  }
}

watch([() => props.workspaceKey, () => market.selectedDate], () => void load(), { immediate: true });
</script>

<template>
  <main class="page-frame market-workspace-page">
    <div v-if="loading" class="card workspace-state">正在读取本地复盘数据</div>
    <EmptyState v-else-if="error" title="页面数据暂不可用" :description="error" class="card" />
    <EmptyState v-else-if="!data?.trade_date" title="暂无真实行情快照" :description="data?.message || '等待管理员首次同步真实收盘行情'" class="card" />
    <EmotionPage v-else-if="workspaceKey === 'emotion'" :data="data" />
    <LadderPage v-else-if="workspaceKey === 'ladder'" :data="data" />
    <RotationPage v-else-if="workspaceKey === 'rotation'" :data="data" />
    <AuctionPage v-else-if="workspaceKey === 'auction'" :data="insightData" />
    <ThemesPage v-else-if="workspaceKey === 'themes'" :data="insightData" />
    <PopularityPage v-else-if="workspaceKey === 'popularity'" :data="insightData" />
    <DragonPage v-else-if="workspaceKey === 'dragon-list'" :data="insightData" @refresh="load" />
    <PerformancePage v-else-if="workspaceKey === 'performance'" :data="data" />
    <PoolPage v-else :kind="workspaceKey" :data="data" />
  </main>
</template>
