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

import type { Candidate, ScreenerRun, ScreenerStrategy } from "../../shared/api/screener";
import CandidateTable from "./CandidateTable.vue";

const props = defineProps<{ strategies: ScreenerStrategy[]; runs: ScreenerRun[]; labels: Record<string, string>; locked: boolean }>();
const emit = defineEmits<{ track: [run: ScreenerRun, candidate: Candidate] }>();
const query = ref("");
const category = ref("全部流派");
const view = ref<"list" | "grid">("list");
const categories = computed(() => ["全部流派", ...new Set(props.strategies.map((item) => item.formula.meta?.category ?? "其他"))]);
const filtered = computed(() => props.strategies.filter((item) => {
  const matchCategory = category.value === "全部流派" || item.formula.meta?.category === category.value;
  return matchCategory && (!query.value.trim() || item.name.includes(query.value.trim()));
}));
const selected = ref(props.strategies[0]?.id ?? "");
const strategy = computed(() => props.strategies.find((item) => item.id === selected.value) ?? filtered.value[0]);
const run = computed(() => props.runs.find((item) => item.strategy_id === strategy.value?.id));
const regimeLabels: Record<string, string> = { ice: "冰点", repair: "修复", fermentation: "发酵", climax: "高潮", divergence: "分化", retreat: "退潮" };

function statusLabel(strategyId: string): string {
  const status = props.runs.find((item) => item.strategy_id === strategyId)?.status;
  return ({
    pending: "未执行",
    running: "执行中",
    completed: "有候选",
    no_signal: "暂无信号",
    data_incomplete: "数据不足",
    failed: "计算失败",
  } as Record<string, string>)[status ?? "pending"] ?? "未执行";
}
</script>

<template>
  <section class="strategy-layout" :class="{ 'locked-content': locked }" :aria-disabled="locked">
    <aside class="card strategy-library">
      <header class="card-header"><h2>策略库</h2><span class="tag">{{ filtered.length }} 套</span></header>
      <div class="strategy-tools">
        <input v-model="query" class="input" type="search" placeholder="搜索策略">
        <select v-model="category" class="select"><option v-for="item in categories" :key="item">{{ item }}</option></select>
        <div class="seg-control" aria-label="排列方式"><button type="button" :class="{ active: view === 'list' }" title="列表排列" @click="view = 'list'">≡</button><button type="button" :class="{ active: view === 'grid' }" title="图标排列" @click="view = 'grid'">▦</button></div>
      </div>
      <div class="strategy-items" :class="`is-${view}`">
        <button v-for="item in filtered" :key="item.id" type="button" :class="{ active: strategy?.id === item.id }" @click="selected = item.id">
          <strong>{{ item.display_name }}</strong><small>{{ item.formula.meta?.category }}</small>
          <span :class="['strategy-status', runs.find((run) => run.strategy_id === item.id)?.status]">{{ statusLabel(item.id) }}</span>
        </button>
      </div>
    </aside>
    <article class="card strategy-detail">
      <header><div><span>{{ strategy?.formula.meta?.category }}</span><h2>{{ strategy?.display_name }}</h2></div><span class="tag">{{ strategy?.formula.meta?.frequency ?? "每日" }}</span></header>
      <p>{{ strategy?.description }}</p>
      <dl><div><dt>策略质量</dt><dd>{{ strategy?.formula.meta?.quality ?? "待评估" }}</dd></div><div><dt>风险等级</dt><dd>{{ strategy?.formula.meta?.risk ?? "未标注" }}</dd></div><div><dt>执行频率</dt><dd>{{ strategy?.formula.meta?.frequency ?? "每日" }}</dd></div><div><dt>适用环境</dt><dd>{{ strategy?.formula.meta?.suitable_environment }}</dd></div><div><dt>主要失效风险</dt><dd>{{ strategy?.formula.meta?.failure_risk }}</dd></div><div><dt>适用阶段</dt><dd>{{ strategy?.regimes.map((item) => regimeLabels[item]).join(" · ") }}</dd></div></dl>
      <div class="strategy-conditions"><h3>选股条件</h3><span v-for="condition in strategy?.formula.filters" :key="`${condition.field}-${condition.op}`">{{ labels[condition.field] }} {{ condition.op }} {{ Array.isArray(condition.value) ? condition.value.join(' 至 ') : condition.value }}</span></div>
      <div class="strategy-conditions"><h3>评分权重</h3><span v-for="score in strategy?.formula.score" :key="score.field">{{ labels[score.field] }} · {{ Math.round(score.weight * 100) }}% · {{ score.direction === 'desc' ? '高优' : '低优' }}</span></div>
    </article>
  </section>
  <CandidateTable :run="run" :locked="locked" @track="(candidate) => run && emit('track', run, candidate)" />
</template>
