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

export default function NewWordTextCard({ card, onComplete }) {
  const [input, setInput]   = useState('')
  const [status, setStatus] = useState('idle') // idle | correct | wrong
  const reportedRef = useRef(false)

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

  const check = () => {
    if (!input.trim()) return
    const correct = input.trim().toLowerCase() === card.word.toLowerCase()
    setStatus(correct ? 'correct' : 'wrong')
    if (correct) {
      triggerConfetti()
      report('correct')
    }
  }

  const reset = () => { setInput(''); 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={`nwt-input-row ${status === 'wrong' ? 'nwt-wrong' : ''}`}>
              <input
                className="nwt-input"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && check()}
                placeholder={`${card.word} …`}
                autoCorrect="off" autoCapitalize="none" spellCheck={false}
              />
              <button className="nwt-submit-btn" onClick={check} aria-label="Prüfen">
                <svg viewBox="0 0 20 20" width="16" height="16" fill="none"
                  stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="4,10 9,15 16,6" />
                </svg>
              </button>
            </div>
            {status === 'wrong' && (
              <p className="nwt-feedback nwt-wrong-text">Nicht ganz — versuch es nochmal.</p>
            )}
          </>
        ) : (
          <div className="nwt-success-bar">
            <span className="nwt-success-left">★ +{card.points} Punkt erhalten</span>
            <span className="nwt-success-right">Gesamt: {card.totalPoints} Punkte</span>
          </div>
        )}
      </div>
    </div>
  )
}
