import { useState, useRef } from 'react'
import './CardShared.css'
import './NewWordVoiceCard.css'
import TableIllustration from './TableIllustration'
import { triggerConfetti } from '../utils/confetti'

export default function NewWordVoiceCard({ card, onComplete }) {
  const [status, setStatus] = useState('idle') // idle | listening | correct | wrong
  const recognitionRef = useRef(null)
  const reportedRef = useRef(false)

  const report = (result) => {
    if (reportedRef.current) return
    reportedRef.current = true
    onComplete?.(result)
  }

  const startListening = () => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition
    if (!SR) {
      // Simulate for browsers without speech API
      setStatus('listening')
      setTimeout(() => { setStatus('correct'); triggerConfetti(); report('correct') }, 2000)
      return
    }

    const rec = new SR()
    rec.lang = card.speechLang || 'sv-SE'
    rec.interimResults = false
    rec.maxAlternatives = 3
    recognitionRef.current = rec

    setStatus('listening')

    rec.onresult = (e) => {
      const heard = Array.from(e.results[0])
        .map((r) => r.transcript.trim().toLowerCase())
      const target = card.word.toLowerCase()
      const correct = heard.some((h) => h === target || h.includes(target))
      setStatus(correct ? 'correct' : 'wrong')
      if (correct) { triggerConfetti(); report('correct') }
    }

    rec.onerror = () => setStatus('wrong')
    rec.onend   = () => { if (status === 'listening') setStatus('wrong') }
    rec.start()
  }

  const reset = () => {
    recognitionRef.current?.abort()
    setStatus('idle')
  }

  return (
    <div className="nw-card">
      <div className="nw-card-header">
        <span className="nw-lang-pill">{card.language}</span>
        <span className="nw-points-pill">★ +{card.points} Punkt</span>
      </div>
      <div className="nw-image">
        <div className="nw-bubble">{card.baseForm}</div>
        <TableIllustration />
      </div>

      <div className="nw-content">
        <div className="nw-word-row">
          <span className="nw-word">{card.word}</span>
          <span className="nw-translation">{card.translation}</span>
        </div>
        <div className="nw-divider" />

        {status !== 'correct' ? (
          <>
            <label className="nw-label">{card.prompt}</label>
            <div className="nwv-mic-row">
              <button
                className={`nwv-mic-btn ${status === 'listening' ? 'nwv-listening' : ''} ${status === 'wrong' ? 'nwv-wrong' : ''}`}
                onClick={status === 'listening' ? reset : startListening}
                aria-label="Sprechen"
              >
                {status === 'listening' ? (
                  <span className="nwv-pulse-ring" />
                ) : null}
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none"
                  stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="9" y="2" width="6" height="11" rx="3" />
                  <path d="M5 10a7 7 0 0 0 14 0" />
                  <line x1="12" y1="19" x2="12" y2="22" />
                  <line x1="8" y1="22" x2="16" y2="22" />
                </svg>
              </button>

              {status === 'listening' && (
                <p className="nwv-hint">Hören …</p>
              )}
              {status === 'wrong' && (
                <p className="nwv-feedback nwv-wrong-text">Nicht erkannt — versuch es nochmal.</p>
              )}
              {status === 'correct' && (
                <p className="nwv-feedback nwv-correct-text">Bra! Aussprache erkannt.</p>
              )}
            </div>
          </>
        ) : (
          <>
            <label className="nw-label">{card.prompt}</label>
            <div className="nwv-mic-row">
              <button className="nwv-mic-btn nwv-done" aria-label="Fertig">
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none"
                  stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="9" y="2" width="6" height="11" rx="3" />
                  <path d="M5 10a7 7 0 0 0 14 0" />
                  <line x1="12" y1="19" x2="12" y2="22" />
                  <line x1="8" y1="22" x2="16" y2="22" />
                </svg>
              </button>
              <p className="nwv-feedback nwv-correct-text">Bra! Aussprache erkannt.</p>
            </div>
            <div className="nwv-success-bar">
              <span className="nwv-success-left">★ +{card.points} Punkt erhalten</span>
              <span className="nwv-success-right">Gesamt: {card.totalPoints} Punkte</span>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
