<template>
  <view></view>
</template>

<script setup>
import { ref } from "vue";
import { watchAdStart } from "@/api/system.js";
import adManager from "@/utils/adManager.js";

const props = defineProps({
  adUnitId: {
    type: String,
    default: "adunit-d7a28e0357d98947",
  },
});

const emit = defineEmits(["onReward", "onError", "onClose"]);

const show = async () => {
  try {
    // Step 1: Start Ad Session to get Token
    const res = await watchAdStart();
    if (res && res.rewardToken) {
      const rewardToken = res.rewardToken;
      
      // Step 2: Show Ad through global AdManager
      const success = await adManager.showVideoAd(props.adUnitId, rewardToken);
      
      if (success) {
        // 延迟 300ms 触发回调，避免和微信小程序的 onShow 页面恢复动画抢占底层渲染线程，导致 insertTextView:fail
        setTimeout(() => {
          emit("onReward", rewardToken);
        }, 300);
      } else {
        emit("onClose");
      }
    } else {
      uni.showToast({ title: "广告启动失败，请稍后再试", icon: "none" });
      emit("onError", new Error("watchAdStart failed"));
    }
  } catch (e) {
    console.error("RewardAd: show failed", e);
    uni.showToast({ title: "广告启动失败，请稍后再试", icon: "none" });
    emit("onError", e);
  }
};

defineExpose({ show });
</script>
