<template>
  <view class="container">
    <web-view :src="url" @message="onMessage"></web-view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const url = ref('')

onLoad((options) => {
  if (options.url) {
    let targetUrl = decodeURIComponent(options.url)
    
    // Append auth info if not present
    const token = uni.getStorageSync('token')
    const uid = uni.getStorageSync('user_id')
    
    const hasQuery = targetUrl.includes('?')
    const separator = hasQuery ? '&' : '?'
    
    // Append standard auth params for the game to consume
    if (token) targetUrl += `${separator}token=${encodeURIComponent(token)}`
    if (uid) targetUrl += `&uid=${encodeURIComponent(uid)}`
    // Append ticket if provided
    if (options.ticket) targetUrl += `&ticket=${encodeURIComponent(options.ticket)}`
    
    console.log('Opening Game WebView:', targetUrl)
    url.value = targetUrl
  } else {
    uni.showToast({ title: '游戏地址无效', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})

function onMessage(e) {
  console.log('Message from Game:', e.detail)
  const data = e.detail.data || []
  
  // Handle specific messages
  data.forEach(msg => {
    if (msg.action === 'close') {
      uni.navigateBack()
    } else if (msg.action === 'game_over') {
      // Optional: Refresh user balance or state
    }
  })
}
</script>

<style>
.container {
  width: 100%;
  height: 100vh;
}
</style>
