﻿<script setup>
import { onMounted, onBeforeUnmount } from 'vue'
import { RouterView } from 'vue-router'
import { App } from '@capacitor/app'
import BottomDock from './components/BottomDock.vue'
import AddEntryView from './views/AddEntryView.vue'
import { useTransactionStore } from './stores/transactions'
import { useUiStore } from './stores/ui'

const transactionStore = useTransactionStore()
const uiStore = useUiStore()

let backButtonListener = null

onMounted(() => {
  transactionStore.ensureInitialized()

  // Android 物理返回键：如果新增记录面板打开，则优先关闭面板而不是直接退出应用
  if (typeof App?.addListener === 'function') {
    App.addListener('backButton', ({ canGoBack }) => {
      if (uiStore.addEntryVisible) {
        uiStore.closeAddEntry()
      } else if (!canGoBack) {
        // 这里保留默认行为（由 Capacitor 处理），不强制 exitApp
      }
    })
      .then((handle) => {
        backButtonListener = handle
      })
      .catch(() => {
        backButtonListener = null
      })
  }
})

onBeforeUnmount(() => {
  if (backButtonListener && typeof backButtonListener.remove === 'function') {
    backButtonListener.remove()
    backButtonListener = null
  }
})
</script>

<template>
  <!-- 整体应用容器：居中展示移动端画布，配合沉浸式状态栏使用安全区域内边距 -->
  <div class="min-h-screen bg-warmOffwhite text-stone-800 flex items-center justify-center">
    <div
      class="h-screen max-h-[844px] max-w-md w-full mx-auto bg-warmOffwhite shadow-2xl relative overflow-hidden flex flex-col"
      style="padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom);"
    >
      <!-- 主内容区域：由 vue-router 控制具体页面 -->
      <main class="flex-1 overflow-y-auto hide-scrollbar px-5 pt-2 pb-28 relative">
        <RouterView />
      </main>

      <!-- 底部 Dock 导航 -->
      <BottomDock />

      <!-- 新增记录底部弹窗：在任意 Tab 上浮层显示 -->
      <AddEntryView v-if="uiStore.addEntryVisible" />
    </div>
  </div>
</template>
