import { reactive } from 'vue'

// 앱 공용 인앱 다이얼로그 상태(싱글턴). 네이티브 alert/confirm/prompt 대체.
// PC(Electron)에서 제목이 'sb_pt'로 뜨던 문제 + 웹/APK 일관 UI 제공.
const state = reactive({
  open: false,
  type: 'alert', // 'alert' | 'confirm' | 'prompt'
  title: '',
  message: '',
  okText: '확인',
  cancelText: '취소',
  danger: false,
  inputValue: '',
  placeholder: '',
  _resolve: null,
})

function settle(result) {
  const r = state._resolve
  state._resolve = null
  state.open = false
  if (r) r(result)
}

function alert(message, { title = '알림', okText = '확인' } = {}) {
  return new Promise((resolve) => {
    Object.assign(state, { type: 'alert', title, message, okText, danger: false, _resolve: resolve, open: true })
  })
}

function confirm(message, { title = '확인', okText = '확인', cancelText = '취소', danger = false } = {}) {
  return new Promise((resolve) => {
    Object.assign(state, { type: 'confirm', title, message, okText, cancelText, danger, _resolve: resolve, open: true })
  })
}

function prompt(message, { title = '입력', okText = '확인', cancelText = '취소', defaultValue = '', placeholder = '' } = {}) {
  return new Promise((resolve) => {
    Object.assign(state, {
      type: 'prompt', title, message, okText, cancelText,
      inputValue: defaultValue, placeholder, danger: false, _resolve: resolve, open: true,
    })
  })
}

// AppDialog 컴포넌트에서 사용
export const dialogState = state
export function dialogConfirm() {
  settle(state.type === 'prompt' ? state.inputValue : true)
}
export function dialogCancel() {
  settle(state.type === 'prompt' ? null : false)
}

export function useDialog() {
  return { alert, confirm, prompt }
}
