import { useEffect, useState } from "preact/hooks";
import tick from '../assets/tick.ogg';
import beep from '../assets/beep.ogg';

const LETTERS = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЭЮЯ'.split('');

export const App = () => {
    const [init, setInit] = useState(false);
    const [usedLetters, setUsedLetters] = useState<string[]>([]);
    const [isOver, setOver] = useState(false);

    useEffect(() => {
        let timeout = 0;

        if (usedLetters.length) {
            tick.pause();
            tick.currentTime = 0;
            tick.loop = true;
            tick.play();

            timeout = window.setTimeout(() => {
                tick.pause();
                beep.play();
                setOver(true);
                window.clearTimeout(timeout);
            }, 10_000);
        }

        return () => {
            window.clearTimeout(timeout);
        };
    }, [usedLetters]);

    if (!init) {
        return <button onClick={() => setInit(true)}>▶</button>;
    }

    return <>
        <main>
            {LETTERS.map(l => (
                <button
                    key={l}
                    disabled={isOver || usedLetters.includes(l)}
                    onMouseDown={() => setUsedLetters(b => [...b, l])}
                    onTouchStart={() => setUsedLetters(b => [...b, l])}
                >
                    {l}
                </button>
            ))}
        </main>
    </>;
};
