<template>
  <view v-if="visible" class="toast-wrap">
    <view class="toast-content">
      <text v-if="icon === 'success'" class="toast-icon"></text>
      <text v-else-if="icon === 'error'" class="toast-icon"></text>
      <text v-else-if="icon === 'loading'" class="toast-icon loading"></text>
      <text class="toast-text">{{ title }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { watch } from 'vue'

const props = withDefaults(
  defineProps<{
    visible: boolean
    title: string
    icon?: 'success' | 'loading' | 'none' | 'error'
    duration?: number
  }>(),
  {
    icon: 'none',
    duration: 2000
  }
)

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

let timer: ReturnType<typeof setTimeout> | null = null

watch(
  () => props.visible,
  (val) => {
    if (timer) clearTimeout(timer)
    if (val && props.duration > 0) {
      timer = setTimeout(() => {
        emit('update:visible', false)
        emit('close')
      }, props.duration)
    }
  }
)
</script>

<style scoped>
.toast-wrap {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  pointer-events: none;
}

.toast-content {
  min-width: 120px;
  max-width: 70%;
  padding: 16px 24px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.toast-icon {
  font-size: 24px;
  color: #fff;
  margin-bottom: 8px;
}

.toast-icon.loading {
  animation: spin 1s linear infinite;
}

.toast-text {
  font-size: 14px;
  color: #fff;
  text-align: center;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
