<template>
  <van-config-provider :theme="theme" class="app-provider">
    <div class="app-root">
      <RouterView />
      <van-tabbar v-model="active" v-show="showTabbar">
        <van-tabbar-item name="ccalendar" icon="notes" to="/calendar">
          日历
        </van-tabbar-item>
        <van-tabbar-item name="statistics" icon="chart-trending-o" to="/statistics">
          统计
        </van-tabbar-item>
        <van-tabbar-item name="balance" icon="balance-list" to="/" @click="handleTabClick('/')">
          账单
        </van-tabbar-item>
        <van-tabbar-item name="email" icon="records" to="/email" @click="handleTabClick('/email')">
          邮件
        </van-tabbar-item>
        <van-tabbar-item name="setting" icon="setting" to="/setting">
          设置
        </van-tabbar-item>
      </van-tabbar>
    </div>
  </van-config-provider>
</template>

<script setup>
import { RouterView, useRoute } from 'vue-router'
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import '@/styles/common.css'

const updateVh = () => {
  // 获取真实的视口高度（PWA 模式下准确）
  const vh = window.innerHeight
  // 设置 CSS 变量，让所有组件使用准确的视口高度
  document.documentElement.style.setProperty('--vh', `${vh}px`)
}

onMounted(() => {
  updateVh()
  window.addEventListener('resize', updateVh)
  // 监听 iOS Safari 视口变化
  if (window.visualViewport) {
    window.visualViewport.addEventListener('resize', updateVh)
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', updateVh)
  if (window.visualViewport) {
    window.visualViewport.removeEventListener('resize', updateVh)
  }
})

const route = useRoute()
// 根据路由判断是否显示Tabbar
const showTabbar = computed(() => {
  return route.path === '/' ||
    route.path === '/calendar' ||
    route.path === '/email' ||
    route.path === '/setting' ||
    route.path === '/statistics'
})

const active = ref('')
const theme = ref('light')

// 检测系统深色模式
const updateTheme = () => {
  const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
  theme.value = isDark ? 'dark' : 'light'
}

// 监听系统主题变化
let mediaQuery
onMounted(() => {
  updateTheme()
  mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', updateTheme)
  setActive(route.path)
})

// 监听路由变化调整
watch(() => route.path, (newPath) => {
  setActive(newPath)
})

const setActive = (path) => {
  active.value = (() => {
    switch (path) {
      case '/calendar':
        return 'ccalendar'
      case '/statistics':
        return 'statistics'
      case '/email':
        return 'email'
      case '/setting':
        return 'setting'
      default:
        return 'balance'
    }
  })()
  console.log(active.value, path)
}

onUnmounted(() => {
  if (mediaQuery) {
    mediaQuery.removeEventListener('change', updateTheme)
  }
})

// 处理tab点击，如果点击当前页面则滚动到顶部
const handleTabClick = (path) => {
  if (route.path === path) {
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

</script>

<style scoped>
.app-provider {
  /* 使用准确的视口高度 CSS 变量 */
  height: var(--vh, 100vh);
  width: 100%;
}

.app-root {
  height: 100%;
  width: 100%;
  position: relative;
  margin-top: max(0px, calc(env(safe-area-inset-top, 0px) * 0.75));
}

/* TabBar 固定在底部 */
:deep(.van-tabbar) {
  position: fixed !important;
  bottom: 0 !important;
  left: 0;
  right: 0;
  /* 重置所有 padding，然后只添加安全区域 */
  padding: 0 !important;
  padding-bottom: env(safe-area-inset-bottom, 0px) !important;
  height: 50px !important;
  min-height: 50px !important;
}

/* 确保 TabBar 项目居中 */
:deep(.van-tabbar-item) {
  padding: 0 !important;
}
</style>
