<script setup lang="ts">
import { onLaunch } from '@dcloudio/uni-app'
import { wxLogin, demoLogin } from '@/api/auth'
import { useGroupStore } from '@/stores/group'
import { saveLoginResult } from '@/utils/request'
import { markReady } from '@/utils/app-ready'

/** 登录重试（最多3次） */
async function loginWithRetry(loginFn: () => Promise<any>, retries = 3): Promise<boolean> {
  for (let i = 0; i < retries; i++) {
    try {
      const data = await loginFn()
      saveLoginResult(data)
      return true
    } catch (e) {
      console.error(`[Auth] Login attempt ${i + 1} failed:`, e)
      if (i < retries - 1) {
        // 等待1秒后重试
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    }
  }
  return false
}

onLaunch(() => {
  const groupStore = useGroupStore()
  groupStore.init()

  // #ifdef MP-WEIXIN
  uni.login({
    provider: 'weixin',
    success: async (loginRes) => {
      if (loginRes.code) {
        const success = await loginWithRetry(() => wxLogin(loginRes.code))
        if (success) {
          groupStore.fetchGroups()
          console.log('[Auth] Login success')
        } else {
          uni.showToast({ title: '登录失败，请重试', icon: 'none', duration: 3000 })
        }
      }
      markReady()
    }
  })
  // #endif

  // #ifdef H5
  const token = uni.getStorageSync('xc:token')
  if (!token) {
    loginWithRetry(demoLogin).then((success) => {
      if (success) {
        groupStore.fetchGroups()
        console.log('[Auth] H5 demo login success')
      } else {
        uni.showToast({ title: '登录失败，请刷新页面', icon: 'none', duration: 3000 })
      }
      markReady()
    })
  } else {
    groupStore.fetchGroups()
    markReady()
    console.log('[Auth] H5 token exists')
  }
  // #endif
})
</script>

<style lang="scss">
@import './uni.scss';

// 全局盒模型
view, text, image, input, textarea, scroll-view, picker {
  box-sizing: border-box;
}

page {
  background-color: $bg;
  font-family: 'Nunito', 'PingFang SC', sans-serif;
  color: $text;
  -webkit-font-smoothing: antialiased;
}
</style>
