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

import type { MarketWorkspaceData } from "../../../shared/api/market";

const props = defineProps<{ data: MarketWorkspaceData }>();
const days = ref<10 | 20 | 60>(20);
const sentiment = computed(() => props.data.sentiment ?? {});
const stats = computed<Record<string, number>>(
  () => (sentiment.value.stats as Record<string, number> | undefined) ?? {},
);
const components = computed<Record<string, unknown>[]>(
  () => (sentiment.value.components as Record<string, unknown>[] | undefined) ?? [],
);
const history = computed(() => (props.data.history ?? []).slice(-days.value));
const graph = computed(() => (props.data.history ?? []).slice(-20));
const width = 720;
const height = 190;
const inset = 18;

function pointX(index: number): number {
  return inset + (index / Math.max(graph.value.length - 1, 1)) * (width - inset * 2);
}

function pointY(value: unknown): number {
  return height - inset - (Number(value ?? 0) / 100) * (height - inset * 2);
}

const temperaturePath = computed(() =>
  graph.value.map((item, index) => `${index ? "L" : "M"}${pointX(index)},${pointY(item.temperature)}`).join(" "),
);
const averagePath = computed(() =>
  graph.value.map((_, index) => {
    const window = graph.value.slice(Math.max(0, index - 4), index + 1);
    const average = window.reduce((sum, item) => sum + Number(item.temperature ?? 0), 0) / window.length;
    return `${index ? "L" : "M"}${pointX(index)},${pointY(average)}`;
  }).join(" "),
);

const warning = computed(() => {
  if (sentiment.value.direction === "降温") return "情绪指标继续走弱";
  if (sentiment.value.direction === "升温") return "情绪指标正在回暖";
  return "情绪指标保持平稳";
});

function number(value: unknown, digits = 0): string {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed.toFixed(digits) : "";
}

function amount(value: unknown): string {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? `${(parsed / 100_000_000).toFixed(2)} 亿` : "";
}

function selectDays(value: number): void {
  if (value === 10 || value === 20 || value === 60) days.value = value;
}
</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="emotion-overview">
    <article class="card temperature-card">
      <header class="card-header"><h2>温度走势</h2><span class="faint">情绪温度 · 五日均线</span></header>
      <div class="temperature-chart-wrap">
        <svg class="temperature-chart" :viewBox="`0 0 ${width} ${height}`" role="img" aria-label="情绪温度走势">
          <line v-for="line in [20, 40, 60, 80]" :key="line" class="temperature-grid" :x1="inset" :x2="width - inset" :y1="pointY(line)" :y2="pointY(line)" />
          <path class="temperature-average" :d="averagePath" />
          <path class="temperature-line" :d="temperaturePath" />
          <circle v-for="(item, index) in graph" :key="String(item.trade_date)" class="temperature-point" :cx="pointX(index)" :cy="pointY(item.temperature)" :r="3" />
        </svg>
      </div>
    </article>

    <article class="card phase-card">
      <header class="card-header"><h2>当前阶段</h2><span class="tag">{{ sentiment.phase }}</span></header>
      <div class="phase-body">
        <div class="phase-name">{{ sentiment.phase }}</div>
        <div class="phase-confidence">置信度 {{ sentiment.confidence }}%</div>
        <p>{{ sentiment.transition_reason }}</p>
        <div class="phase-metrics">
          <span>温度 <strong>{{ sentiment.score }}</strong></span>
          <span>较前日 <strong>{{ Number(sentiment.day_change ?? 0) > 0 ? "+" : "" }}{{ sentiment.day_change }}</strong></span>
          <span>{{ sentiment.direction }}</span>
          <span>封板率 <strong>{{ number(data.overview.seal_rate, 1) }}%</strong></span>
          <span>涨停 <strong>{{ data.overview.limit_up }}</strong> / 炸板 <strong>{{ data.overview.broken }}</strong></span>
          <span>昨涨停红盘 <strong>{{ number(stats.positive_rate, 1) }}%</strong></span>
          <span>样本 <strong>{{ stats.yesterday_count }}</strong></span>
        </div>
        <div class="notice notice-warning phase-warning">{{ warning }}</div>
      </div>
    </article>
  </section>

  <section class="card component-card">
    <header class="card-header"><h2>评分构成</h2><span class="faint">五维加权后执行系统健康门控</span></header>
    <div class="component-grid">
      <div v-for="component in components" :key="String(component.key)" class="component-item">
        <div><span>{{ component.label }}</span><strong>{{ number(component.score, 1) }}</strong></div>
        <div class="score-track"><span :style="{ width: `${Number(component.score ?? 0)}%` }"></span></div>
        <small>权重 {{ component.weight }}%</small>
      </div>
    </div>
  </section>

  <section class="card history-card">
    <header class="card-header history-header">
      <h2>交易日明细</h2>
      <div class="seg-control" aria-label="明细天数">
        <button v-for="value in [10, 20, 60]" :key="value" type="button" :class="{ active: days === value }" @click="selectDays(value)">{{ value }}日</button>
      </div>
    </header>
    <div class="data-table-wrap emotion-history-wrap">
      <table class="data-table emotion-history-table">
        <thead><tr><th>日期</th><th class="numeric">温度</th><th>阶段</th><th>方向</th><th class="numeric">红盘率（%）</th><th class="numeric">封板率（%）</th><th class="numeric">涨停</th><th class="numeric">炸板</th><th class="numeric">跌停</th><th class="numeric">最高板</th><th class="numeric">成交额（亿）</th></tr></thead>
        <tbody><tr v-for="item in history" :key="String(item.trade_date)"><td>{{ item.trade_date }}</td><td class="numeric">{{ item.temperature }}</td><td>{{ item.phase }}</td><td>{{ item.direction }}</td><td class="numeric">{{ number(item.positive_rate, 1) }}</td><td class="numeric">{{ number(item.seal_rate, 1) }}</td><td class="numeric">{{ item.limit_up }}</td><td class="numeric">{{ item.broken }}</td><td class="numeric">{{ item.limit_down }}</td><td class="numeric">{{ item.max_height }}</td><td class="numeric">{{ amount(item.amount) }}</td></tr></tbody>
      </table>
    </div>
  </section>
</template>
