import { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore } from '../store'
import Tooltip from './ui/Tooltip'

export default function ActiveClue() {
  const { t } = useTranslation()
  const puzzle = useStore((s) => s.puzzle)
  const activeClue = useStore((s) => s.activeClue)
  const direction = useStore((s) => s.direction)
  const toggleDirection = useStore((s) => s.toggleDirection)
  const [display, setDisplay] = useState<{ dir: string; text: string; num: number | null }>({
    dir: '', text: '', num: null,
  })
  const [animating, setAnimating] = useState(false)
  const prevKey = useRef('')

  useEffect(() => {
    if (!puzzle || !activeClue) {
      if (display.num !== null) {
        queueMicrotask(() => setAnimating(true))
        setTimeout(() => {
          setDisplay({ dir: '', text: '', num: null })
          setAnimating(false)
        }, 150)
      }
      return
    }

    const clues = direction === 'across' ? puzzle.clues_across : puzzle.clues_down
    const clue = clues.find((c) => c.number === activeClue)
    if (!clue) return

    const key = `${activeClue}-${direction}`
    if (key === prevKey.current) return
    prevKey.current = key

    queueMicrotask(() => setAnimating(true))
    setTimeout(() => {
      setDisplay({ dir: `${activeClue} ${direction}`, text: clue.text, num: activeClue })
      setAnimating(false)
    }, 150)
  }, [puzzle, activeClue, direction])

  if (!puzzle) return null

  return (
    <Tooltip text={t('game.clickToSwitchDirection')}>
    <button
      type="button"
      className="active-clue-banner"
      onClick={toggleDirection}
    >
      <div
        className="clue-direction"
        style={{
          opacity: animating ? 0 : 1,
          transform: animating ? 'translateY(-4px)' : 'translateY(0)',
          transition: 'all 150ms ease',
        }}
      >
        {display.dir || '\u00A0'}
      </div>
      <div
        className="clue-text"
        style={{
          opacity: animating ? 0 : 1,
          transform: animating ? 'translateY(4px)' : 'translateY(0)',
          transition: 'all 150ms ease',
        }}
      >
        {display.text || t('game.selectCellToBegin')}
      </div>
    </button>
    </Tooltip>
  )
}
