<template>
  <view class="quiz-page">
    <view class="nav-bar" :style="navBarStyle">
      <view class="nav-left" @tap="handleBack">
        <text class="back-icon">‹</text>
      </view>
      <text class="nav-title">在线测评</text>
      <view class="nav-right"></view>
    </view>
    <view class="webview-container" :style="contentStyle">
      <web-view v-if="url" :src="url"></web-view>
    </view>
  </view>
</template>

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

const url = ref('')
const assessmentId = ref('')
const source = ref('')
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 20
const navBarHeight = 44
const navBarStyle = `padding-top:${statusBarHeight}px;height:${navBarHeight}px;`
const contentStyle = `margin-top:${statusBarHeight + navBarHeight}px;`

const handleBack = () => {
  if (source.value === 'kaoshixing' && assessmentId.value) {
    uni.redirectTo({
      url: `/pages/common/webview?mode=kaoshixing&assessmentId=${encodeURIComponent(assessmentId.value)}`
    })
    return true
  }
  uni.navigateBack()
  return true
}

onBackPress((options) => {
  return handleBack()
})

onLoad((options) => {
  assessmentId.value = options.assessmentId || ''
  source.value = options.from || ''

  if (options.from === 'report') {
    const cachedUrl = uni.getStorageSync('temp_report_url')
    if (cachedUrl) {
      url.value = cachedUrl
      uni.removeStorageSync('temp_report_url')
      return
    }
  }

  if (options.from === 'kaoshixing') {
    const cachedUrl = uni.getStorageSync('temp_exam_url')
    if (cachedUrl) {
      url.value = cachedUrl
      uni.removeStorageSync('temp_exam_url')
      return
    }
  }

  if (options.url) {
    url.value = decodeURIComponent(options.url)
    console.log('Quiz WebView Loading URL:', url.value)
  }
})
</script>

<style scoped>
.quiz-page {
  min-height: 100vh;
  background: #fff;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}

.nav-left,
.nav-right {
  width: 88rpx;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.back-icon {
  font-size: 52rpx;
  color: #111;
  line-height: 1;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #111;
  font-weight: 500;
}

.webview-container {
  height: calc(100vh - 44px);
}
</style>
