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

function shuffle(arr) {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

function SofaIllustration() {
  return (
    <svg viewBox="0 0 200 140" width="190" height="133" aria-hidden="true">
      <rect x="16" y="46" width="14" height="50" rx="6" fill="rgba(74,55,40,0.16)"/>
      <rect x="170" y="46" width="14" height="50" rx="6" fill="rgba(74,55,40,0.16)"/>
      <rect x="22" y="36" width="156" height="22" rx="8" fill="rgba(74,55,40,0.14)"/>
      <rect x="22" y="54" width="156" height="38" rx="10" fill="rgba(74,55,40,0.18)"/>
      <rect x="32" y="56" width="64" height="32" rx="8" fill="rgba(74,55,40,0.11)"/>
      <rect x="104" y="56" width="64" height="32" rx="8" fill="rgba(74,55,40,0.11)"/>
      <rect x="30" y="92" width="10" height="22" rx="3" fill="rgba(74,55,40,0.13)"/>
      <rect x="160" y="92" width="10" height="22" rx="3" fill="rgba(74,55,40,0.13)"/>
    </svg>
  )
}

export default function LetterOrderCard({ card, onComplete }) {
  const scrambled = useMemo(() => shuffle(card.word.split('')), [card.word])
  const [placed, setPlaced]       = useState([])
  const [available, setAvailable] = useState(scrambled)
  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 placeLetter = (idx) => {
    if (status === 'correct') return
    const letter = available[idx]
    const newPlaced    = [...placed, letter]
    const newAvailable = available.filter((_, i) => i !== idx)

    if (newPlaced.length === card.word.length) {
      const correct = newPlaced.join('') === card.word
      setPlaced(newPlaced)
      setAvailable(newAvailable)
      setStatus(correct ? 'correct' : 'wrong')
      if (correct) { triggerConfetti(); report('correct') }
    } else {
      setPlaced(newPlaced)
      setAvailable(newAvailable)
    }
  }

  const removeLast = () => {
    if (placed.length === 0) return
    const letter = placed[placed.length - 1]
    setPlaced(placed.slice(0, -1))
    setAvailable([...available, letter])
    setStatus('idle')
  }

  const reset = () => {
    setPlaced([])
    setAvailable(scrambled)
    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">
        <SofaIllustration />
      </div>

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

        <div className={`lo-answer-area${status === 'correct' ? ' lo-answer-correct' : status === 'wrong' ? ' lo-answer-wrong' : ''}`}>
          {placed.map((letter, i) => (
            <span key={i} className="lo-chip lo-chip-placed">{letter}</span>
          ))}
        </div>

        <div className="nw-divider" />

        {status === 'correct' ? (
          <>
            <p className="lo-success-text">Perfekt! Bra jobbat!</p>
            <div className="lo-success-bar">
              <span className="lo-success-left">★ +{card.points} Punkt erhalten</span>
              <span className="lo-success-right">Gesamt: {card.totalPoints} Punkte</span>
            </div>
          </>
        ) : (
          <>
            <div className="lo-available">
              {available.map((letter, i) => (
                <button key={i} className="lo-chip lo-chip-available" onClick={() => placeLetter(i)}>
                  {letter}
                </button>
              ))}
            </div>
            {status === 'wrong' && (
              <p className="lo-wrong-text">Nicht ganz — versuch es nochmal.</p>
            )}
            <button
              className={`lo-back-btn${placed.length === 0 ? ' lo-back-disabled' : ''}`}
              onClick={status === 'wrong' ? reset : removeLast}
              disabled={placed.length === 0 && status === 'idle'}
            >
              {status === 'wrong' ? 'Nochmal' : '← Zurück'}
            </button>
          </>
        )}
      </div>
    </div>
  )
}
