import { PropsWithChildren } from 'react'
import Taro, { useLaunch } from '@tarojs/taro'
import { login } from './utils/request'
import './app.scss'

function App({ children }: PropsWithChildren<any>) {

  useLaunch((options) => {
    console.log('App launched.', options)
    
    // 捕获邀请码 (场景值或直接参数)
    const { query } = options
    if (query) {
        let inviteCode = ''
        if (query.scene) {
            // 扫码进入，scene 需要解码
            inviteCode = decodeURIComponent(query.scene)
        } else if (query.invite_code) {
            // 链接分享进入
            inviteCode = query.invite_code
        }
        
        if (inviteCode && inviteCode !== 'undefined') {
            console.log('Captured invite code:', inviteCode)
            Taro.setStorageSync('invite_code', inviteCode)
        }
    }

    // Auto login only if user info with phone number exists
    const userInfo = Taro.getStorageSync('userInfo')
    if (userInfo && userInfo.phone_number) {
        console.log('User has phone number, attempting auto login...')
        login().then(res => {
           console.log('Auto login success, user:', res?.nickname)
        }).catch(err => {
           console.log('Auto login failed', err)
           // If login fails (e.g. user deleted on backend), clear storage
           if (err.statusCode === 404 || err.statusCode === 401) {
               Taro.removeStorageSync('userInfo')
               Taro.removeStorageSync('token')
           }
        })
    } else {
        console.log('No phone number found, skipping auto login')
    }
  })

  return children
}

export default App
