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

import { marketApi, type ChartSeries, type MarketEntity } from "../api/market";
import MarketChart from "./MarketChart.vue";

const props = defineProps<{ entity: MarketEntity | null }>();
const interval = ref<"day" | "minute">("day");
const series = ref<ChartSeries | null>(null);
const loading = ref(false);
const error = ref("");
let requestSequence = 0;

async function load(): Promise<void> {
  const entity = props.entity;
  if (!entity) {
    series.value = null;
    return;
  }
  const sequence = ++requestSequence;
  loading.value = true;
  error.value = "";
  try {
    const result = await marketApi.chart(entity, interval.value);
    if (sequence === requestSequence) series.value = result;
  } catch (reason) {
    if (sequence === requestSequence) {
      series.value = null;
      error.value = reason instanceof Error ? reason.message : "行情读取失败";
    }
  } finally {
    if (sequence === requestSequence) loading.value = false;
  }
}

watch(() => props.entity?.identifier, () => {
  interval.value = "day";
  void load();
}, { immediate: true });
watch(interval, () => void load());
</script>

<template>
  <section class="market-preview">
    <header v-if="entity" class="preview-header">
      <div><strong>{{ entity.name }}</strong><span>{{ entity.code }}</span></div>
      <div class="seg-control" aria-label="行情周期">
        <button type="button" :class="{ active: interval === 'day' }" @click="interval = 'day'">日K</button>
        <button type="button" :class="{ active: interval === 'minute' }" @click="interval = 'minute'">分时</button>
      </div>
    </header>
    <div v-if="loading" class="preview-state">正在读取真实行情</div>
    <div v-else-if="error" class="preview-state">{{ error }}</div>
    <MarketChart v-else-if="series" :series="series" />
    <div v-else class="preview-state">选择一个结果查看最新行情</div>
    <footer v-if="series" class="preview-meta">
      数据日期 {{ series.trade_date }}<template v-if="series.interval === 'minute'"> · 分时范围固定 09:30–15:00</template>
    </footer>
  </section>
</template>
