import { useEffect, useState } from 'react'

interface ConversionPair {
  rub: string
  usdt: string
}

const PAIRS: ConversionPair[] = [
  { rub: '10 000 ₽', usdt: '≈ 125.3 USDT' },
  { rub: '25 000 ₽', usdt: '≈ 313.3 USDT' },
  { rub: '50 000 ₽', usdt: '≈ 626.5 USDT' },
  { rub: '100 000 ₽', usdt: '≈ 1 253.1 USDT' },
]

const ERASE_MS = 40
const TYPE_MS = 75
const PAUSE_MS = 3500
const TRANSFER_MS = 900

export type ActiveField = 'rub' | 'usdt' | null

export function useConversionCycle() {
  const [rub, setRub] = useState(PAIRS[0].rub)
  const [usdt, setUsdt] = useState(PAIRS[0].usdt)
  const [active, setActive] = useState<ActiveField>(null)
  const [settled, setSettled] = useState(true)

  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return

    let alive = true
    const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))

    const erase = async (text: string, set: (s: string) => void) => {
      for (let n = text.length - 1; n >= 0 && alive; n--) {
        set(text.slice(0, n))
        await sleep(ERASE_MS)
      }
    }

    const type = async (text: string, set: (s: string) => void) => {
      for (let n = 1; n <= text.length && alive; n++) {
        set(text.slice(0, n))
        await sleep(TYPE_MS)
      }
    }

    const run = async () => {
      let i = 0
      while (alive) {
        await sleep(PAUSE_MS)
        if (!alive) return
        const cur = PAIRS[i % PAIRS.length]
        const next = PAIRS[(i + 1) % PAIRS.length]

        setSettled(false)
        setActive('rub')
        await erase(cur.rub, setRub)
        await type(next.rub, setRub)

        // пауза — «средства идут» по траектории к USDT
        setActive(null)
        await sleep(TRANSFER_MS)
        if (!alive) return

        setActive('usdt')
        await erase(cur.usdt, setUsdt)
        await type(next.usdt, setUsdt)

        setActive(null)
        setSettled(true)
        i++
      }
    }

    run()
    return () => {
      alive = false
    }
  }, [])

  return { rub, usdt, active, settled }
}
