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

import { useMarketStore } from "../../shared/stores/market";

const expanded = ref(false);
const market = useMarketStore();
const values = computed(() => market.summary?.values ?? {});
const cells = computed(() => [
  ["市场情绪", display("temperature")],
  ["涨停", display("limit_up")],
  ["跌停", display("limit_down")],
  ["炸板", display("broken")],
  ["封板率", percent("seal_rate")],
  ["两市成交", amount("amount")],
  ["数据日期", observedTime()],
]);

function display(key: string): string {
  const value = values.value[key];
  return typeof value === "number" || typeof value === "string" ? String(value) : "";
}

function percent(key: string): string {
  const value = values.value[key];
  return typeof value === "number" ? `${value.toFixed(1)}%` : "";
}

function amount(key: string): string {
  const value = values.value[key];
  return typeof value === "number" ? `${(value / 100_000_000).toFixed(2)} 亿` : "";
}

function observedTime(): string {
  const observed = market.summary?.context.observed_at;
  if (!observed) return "";
  return new Intl.DateTimeFormat("zh-CN", {
    timeZone: "Asia/Shanghai",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(new Date(observed));
}
</script>

<template>
  <section class="market-strip" aria-label="市场摘要">
    <div class="market-strip-row">
      <span class="market-emotion"><span class="emotion-dot" aria-hidden="true"></span>市场情绪</span>
      <span>涨停 {{ display("limit_up") }}</span>
      <span>跌停 {{ display("limit_down") }}</span>
      <span>炸板 {{ display("broken") }}</span>
      <span>封板率 {{ percent("seal_rate") }}</span>
      <span>两市成交 {{ amount("amount") }}</span>
      <span class="faint">{{ market.loading ? "正在读取行情" : observedTime() || market.summary?.context.message || market.error }}</span>
      <button class="market-toggle" type="button" :aria-expanded="expanded" @click="expanded = !expanded">
        {{ expanded ? "收起详情" : "展开详情" }}
      </button>
    </div>
    <div v-if="expanded" class="market-details">
      <div v-for="cell in cells" :key="cell[0]" class="market-cell">
        <div class="market-cell-label">{{ cell[0] }}</div>
        <div class="market-cell-value">{{ cell[1] }}</div>
      </div>
    </div>
  </section>
</template>
