<template>
  <view class="welcome-container">
    <web-view
      v-if="currentScene !== 4"
      class="animation-webview"
      :src="webviewUrl"
      @message="handleMessage"
      @error="handleWebviewError"
    ></web-view>

    <!-- 场景5: 选择明星页面 -->
    <view v-if="currentScene === 4" class="role-overlay">
      <SelectRole :is-welcome="true" @confirm="onSelectRoleConfirm" />
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import SelectRole from '../profile/selectRole.vue';

const store = useStore();
const emit = defineEmits(['complete', 'skip']);

const webviewUrl = ref('');
const currentScene = ref(0);

const initHtmlUrl = () => {
  webviewUrl.value = '/static/welcome-animation-app.html';
};

const handleWebviewError = (e) => {
  console.error('[WelcomeAnimationWebview] error:', e);
};

// uni.postMessage 触发的 @message 事件
const handleMessage = (e) => {
  console.log('[WelcomeAnimationWebview] @message:', JSON.stringify(e.detail));
  const data = e.detail && e.detail.data;
  if (!data || !data.length) return;
  handleMessageData(data[0]);
};

const handleMessageData = (msg) => {
  if (!msg || !msg.action) return;
  console.log('[WelcomeAnimationWebview] action:', msg.action);
  if (msg.action === 'skip') {
    emit('skip');
  } else if (msg.action === 'complete') {
    emit('complete');
  } else if (msg.action === 'selectRole') {
    currentScene.value = 4;
  }
};

const onSelectRoleConfirm = async (star) => {
  try {
    const mobile = uni.getStorageSync('temp_register_mobile');
    const password = uni.getStorageSync('temp_register_password');
    const nickname = uni.getStorageSync('temp_register_nickname');
    const star_id = star.star_id;

    if (!mobile || !password || !nickname || !star_id) {
      uni.showToast({ title: '注册信息不完整', icon: 'none' });
      uni.navigateTo({ url: '/pages/register/register' });
      return;
    }

    uni.showLoading({ title: '注册中...', mask: true });
    await store.dispatch('user/register', { mobile, password, star_id, nickname });
    uni.hideLoading();
    uni.removeStorageSync('temp_register_mobile');
    uni.removeStorageSync('temp_register_password');
    uni.removeStorageSync('temp_register_nickname');

    // 切回 webview 显示场景6动画，通过 URL 参数指定起始场景
    webviewUrl.value = '/static/welcome-animation-app.html?scene=5';
    currentScene.value = 5;
    // 场景6播放3秒后结束
    setTimeout(() => {
      emit('complete');
    }, 3000);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ title: error.message || '注册失败', icon: 'none' });
  }
};

onMounted(() => {
  initHtmlUrl();

  // H5 端用 window.addEventListener 接收 postMessage
  // #ifdef H5
  window.addEventListener('message', (e) => {
    if (e.data && e.data.action) handleMessageData(e.data);
  });
  // #endif
});
</script>

<style scoped>
.welcome-container { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999; }
.animation-webview { width: 100%; height: 100%; }
.role-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: #fff; z-index: 100; }
</style>
