(() => {
    const root = document.getElementById('listenRepeatPlayer');
    if (!root) return;

    const cards = JSON.parse(root.dataset.cards || '[]');
    let currentIndex = 0;
    let answerVisible = false;
    let currentAudio = null;

    const image = document.getElementById('lrImage');
    const imageButton = document.getElementById('lrImageButton');
    const answer = document.getElementById('lrAnswer');
    const word = document.getElementById('lrWord');
    const ipa = document.getElementById('lrIpa');
    const meaning = document.getElementById('lrMeaning');
    const listenButton = document.getElementById('lrListenButton');
    const showButton = document.getElementById('lrShowButton');
    const previousButton = document.getElementById('lrPreviousButton');
    const nextButton = document.getElementById('lrNextButton');
    const progressLabel = document.getElementById('lrProgressLabel');
    const progressBar = document.getElementById('lrProgressBar');

    function currentCard() {
        return cards[currentIndex];
    }

    function render() {
        const card = currentCard();
        answerVisible = false;
        answer.hidden = true;
        showButton.textContent = 'Show Answer';

        word.textContent = card.word;
        ipa.textContent = card.ipa || '';
        meaning.textContent = card.meaning || 'Chưa có nghĩa tiếng Việt.';

        if (card.image) {
            image.src = card.image;
            image.alt = '';
            image.hidden = false;
            image.onerror = () => {
                image.hidden = true;
            };
        } else {
            image.removeAttribute('src');
            image.hidden = true;
        }

        progressLabel.textContent = `${currentIndex + 1} / ${cards.length}`;
        progressBar.style.width = `${((currentIndex + 1) / cards.length) * 100}%`;
        previousButton.disabled = currentIndex === 0;
        nextButton.disabled = currentIndex === cards.length - 1;
    }

    function browserSpeech(text) {
        if (!('speechSynthesis' in window)) return;
        speechSynthesis.cancel();
        const utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = 'en-US';
        utterance.rate = 0.78;
        speechSynthesis.speak(utterance);
    }

    function listen() {
        const card = currentCard();

        if (currentAudio) {
            currentAudio.pause();
            currentAudio = null;
        }

        if ('speechSynthesis' in window) {
            speechSynthesis.cancel();
        }

        if (card.audio) {
            currentAudio = new Audio(card.audio);
            currentAudio.play().catch(() => browserSpeech(card.word));
        } else {
            browserSpeech(card.word);
        }
    }

    function toggleAnswer() {
        answerVisible = !answerVisible;
        answer.hidden = !answerVisible;
        showButton.textContent = answerVisible ? 'Hide Answer' : 'Show Answer';
    }

    function move(direction) {
        const next = currentIndex + direction;
        if (next < 0 || next >= cards.length) return;
        currentIndex = next;
        render();
    }

    imageButton.addEventListener('click', listen);
    listenButton.addEventListener('click', listen);
    showButton.addEventListener('click', toggleAnswer);
    previousButton.addEventListener('click', () => move(-1));
    nextButton.addEventListener('click', () => move(1));

    document.addEventListener('keydown', event => {
        if (event.key === 'ArrowLeft') move(-1);
        if (event.key === 'ArrowRight') move(1);
        if (event.code === 'Space') {
            event.preventDefault();
            listen();
        }
        if (event.key.toLowerCase() === 'a') toggleAnswer();
    });

    render();
})();
