import React, { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import styles from './DedoNoCopo.module.css'

export default function DedoNoCopo() {
    const [touches, setTouches] = useState([])
    const [status, setStatus] = useState('waiting') // 'waiting', 'counting', 'result'
    const [winnerId, setWinnerId] = useState(null)
    const [progress, setProgress] = useState(0)
    const [autoStartTimer, setAutoStartTimer] = useState(null)
    const touchAreaRef = useRef(null)

    const handleTouch = (e) => {
        if (status === 'result') return
        updateTouches(e.targetTouches)
    }

    const updateTouches = (touchList) => {
        if (!touchAreaRef.current) return

        const rect = touchAreaRef.current.getBoundingClientRect()
        const newTouches = Array.from(touchList).map(t => ({
            id: t.identifier,
            x: t.clientX - rect.left,
            y: t.clientY - rect.top
        }))
        setTouches(newTouches)
    }

    // Gerenciador de Estados e Timers
    useEffect(() => {
        if (status === 'result') return

        // Se desistirem (menos de 2 dedos), reseta
        if (touches.length < 2) {
            if (status === 'counting') setStatus('waiting')
            setAutoStartTimer(null)
            setProgress(0)
            return
        }

        let interval = null

        if (status === 'waiting') {
            // Fase de Sincronização: 5 segundos
            // Sempre que o número de toques muda, o timer reinicia (devido à dependência [touches.length])
            setAutoStartTimer(5)
            let timeLeft = 5

            interval = setInterval(() => {
                timeLeft -= 1
                setAutoStartTimer(timeLeft)
                if (timeLeft <= 0) {
                    clearInterval(interval)
                    setStatus('counting')
                    setAutoStartTimer(null)
                }
            }, 1000)
        } else if (status === 'counting') {
            // Fase de Carga (Roleta): ~2.5 segundos
            setProgress(0)
            let p = 0
            interval = setInterval(() => {
                p += 2
                setProgress(p)
                if (p >= 100) {
                    clearInterval(interval)
                    finishGame()
                }
            }, 50)
        }

        return () => {
            if (interval) clearInterval(interval)
        }
    }, [touches.length, status])

    const finishGame = () => {
        setTouches(prev => {
            if (prev.length === 0) return prev
            const winner = prev[Math.floor(Math.random() * prev.length)]
            setWinnerId(winner.id)
            return prev
        })
        setStatus('result')
        if (navigator.vibrate) navigator.vibrate([100, 50, 200])
    }

    const resetGame = () => {
        setStatus('waiting')
        setWinnerId(null)
        setProgress(0)
        setTouches([])
        setAutoStartTimer(null)
    }

    return (
        <div className={styles.page}>
            <Link to="/jogos" className={styles.backLink} onClick={resetGame}>
                <i className="fas fa-arrow-left"></i> Voltar
            </Link>

            <div className={styles.titleWrapper}>
                <h1 className={styles.title}>Roleta de Toque</h1>
            </div>

            <div
                ref={touchAreaRef}
                className={styles.touchArea}
                onTouchStart={handleTouch}
                onTouchMove={handleTouch}
                onTouchEnd={handleTouch}
                // Para testes em Desktop (apenas 1 círculo simulado)
                onMouseDown={(e) => {
                    if (status === 'result' || !touchAreaRef.current) return
                    const rect = touchAreaRef.current.getBoundingClientRect()
                    setTouches([{ id: 'mouse', x: e.clientX - rect.left, y: e.clientY - rect.top }])
                }}
                onMouseUp={() => { if (status !== 'result') setTouches([]) }}
            >
                {touches.map(t => (
                    <div
                        key={t.id}
                        className={`
              ${styles.fingerCircle} 
              ${status === 'result' && t.id === winnerId ? styles.selected : ''}
              ${status === 'result' && t.id !== winnerId ? styles.eliminated : ''}
            `}
                        style={{ left: t.x, top: t.y }}
                    >
                        {(status === 'counting' || (status === 'result' && t.id === winnerId)) && (
                            <div
                                className={`${styles.loadingRing} ${status === 'result' ? styles.winnerRing : ''}`}
                                style={{
                                    background: status === 'result'
                                        ? '#efcd28'
                                        : `conic-gradient(#efcd28 ${progress}%, transparent ${progress}%)`
                                }}
                            />
                        )}
                    </div>
                ))}

                {status === 'waiting' && (
                    <div className={styles.instructions}>
                        {touches.length < 2 ? (
                            touches.length === 0 ? "COLOQUEM OS DEDOS NA TELA" : "FALTA MAIS ALGUÉM..."
                        ) : (
                            <div className={styles.timerAnnounce}>
                                SINCRONIZANDO... {autoStartTimer}s
                            </div>
                        )}
                    </div>
                )}

                {status === 'counting' && (
                    <div className={styles.instructions}>
                        NÃO TIREM OS DEDOS!
                    </div>
                )}

                {status === 'result' && (
                    <div className={styles.resultOverlay}>
                        <div className={styles.resultTitle}>ELEITO! 🍺</div>
                        <p>Quem parou no círculo dourado, bebe!</p>
                        <button className={styles.resultBtn} onClick={resetGame}>JOGAR NOVAMENTE</button>
                    </div>
                )}
            </div>
        </div>
    )
}
