<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

import { screenerApi, type StrategyTrack } from "../../shared/api/screener";
import EmptyState from "../../shared/components/EmptyState.vue";
import MarketEntityLink from "../../shared/market/MarketEntityLink.vue";
import { useUiStore } from "../../shared/stores/ui";

const router = useRouter();
const ui = useUiStore();
const rows = ref<StrategyTrack[]>([]);
const loading = ref(true);
const error = ref("");
async function load(): Promise<void> {
  loading.value = true;
  try { rows.value = await screenerApi.tracks(); }
  catch (reason) { error.value = reason instanceof Error ? reason.message : "策略跟踪读取失败"; }
  finally { loading.value = false; }
}
async function remove(row: StrategyTrack): Promise<void> {
  try { await screenerApi.removeTrack(row.id); ui.showToast(`${row.name} 已停止跟踪`); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "操作失败"); }
}
function number(value: number | null): string { return value === null ? "" : value.toFixed(2); }
onMounted(load);
</script>

<template>
  <main class="page-frame tracking-page">
    <header class="page-header"><div><button class="btn btn-ghost" type="button" @click="router.push('/workspace/screener')">← 返回智能选股</button><h1>策略持续跟踪</h1><p class="page-subtitle">仅跟踪手动加入的候选，按账户独立保存</p></div></header>
    <div v-if="loading" class="card workspace-state">正在读取跟踪记录</div>
    <EmptyState v-else-if="error" class="card" title="跟踪记录暂不可用" :description="error" />
    <EmptyState v-else-if="!rows.length" class="card" title="暂无跟踪记录" description="从任一候选结果中点击“加入跟踪”后，记录会出现在这里。" />
    <section v-else class="card tracking-table"><div class="data-table-wrap"><table class="data-table"><thead><tr><th>代码</th><th>股票</th><th>策略</th><th>入选日期</th><th class="numeric">入选价（元）</th><th class="numeric">T+1开盘（%）</th><th class="numeric">T+1收盘（%）</th><th class="numeric">T+3收盘（%）</th><th class="numeric">T+5收盘（%）</th><th class="numeric">最大涨幅（%）</th><th class="numeric">最大回撤（%）</th><th>操作</th></tr></thead><tbody><tr v-for="row in rows" :key="row.id"><td><MarketEntityLink :entity="{ entity_type: 'stock', identifier: row.identifier, code: row.code, name: row.name, sector: row.sector }" /></td><td>{{ row.name }}</td><td>{{ row.strategy_name }}</td><td>{{ row.selection_date }}</td><td class="numeric">{{ number(row.entry_price) }}</td><td class="numeric">{{ number(row.t1_open_return) }}</td><td class="numeric">{{ number(row.t1_return) }}</td><td class="numeric">{{ number(row.t3_return) }}</td><td class="numeric">{{ number(row.t5_return) }}</td><td class="numeric up">{{ number(row.max_gain) }}</td><td class="numeric down">{{ number(row.max_drawdown) }}</td><td><button class="btn btn-small" type="button" @click="remove(row)">停止</button></td></tr></tbody></table></div></section>
  </main>
</template>
