<template>
  <cwg-popup v-model:visible="popupState.visible" type="center" :mask-click="false" :show-footers="showFooters" width="400px">
    <view class="popup-content">
      <view class="confirm-title">{{ popupState.title }}</view>
      <view class="confirm-content">{{ popupState.content }}</view>
    </view>
    <template #footer>
      <button v-if="popupState.showCancel && !popupState.autoClose" @click="close">{{ popupState.cancelText }}</button>
      <button v-if="!popupState.autoClose" class="btn btn-secondary btn-shadow waves-effect" @click="handleConfirm">{{ popupState.confirmText }}</button>
    </template>
  </cwg-popup>
</template>

<script setup>
import { watch, ref, computed, onUnmounted } from 'vue'
import { usePopup } from '@/hooks/usePopup'

const { popupState, close, handleConfirm } = usePopup()

const popupRef = ref(null)
let autoCloseTimer = null

const showFooters = computed(() => !popupState.value.autoClose)

watch(() => popupState.value.visible, (val) => {
    if (val) {
        popupRef.value?.open()
        if (popupState.value.autoClose) {
            autoCloseTimer = setTimeout(() => {
                close()
            }, popupState.value.autoCloseDelay)
        }
    } else {
        popupRef.value?.close()
        if (autoCloseTimer) {
            clearTimeout(autoCloseTimer)
            autoCloseTimer = null
        }
    }
}, { immediate: true })

onUnmounted(() => {
    if (autoCloseTimer) {
        clearTimeout(autoCloseTimer)
    }
})
</script>

<style scoped lang="scss">
  @import "@/uni.scss";

  :deep(.cwg-dialog) {
    width: px2rpx(500);
    background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
    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: var(--bs-heading-color);
    margin-bottom: px2rpx(30);
  }

  .confirm-content {
    font-size: px2rpx(20);
    color: var(--bs-heading-color);
    margin-bottom: px2rpx(30);
    line-height: 1.5;
    word-break: break-word;
  }
</style>
