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

import { marketApi } from "../../shared/api/market";
import { reviewApi } from "../../shared/api/review";
import { useMarketStore } from "../../shared/stores/market";
import { useSessionStore } from "../../shared/stores/session";
import { useUiStore } from "../../shared/stores/ui";
import { findWorkspace } from "../workspaceRegistry";
import TradingDateControl from "./TradingDateControl.vue";

const route = useRoute();
const router = useRouter();
const market = useMarketStore();
const session = useSessionStore();
const ui = useUiStore();
const menuOpen = ref(false);
const menuRoot = ref<HTMLElement | null>(null);
const refreshing = ref(false);

const title = computed(() => {
  if (typeof route.meta.title === "string") return route.meta.title;
  return findWorkspace(String(route.params.workspace ?? "emotion"))?.title ?? "小白复盘";
});

function closeOnOutside(event: MouseEvent): void {
  if (!menuRoot.value?.contains(event.target as Node)) menuOpen.value = false;
}

function openAccountDialog(name: "profile" | "membership" | "password"): void {
  menuOpen.value = false;
  ui.openDialog(name);
}

async function endSession(action: "logout" | "switch-account"): Promise<void> {
  menuOpen.value = false;
  try {
    await session.endSession(action);
    await router.replace("/workspace/emotion");
  } catch (error) {
    ui.showToast(error instanceof Error ? error.message : "操作失败，请稍后重试。");
  }
}

async function refreshMarket(): Promise<void> {
  if (refreshing.value) return;
  refreshing.value = true;
  try {
    const result = await marketApi.syncSnapshot(market.selectedDate);
    ui.showToast(`${result.trade_date} 行情快照已更新，刷新页面后读取新数据`);
  } catch (error) {
    ui.showToast(error instanceof Error ? error.message : "行情刷新失败，请稍后重试");
  } finally {
    refreshing.value = false;
  }
}

async function refreshAlerts(): Promise<void> {
  try { ui.alertUnread = (await reviewApi.alerts()).unread_count; }
  catch { ui.alertUnread = 0; }
}

onMounted(() => { document.addEventListener("mousedown", closeOnOutside); void refreshAlerts(); });
onBeforeUnmount(() => document.removeEventListener("mousedown", closeOnOutside));
</script>

<template>
  <header class="topbar">
    <span class="topbar-title">{{ title }}</span>
    <div class="topbar-spacer"></div>
    <TradingDateControl class="desktop-only" />
    <button class="icon-button" type="button" aria-label="全局搜索" title="全局搜索（Ctrl+K）" @click="ui.openDialog('search')">⌕</button>
    <button class="icon-button topbar-alert desktop-only" type="button" aria-label="提醒中心" title="提醒中心" @click="ui.openDialog('alerts')">!<span v-if="ui.alertUnread" class="alert-badge">{{ ui.alertUnread > 99 ? '99+' : ui.alertUnread }}</span></button>
    <button class="icon-button desktop-only" type="button" aria-label="复盘助手" title="复盘助手" @click="ui.openDialog('assistant')">复</button>
    <button class="btn btn-small" type="button" :title="ui.theme === 'light' ? '切换夜间模式' : '切换日间模式'" @click="ui.toggleTheme">
      {{ ui.theme === "light" ? "夜间" : "日间" }}
    </button>
    <button v-if="session.isAdmin" class="btn btn-small desktop-only" type="button" :disabled="refreshing" @click="refreshMarket">{{ refreshing ? "刷新中" : "后台刷新" }}</button>
    <button v-if="session.isAdmin" class="btn btn-small desktop-only" type="button" @click="router.push('/system')">系统管理</button>
    <div class="identity-cluster">
      <button v-if="session.isMember" class="tag tag-vip" type="button" title="查看会员状态" @click="ui.openDialog('membership')">V 会员</button>
      <span v-if="session.isAdmin" class="tag tag-admin">管理员</span>
      <button v-if="!session.isMember" class="tag desktop-only" type="button" @click="ui.openDialog('membership')">普通用户</button>
    </div>
    <div ref="menuRoot" class="account-menu-wrap">
      <button class="btn btn-small account-trigger" type="button" :aria-expanded="menuOpen" @click="menuOpen = !menuOpen">
        <span class="account-name">{{ session.account?.username }}</span><span class="mobile-account-label">账户</span><span aria-hidden="true">⌄</span>
      </button>
      <div v-if="menuOpen" class="account-menu">
        <button type="button" @click="openAccountDialog('profile')">个人资料</button>
        <button type="button" @click="openAccountDialog('membership')">会员状态</button>
        <button type="button" @click="openAccountDialog('password')">修改密码</button>
        <button type="button" @click="endSession('switch-account')">切换账号</button>
        <button type="button" @click="endSession('logout')">退出</button>
      </div>
    </div>
  </header>
</template>
