<template>
  <!-- Login overlay -->
  <div v-if="!auth.loggedIn" class="login-overlay">
    <div class="login-banner">
      <div class="circle c1"></div>
      <div class="circle c2"></div>
      <div class="circle c3"></div>
    </div>
    <div class="login-card">
      <h1 class="login-title">Hera's Planner</h1>
      <p class="login-subtitle">规划每一天，成为更好的自己</p>
      <div class="login-input-wrap">
        <input
          class="login-input"
          type="password"
          placeholder="密码"
          v-model="password"
          @keydown.enter="doLogin"
        >
        <button class="login-btn" @click="doLogin">进入</button>
      </div>
      <div class="login-error">{{ loginError }}</div>
    </div>
  </div>

  <!-- Main app -->
  <template v-else>
    <header>
      <div class="header-main">
        <div class="header-top">
          <h1>
            Hera's Planner
            <span class="header-subtitle">v2.0</span>
          </h1>
          <div class="header-actions">
            <button class="header-menu-btn" @click="showMenu = !showMenu">⋮</button>
            <div v-if="menuMask" class="dropdown-mask open" @click="showMenu = false"></div>
            <div class="header-dropdown" :class="{ open: showMenu }">
              <button @click="doExport">导出数据</button>
              <button @click="doChangePassword">修改密码</button>
              <button @click="doBackup">手动备份</button>
              <button class="dd-danger" @click="doLogout">退出登录</button>
            </div>
          </div>
        </div>
      </div>
      <nav class="tabs">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          class="tab-btn"
          :class="{ active: ui.currentTab === tab.key }"
          @click="goTab(tab.key)"
        >{{ tab.label }}</button>
      </nav>
    </header>

    <main>
      <router-view />
    </main>
  </template>

  <!-- Toast messages -->
  <div v-for="(msg, i) in ui.toasts" :key="i" class="toast">{{ msg }}</div>

  <!-- Custom Dialog -->
  <CustomDialog />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from './stores/auth'
import { useUiStore } from './stores/ui'
import { usePlannerStore } from './stores/planner'
import CustomDialog from './components/CustomDialog.vue'

const auth = useAuthStore()
const ui = useUiStore()
const planner = usePlannerStore()
const router = useRouter()
const route = useRoute()

const password = ref('')
const loginError = ref('')
const showMenu = ref(false)
const menuMask = computed(() => showMenu.value)

const tabs = [
  { key: 'notes', label: '随手记', path: '/' },
  { key: 'tasks', label: '待办', path: '/tasks' },
  { key: 'reminders', label: '提醒', path: '/reminders' },
  { key: 'body', label: '身体', path: '/body' },
  { key: 'music', label: '音乐', path: '/music' },
  { key: 'docs', label: '文档', path: '/docs' },
  { key: 'planning', label: '日程', path: '/planning' },
]

const tabKeyToPath = Object.fromEntries(tabs.map(t => [t.key, t.path]))
const pathToTabKey = Object.fromEntries(tabs.map(t => [t.path, t.key]))

function goTab(key) {
  ui.setTab(key)
  router.push(tabKeyToPath[key] || '/')
}

async function doLogin() {
  loginError.value = ''
  try {
    await auth.login(password.value)
    password.value = ''
    planner.loadAll()
  } catch (e) {
    loginError.value = e.message || '登录失败'
  }
}

function doLogout() {
  showMenu.value = false
  auth.logout()
}

function doExport() {
  showMenu.value = false
  ui.toast('导出功能开发中')
}

async function doChangePassword() {
  showMenu.value = false
  ui.toast('修改密码功能开发中')
}

async function doBackup() {
  showMenu.value = false
  try {
    const { api } = await import('./composables/useApi')
    await api.post('/api/backup')
    ui.toast('备份完成')
  } catch {
    ui.toast('备份失败')
  }
}

onMounted(async () => {
  // Sync tab from route
  const tabKey = pathToTabKey[route.path] || 'notes'
  ui.setTab(tabKey)

  if (auth.loggedIn) {
    await planner.loadAll()
  }

  // Register service worker
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js').catch(() => {})
  }
})
</script>
