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

import { heavenApi, type HeavenReading, type HeavenSetup, type ReadingMode } from "../../shared/api/heaven";
import { useMarketStore } from "../../shared/stores/market";
import { useSessionStore } from "../../shared/stores/session";
import { useUiStore } from "../../shared/stores/ui";
import FortunePanel from "./FortunePanel.vue";
import HeartPanel from "./HeartPanel.vue";
import InterpretDialog from "./InterpretDialog.vue";
import TrendPanel from "./TrendPanel.vue";

const market = useMarketStore();
const route = useRoute();
const session = useSessionStore();
const ui = useUiStore();
const mode = ref<ReadingMode>(["trend", "fortune", "heart"].includes(String(route.query.mode)) ? String(route.query.mode) as ReadingMode : "trend");
const setup = ref<HeavenSetup | null>(null);
const loading = ref(false);
const error = ref("");
const activeReading = ref<HeavenReading | null>(null);
const locked = computed(() => !session.account?.smart_access);
const labels: Record<ReadingMode, { title: string; subtitle: string }> = {
  trend: { title: "观势", subtitle: "以客观行情量化三才六爻" },
  fortune: { title: "观气", subtitle: "以五运六气观照当日气机" },
  heart: { title: "观心", subtitle: "静心、起卦，察见第一念" },
};

async function load(): Promise<void> {
  setup.value = null;
  error.value = "";
  if (locked.value) return;
  loading.value = true;
  try {
    setup.value = await heavenApi.setup(market.selectedDate);
  } catch (reason) {
    error.value = reason instanceof Error ? reason.message : "问天数据读取失败";
  } finally {
    loading.value = false;
  }
}

function openInterpret(reading: HeavenReading): void {
  activeReading.value = reading;
  if (!setup.value?.history.some((item) => item.id === reading.id)) {
    setup.value?.history.unshift(reading);
  }
}

function saveFortune(reading: HeavenReading): void {
  if (!setup.value) return;
  setup.value.daily_fortune = reading;
  if (!setup.value.history.some((item) => item.id === reading.id)) setup.value.history.unshift(reading);
}

function completed(reading: HeavenReading): void {
  if (!setup.value) return;
  const index = setup.value.history.findIndex((item) => item.id === reading.id);
  if (index >= 0) setup.value.history[index] = reading;
  if (reading.mode === "fortune") setup.value.daily_fortune = reading;
}

watch([() => market.selectedDate, locked], load, { immediate: true });
</script>

<template>
  <main class="page-frame heaven-page">
    <header class="page-header heaven-page-header">
      <div><h1>问天</h1><p class="page-subtitle">观天之道 · 执天之行 · 数据日期 {{ setup?.date || market.selectedDate }}</p></div>
      <button class="btn btn-small" type="button" :disabled="locked || !setup?.history.length" @click="activeReading = setup?.history[0] || null">历史记录</button>
    </header>
    <div v-if="locked" class="notice notice-warning membership-lock"><span><strong>问天仅对会员开放</strong>，开通会员后可使用观势、观气与观心。</span><button class="btn btn-small" type="button" @click="ui.openDialog('membership')">查看会员状态</button></div>
    <nav class="heaven-mode-tabs" aria-label="问天模式">
      <button v-for="(item, key) in labels" :key="key" type="button" :class="{ active: mode === key }" @click="mode = key"><strong>{{ item.title }}</strong><span>{{ item.subtitle }}</span></button>
    </nav>
    <div v-if="loading" class="card workspace-state">正在推演当日基础气机</div>
    <div v-else-if="error" class="notice notice-warning">{{ error }}</div>
    <div v-else :class="{ 'locked-content': locked }" :aria-disabled="locked">
      <TrendPanel v-if="mode === 'trend'" :disabled="locked" :initial-query="String(route.query.query || '')" @interpret="openInterpret" />
      <FortunePanel v-else-if="mode === 'fortune'" :field="setup?.fortune || null" :daily="setup?.daily_fortune || null" :disabled="locked" @interpret="openInterpret" @saved="saveFortune" />
      <HeartPanel v-else :disabled="locked" @interpret="openInterpret" />
    </div>
    <InterpretDialog v-if="activeReading" :reading="activeReading" :history="setup?.history || []" @close="activeReading = null" @completed="completed" />
  </main>
</template>
