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

import type { MarketInsightData } from "../../../shared/api/market";
import DataTable from "../../../shared/components/DataTable.vue";
import EmptyState from "../../../shared/components/EmptyState.vue";
import { formatNumber, sortRows, type SortDirection } from "../../../shared/market/table";

const props = defineProps<{ data: MarketInsightData }>();
const source = ref<"combined" | "ths" | "dc">("combined");
const query = ref("");
const sortKey = ref("rank");
const sortDirection = ref<SortDirection>("asc");
const sourceRows = computed(() => props.data[source.value] ?? []);
const rows = computed(() => {
  const normalized = query.value.trim().toLocaleLowerCase();
  const filtered = sourceRows.value.filter((row) => !normalized || [row.code, row.name, ...(row.concepts as unknown[] ?? [])]
    .some((value) => String(value ?? "").toLocaleLowerCase().includes(normalized)));
  return sortRows(filtered, sortKey.value, sortDirection.value);
});
const columns = [
  { key: "rank", label: "排名", numeric: true, sortable: true },
  { key: "code", label: "代码", code: true, sortable: true },
  { key: "name", label: "股票", sortable: true },
  { key: "change", label: "涨跌幅（%）", numeric: true, sortable: true, format: number },
  { key: "ths_rank", label: "同花顺排名", numeric: true, sortable: true },
  { key: "dc_rank", label: "东方财富排名", numeric: true, sortable: true },
  { key: "rank_change", label: "排名变化", numeric: true, sortable: true, format: signed },
  { key: "concepts", label: "相关题材", wide: true, format: concepts },
  { key: "reason", label: "上榜线索", wide: true },
];
const topThs = computed(() => (props.data.ths ?? []).slice(0, 3));
const topDc = computed(() => (props.data.dc ?? []).slice(0, 3));
const consensus = computed(() => (props.data.combined ?? []).filter((row) => row.dual_source).slice(0, 3));

function sort(key: string): void {
  if (sortKey.value === key) sortDirection.value = sortDirection.value === "asc" ? "desc" : "asc";
  else { sortKey.value = key; sortDirection.value = key === "rank" ? "asc" : "desc"; }
}
function number(value: unknown): string { return formatNumber(value, 2); }
function signed(value: unknown): string {
  const text = formatNumber(value, 0);
  return text && Number(value) > 0 ? `+${text}` : text;
}
function concepts(value: unknown): string { return Array.isArray(value) ? value.join(" · ") : ""; }
</script>

<template>
  <header class="page-header market-page-header">
    <div><h1>人气热榜</h1><p class="page-subtitle">双平台人气与共识 · 榜单日期 {{ data.trade_date }}</p></div>
    <span v-if="data.message" class="tag warning">{{ data.message }}</span>
  </header>
  <section class="popularity-summary-strip">
    <article><header><span>同花顺热度 Top3</span><strong>{{ data.summary.ths_count ?? 0 }}只</strong></header><p>{{ topThs.map((item) => item.name).join(' · ') || '暂无榜单' }}</p></article>
    <article><header><span>东方财富热度 Top3</span><strong>{{ data.summary.dc_count ?? 0 }}只</strong></header><p>{{ topDc.map((item) => item.name).join(' · ') || '暂无榜单' }}</p></article>
    <article><header><span>双榜共识</span><strong>{{ data.summary.dual_count ?? 0 }}只</strong></header><p>{{ consensus.map((item) => item.name).join(' · ') || '暂无共识' }}</p></article>
  </section>
  <section class="card popularity-table-card">
    <div class="popularity-toolbar">
      <div class="seg-control"><button type="button" :class="{ active: source === 'combined' }" @click="source = 'combined'">双榜综合</button><button type="button" :class="{ active: source === 'ths' }" @click="source = 'ths'">同花顺</button><button type="button" :class="{ active: source === 'dc' }" @click="source = 'dc'">东方财富</button></div>
      <label class="search-control"><span>搜索</span><input v-model="query" type="search" placeholder="代码、名称或题材"></label>
    </div>
    <DataTable v-if="rows.length" :columns="columns" :rows="rows" :sort-key="sortKey" :sort-direction="sortDirection" @sort="sort" />
    <EmptyState v-else title="暂无人气榜结果" description="当日榜单尚未生成时，系统会显示最近有效榜单并标注真实日期。" />
  </section>
</template>
