<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) {
    url.value = decodeURIComponent(options.url)
    console.log('Opening Game WebView:', url.value)
  } 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 === 'playAgain') {
      // 再来一局: 返回上一页，上一页会自动刷新重新获取token进入游戏
      console.log('PlayAgain: 返回游戏入口页面')
      uni.navigateBack({
        delta: 1,
        success: () => {
          // 可选: 发送事件通知上一页刷新
          uni.$emit('refreshGame')
        }
      })
    } else if (msg.action === 'game_over') {
      // Optional: Refresh user balance or state
    }
  })
}
</script>

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