import { ref, watch, onUnmounted, type MaybeRefOrGetter, toValue } from 'vue'
import { useSpotWs, spotWsSlug } from '@/composables/useSpotWs'

/**
 * 现货 WS 交易对 slug：币 + USDT 全小写，如 IBIT → ibitusdt
 */
export function toSpotPairSlug(coinUnit: string): string {
  const u = coinUnit.trim().toUpperCase()
  if (!u) return ''
  if (u === 'USDT') return 'usdt'
  return spotWsSlug(`${u}USDT`)
}

/** market_{pair}_trade_ticker，如 market_ibitusdt_trade_ticker */
export function spotTradeTickerChannel(coinUnit: string): string {
  const slug = toSpotPairSlug(coinUnit)
  if (!slug) return ''
  return `market_${slug}_trade_ticker`
}

/**
 * 订阅现货 WS（/ws/spot）单交易对 trade_ticker，用于 IDO 页 USDT 折算。
 */
export function useLiveCoinUsdtPrice(coinUnit: MaybeRefOrGetter<string>) {
  const livePrice = ref(0)

  const ws = useSpotWs(
    {
      onTicker: (t) => {
        if (t.last > 0) {
          livePrice.value = t.last
        }
      },
      onTrade: (t) => {
        if (t.price > 0) {
          livePrice.value = t.price
        }
      },
    },
    { tradeTickerOnly: true },
  )

  function connect(unit: string) {
    const u = unit.trim().toUpperCase()
    if (!u) {
      livePrice.value = 0
      ws.disconnect()
      return
    }
    if (u === 'USDT') {
      livePrice.value = 1
      ws.disconnect()
      return
    }
    ws.connect(`${u}USDT`)
  }

  watch(
    () => toValue(coinUnit),
    (unit) => {
      connect(unit)
    },
    { immediate: true },
  )

  onUnmounted(() => {
    ws.disconnect()
  })

  return {
    livePrice,
    refresh: () => connect(toValue(coinUnit)),
    disconnect: () => ws.disconnect(),
  }
}
