<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="/" @click="handleTabClick('/statistics')">
          统计
        </van-tabbar-item>
        <van-tabbar-item name="balance" icon="balance-list" to="/balance" @click="handleTabClick('/balance')">
          账单
        </van-tabbar-item>
        <van-tabbar-item name="message" icon="comment" to="/message" @click="handleTabClick('/message')" :badge="messageStore.unreadCount || null">
          消息
        </van-tabbar-item>
        <van-tabbar-item name="setting" icon="setting" to="/setting">
          设置
        </van-tabbar-item>
      </van-tabbar>
      <GlobalAddBill @success="handleAddTransactionSuccess"/>
    </div>
  </van-config-provider>
</template>

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

const messageStore = useMessageStore()

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 === '/message' ||
    route.path === '/setting' ||
    route.path === '/balance'
})

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)
})

setInterval(() => {
  messageStore.updateUnreadCount()
}, 30 * 1000) // 每30秒更新一次未读消息数

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

const setActive = (path) => {
  active.value = (() => {
    switch (path) {
      case '/calendar':
        return 'ccalendar'
      case '/balance':
        return 'balance'
      case '/message':
        return 'message'
      case '/setting':
        return 'setting'
      default:
        return 'statistics'
    }
  })()
  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' })
  }
}

const handleAddTransactionSuccess = () => {
  // 当添加交易成功时，通知当前页面刷新数据
  const event = new Event('transactions-changed')
  window.dispatchEvent(event)
}

// 辅助函数：将 Base64 字符串转换为 Uint8Array
const urlBase64ToUint8Array = (base64String) => {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);
  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

const subscribeToPush = async () => {
  if (!('serviceWorker' in navigator)) return;

  // 1. 获取 VAPID 公钥
  const response = await fetch('/api/notification/vapid-public-key');
  const { publicKey } = await response.json();

  // 2. 等待 Service Worker 准备就绪
  const registration = await navigator.serviceWorker.ready;

  // 3. 请求订阅
  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicKey)
  });

  // 4. 将订阅信息发送给后端
  // 注意：后端 PushSubscriptionEntity 字段首字母大写，这里需要转换或让后端兼容
  const subJson = subscription.toJSON();
  await fetch('/api/notification/subscribe', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      endpoint: subJson.endpoint,
      p256dh: subJson.keys.p256dh,
      auth: subJson.keys.auth
    })
  });
}

</script>

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

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

/* 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: auto !important;
  min-height: 50px !important;
  box-sizing: content-box !important;
}

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

.debug-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  font-size: 12px;
  pointer-events: auto;
}
</style>
