<template>
  <view v-if="visible" class="modal-wrap">
    <view class="modal-mask" @click="onMaskClick"></view>
    <view class="modal-content bg-white rounded-card p-4 mx-6">
      <text v-if="title" class="modal-title text-lg font-semibold text-gray-800 text-center mb-3">{{ title }}</text>
      <view class="modal-body text-sm text-gray-600 text-center mb-5">
        <slot name="content">
          <text>{{ content }}</text>
        </slot>
      </view>
      <view class="modal-footer flex gap-3">
        <button
          v-if="showCancel"
          class="flex-1 py-2 rounded-button border border-gray-200 text-gray-600 text-sm font-medium clickable"
          @click="onCancel"
        >
          {{ cancelText }}
        </button>
        <button
          class="flex-1 py-2 rounded-button bg-primary text-white text-sm font-medium clickable"
          @click="onConfirm"
        >
          {{ confirmText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    visible: boolean
    title?: string
    content?: string
    showCancel?: boolean
    cancelText?: string
    confirmText?: string
    closeOnMask?: boolean
  }>(),
  {
    title: '',
    content: '',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    closeOnMask: false
  }
)

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'confirm'): void
  (e: 'cancel'): void
}>()

function onMaskClick() {
  if (props.closeOnMask) {
    emit('update:visible', false)
    emit('cancel')
  }
}

function onCancel() {
  emit('update:visible', false)
  emit('cancel')
}

function onConfirm() {
  emit('update:visible', false)
  emit('confirm')
}
</script>

<style scoped>
.modal-wrap {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 100%;
  max-width: 320px;
  z-index: 1;
}

.modal-title {
  display: block;
}

.modal-body {
  display: block;
}
</style>
