<template>
  <cwg-popup v-model:visible="visible" type="center" :mask-click="false" :show-footers="true">
    <view class="popup-content">
      <view class="confirm-title">{{ title }}</view>
      <view class="confirm-content">{{ content }}</view>
    </view>
    <template #footer>
      <button @click="handleCancel">{{ cancelText }}</button>
      <button type="primary" @click="handleConfirm">{{ confirmText }}</button>
    </template>
  </cwg-popup>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const visible = ref(false)
let currentEventId = null
let isShowing = false // 单例锁，永远只弹一个

const title = ref('')
const content = ref('')
const confirmText = ref('')
const cancelText = ref('')

// 显示弹窗
const handleShowConfirm = (options) => {
  if (isShowing || visible.value) return

  isShowing = true
  currentEventId = options.eventId

  title.value = options.title || t('Msg.SystemPrompt')
  content.value = options.content || ''
  confirmText.value = options.confirmText || t('Btn.Confirm')
  cancelText.value = options.cancelText || t('Btn.Cancel')

  visible.value = true
}

// 关闭并返回结果 + 强制清空所有状态
const close = (result) => {
  visible.value = false
  isShowing = false

  if (currentEventId) {
    uni.$emit(`confirmResult_${currentEventId}`, result)
  }

  // 🔥 强制清空，永不残留
  currentEventId = null
  title.value = ''
  content.value = ''
  confirmText.value = ''
  cancelText.value = ''
}

const handleConfirm = () => close(true)
const handleCancel = () => close(false)

onMounted(() => {
  uni.$on('showConfirm', handleShowConfirm)
})

onUnmounted(() => {
  uni.$off('showConfirm', handleShowConfirm)
  visible.value = false
  isShowing = false
  currentEventId = null
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";
:deep(.cwg-dialog) {
  width: px2rpx(500);
  background-color: #fff;
  border-radius: px2rpx(16);
  text-align: center;
  box-shadow: 0 px2rpx(10) px2rpx(20) rgba(0, 0, 0, 0.1);
}
.confirm-title {
  font-size: px2rpx(24);
  font-weight: 600;
  color: #333;
  margin-bottom: px2rpx(30);
}
.confirm-content {
  font-size: px2rpx(20);
  color: #666;
  margin-bottom: px2rpx(30);
  line-height: 1.5;
  word-break: break-word;
}
</style>