import { createApp, nextTick } from 'vue'
import MessagePopup from './index.vue'

const message = {
  success(text, duration = 2000) {
    if (process.client) {
      this.show({ type: 'success', message: text, duration })
    }
  },
  error(text, duration = 2000) {
    if (process.client) {
      this.show({ type: 'error', message: text, duration })
    }
  },
  warning(text, duration = 2000) {
    if (process.client) {
      this.show({ type: 'warning', message: text, duration })
    }
  },
  show({ type = 'success', message, duration = 2000 }) {
    if (!process.client) return
    
    const container = document.createElement('div')
    document.body.appendChild(container)
    
    const app = createApp(MessagePopup, {
      onAfterLeave: () => {
        app.unmount()
        document.body.removeChild(container)
      }
    })
    
    const instance = app.mount(container)
    nextTick(() => {
      instance.showMessage?.({
        type,
        message,
        duration
      })
    })
  }
}

export { message }