import { ref } from 'vue'

import type { PaymentPayWay } from '@/features/orders/api/orders'

// useMobilePayWaySelect 提供移动端"选择支付方式"底部弹层的状态与 Promise 化选择逻辑。
// 与 MobilePayWaySelectPopup 配合：select() 打开弹层并返回用户所选渠道，关闭即视为取消。
export function useMobilePayWaySelect() {
  const visible = ref(false)
  let resolver: ((value: PaymentPayWay | null) => void) | null = null

  // select 打开弹层并返回 Promise，resolve 为所选渠道；取消则为 null。
  function select(): Promise<PaymentPayWay | null> {
    visible.value = true
    return new Promise(resolve => {
      resolver = resolve
    })
  }

  // choose 用户点选某渠道，关闭弹层并 resolve。
  function choose(payWay: PaymentPayWay) {
    resolver?.(payWay)
    resolver = null
    visible.value = false
  }

  // handleClosed 弹层关闭（含遮罩/返回）时若未选择则按取消处理。
  function handleClosed() {
    resolver?.(null)
    resolver = null
  }

  return { visible, select, choose, handleClosed }
}
