<script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { auth } from "@/lib/nvwa";
import { AUTH_REQUIRED } from "@/lib/config";
import redirectToLogin from "@/custom/redirect-to-login";
import { setupIframeHoverInspector, setupIframeSourceLocationListener } from "@nvwa-app/sdk-uniapp";

// 如果页面被嵌入 iframe，设置跨域通信监听器
if (typeof window !== 'undefined') {
  setupIframeHoverInspector();
  setupIframeSourceLocationListener();
}

onLaunch(async () => {
  console.log("App Launch");
  
  // 如果需要认证，检查登录状态
  if (AUTH_REQUIRED) {
    try {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage?.route || "";
      
      // 如果当前不在登录页或注册页，检查登录状态
      if (!currentRoute.includes("user/login") && !currentRoute.includes("user/register")) {
        const user = await auth.currentUser();
        if (!user) {
          // 未登录，重定向到登录页
          await redirectToLogin();
        }
      }
    } catch (error) {
      // 获取用户信息失败，重定向到登录页
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage?.route || "";
      if (!currentRoute.includes("user/login") && !currentRoute.includes("user/register")) {
        await redirectToLogin();
      }
    }
  }
});
onShow(() => {
  console.log("App Show");
});
onHide(() => {
  console.log("App Hide");
});
</script>
<style>
@import './main.css';
</style>
