import { useMemo, useState } from 'react'
import { phonemeDeck, defaultPhoneme } from '../data/phonemes'

const vowels = ['a', 'e', 'i', 'o', 'u']

export function PhonicsPlay() {
  const [selectedPhoneme, setSelectedPhoneme] = useState(defaultPhoneme)
  const [activeVowel, setActiveVowel] = useState('a')
  const [track, setTrack] = useState<string[]>([])
  const [challenge, setChallenge] = useState<string | null>(null)

  const syllable = useMemo(() => {
    if (!selectedPhoneme) return ''
    return `${selectedPhoneme.fonema}${activeVowel}`
  }, [selectedPhoneme, activeVowel])

  const addToTrack = () => {
    if (!syllable) return
    setTrack((prev) => [syllable, ...prev].slice(0, 8))
  }

  const spinChallenge = () => {
    const randomPhoneme = phonemeDeck[Math.floor(Math.random() * phonemeDeck.length)]
    const randomVowel = vowels[Math.floor(Math.random() * vowels.length)]
    setSelectedPhoneme(randomPhoneme)
    setActiveVowel(randomVowel)
    setChallenge(`${randomPhoneme.fonema}${randomVowel}`)
  }

  if (!selectedPhoneme) return null

  return (
    <section className="phonics-grid">
      <div className="phoneme-scroll">
        {phonemeDeck.map((card) => (
          <button
            key={card.fonema}
            className={`phoneme-button ${
              card.fonema === selectedPhoneme.fonema ? 'active' : ''
            }`}
            onClick={() => {
              setSelectedPhoneme(card)
              setChallenge(null)
            }}
          >
            <span style={{ fontSize: '1.5rem' }}>{card.fonema}</span>
            <small>{card.grafemas.join(', ')}</small>
          </button>
        ))}
      </div>

      <div className="phoneme-detail">
        <h3>Fonema /{selectedPhoneme.fonema}/</h3>
        <p>
          <strong>Gesto Montessori:</strong> {selectedPhoneme.gestoMontessori}
        </p>
        <p>
          <strong>Palabras clave:</strong> {selectedPhoneme.palabrasClave.join(', ')}
        </p>
        <p>{selectedPhoneme.actividad}</p>
      </div>

      <div className="syllable-lab">
        <div>
          <p>Elige una vocal para combinar</p>
          <div className="vowel-row">
            {vowels.map((vowel) => (
              <button
                key={vowel}
                className={`vowel-button ${activeVowel === vowel ? 'active' : ''}`}
                onClick={() => setActiveVowel(vowel)}
              >
                {vowel.toUpperCase()}
              </button>
            ))}
          </div>
        </div>
        <div className="syllable-display">{syllable}</div>
        <div className="controls-row">
          <button className="control-button primary" onClick={addToTrack}>
            Agregar al circuito
          </button>
          <button className="control-button" onClick={spinChallenge}>
            Reto relámpago ⚡
          </button>
        </div>
        {challenge && (
          <p>
            Busca <strong>{challenge}</strong> en los cuentos o arma la ficha correcta para avanzar.
          </p>
        )}
        <div>
          <p style={{ margin: '0.5rem 0' }}>Trayecto practicado</p>
          <div className="track">
            {track.length === 0 && <span>Agrega sílabas para verlas aquí.</span>}
            {track.map((item, index) => (
              <span key={`${item}-${index}`} className="track-item">
                {item}
              </span>
            ))}
          </div>
        </div>
      </div>
    </section>
  )
}
