<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * File: games/flashcards/player.php
 *
 * Activity -> Flashcard Set -> Flashcard Set Words -> Word Library
 *
 * Supported URL:
 * /EnglishSpeak/games/flashcards/player.php?activity_id=15
 * /EnglishSpeak/games/flashcards/player.php?activity=15
 */

require_once dirname(__DIR__, 3) . '/config/database.php';

$pdo = getDbConnection();

$activityId = max(
    0,
    (int)($_GET['activity_id'] ?? ($_GET['activity'] ?? 0))
);

if ($activityId <= 0) {
    http_response_code(400);
    exit('Invalid Activity ID.');
}

/**
 * @return array<string,array<string,mixed>>
 */
function flashPlayerColumns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    if ((int)$stmt->fetchColumn() === 0) {
        return [];
    }

    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

function flashPlayerUrl(string $path): string
{
    if ($path === '') {
        return '';
    }

    if (function_exists('es_url')) {
        return es_url($path);
    }

    if (preg_match('#^https?://#i', $path) === 1) {
        return $path;
    }

    return '/EnglishSpeak/' . ltrim($path, '/');
}

$activityColumns = flashPlayerColumns($pdo, 'activities');
$setColumns = flashPlayerColumns($pdo, 'flashcard_sets');
$relationColumns = flashPlayerColumns($pdo, 'flashcard_set_words');
$wordColumns = flashPlayerColumns($pdo, 'words');

if (
    $activityColumns === []
    || $setColumns === []
    || $relationColumns === []
    || $wordColumns === []
) {
    http_response_code(500);
    exit('Required Flashcard tables are missing.');
}

if (!isset($activityColumns['flashcard_set_id'])) {
    http_response_code(500);
    exit('activities.flashcard_set_id is missing.');
}

$activityTitleColumn = isset($activityColumns['title'])
    ? 'title'
    : (isset($activityColumns['name']) ? 'name' : null);

$activityTypeColumn = isset($activityColumns['activity_type'])
    ? 'activity_type'
    : (isset($activityColumns['type']) ? 'type' : null);

$setTitleColumn = isset($setColumns['title'])
    ? 'title'
    : (isset($setColumns['name']) ? 'name' : null);

$setDescriptionColumn = isset($setColumns['description'])
    ? 'description'
    : null;

$setFk = isset($relationColumns['set_id'])
    ? 'set_id'
    : (isset($relationColumns['flashcard_set_id']) ? 'flashcard_set_id' : null);

$wordFk = isset($relationColumns['word_id'])
    ? 'word_id'
    : null;

$orderColumn = isset($relationColumns['order_no'])
    ? 'order_no'
    : (isset($relationColumns['sort_order']) ? 'sort_order' : 'id');

$wordTextColumn = isset($wordColumns['word'])
    ? 'word'
    : (isset($wordColumns['term']) ? 'term' : null);

$meaningColumn = isset($wordColumns['meaning_vi'])
    ? 'meaning_vi'
    : (isset($wordColumns['meaning']) ? 'meaning' : null);

$ipaColumn = isset($wordColumns['phonetic'])
    ? 'phonetic'
    : (isset($wordColumns['ipa']) ? 'ipa' : null);

$imageColumn = isset($wordColumns['image_path'])
    ? 'image_path'
    : (isset($wordColumns['image']) ? 'image' : null);

$audioColumn = isset($wordColumns['audio_us_path'])
    ? 'audio_us_path'
    : (isset($wordColumns['audio_path']) ? 'audio_path' : null);

if (
    $activityTitleColumn === null
    || $setTitleColumn === null
    || $setFk === null
    || $wordFk === null
    || $wordTextColumn === null
) {
    http_response_code(500);
    exit('Flashcard schema is incomplete.');
}

$activityTypeSelect = $activityTypeColumn !== null
    ? "a.`{$activityTypeColumn}` AS activity_type"
    : "'flashcards' AS activity_type";

$setDescriptionSelect = $setDescriptionColumn !== null
    ? "fs.`{$setDescriptionColumn}` AS set_description"
    : "'' AS set_description";

$xpRewardSelect = isset($activityColumns['xp_reward'])
    ? 'a.xp_reward AS xp_reward'
    : '0 AS xp_reward';

$activityStmt = $pdo->prepare(
    "SELECT
        a.id,
        a.lesson_id,
        a.`{$activityTitleColumn}` AS activity_title,
        {$activityTypeSelect},
        a.flashcard_set_id,
        {$xpRewardSelect},
        fs.`{$setTitleColumn}` AS set_title,
        {$setDescriptionSelect},
        l.lesson_number,
        l.title AS lesson_title,
        u.unit_number,
        u.title AS unit_title,
        b.name AS book_name
     FROM activities a
     INNER JOIN flashcard_sets fs
        ON fs.id = a.flashcard_set_id
     INNER JOIN lessons l
        ON l.id = a.lesson_id
     INNER JOIN units u
        ON u.id = l.unit_id
     INNER JOIN books b
        ON b.id = u.book_id
     WHERE a.id = ?
     LIMIT 1"
);
$activityStmt->execute([$activityId]);
$activity = $activityStmt->fetch(PDO::FETCH_ASSOC);

if (!$activity) {
    http_response_code(404);
    exit('Activity or Flashcard Set not found.');
}

$meaningSelect = $meaningColumn !== null
    ? "w.`{$meaningColumn}` AS meaning"
    : "'' AS meaning";

$ipaSelect = $ipaColumn !== null
    ? "w.`{$ipaColumn}` AS ipa"
    : "'' AS ipa";

$imageSelect = $imageColumn !== null
    ? "w.`{$imageColumn}` AS image_path"
    : "'' AS image_path";

$audioSelect = $audioColumn !== null
    ? "w.`{$audioColumn}` AS audio_path"
    : "'' AS audio_path";

$exampleSelect = "
    (
        SELECT we.example_en
        FROM word_examples we
        WHERE we.word_id = w.id
          AND we.status = 'active'
        ORDER BY we.sort_order ASC, we.id ASC
        LIMIT 1
    ) AS example_en
";

$wordStmt = $pdo->prepare(
    "SELECT
        w.id,
        w.`{$wordTextColumn}` AS word_text,
        {$meaningSelect},
        {$ipaSelect},
        {$imageSelect},
        {$audioSelect},
        {$exampleSelect},
        fsw.`{$orderColumn}` AS display_order
     FROM flashcard_set_words fsw
     INNER JOIN words w
        ON w.id = fsw.`{$wordFk}`
     WHERE fsw.`{$setFk}` = ?
       " . (isset($wordColumns['status']) ? "AND w.status = 'active'" : "") . "
     ORDER BY fsw.`{$orderColumn}` ASC, fsw.id ASC"
);
$wordStmt->execute([(int)$activity['flashcard_set_id']]);
$wordRows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

$cards = array_map(
    static function (array $row): array {
        return [
            'id' => (int)$row['id'],
            'word' => (string)$row['word_text'],
            'meaning' => (string)($row['meaning'] ?? ''),
            'ipa' => (string)($row['ipa'] ?? ''),
            'image' => flashPlayerUrl((string)($row['image_path'] ?? '')),
            'audio' => flashPlayerUrl((string)($row['audio_path'] ?? '')),
            'example' => (string)($row['example_en'] ?? ''),
        ];
    },
    $wordRows
);

$activityTitle = (string)$activity['activity_title'];
$setTitle = (string)$activity['set_title'];
$lessonPath = implode(' • ', array_filter([
    (string)$activity['book_name'],
    (string)$activity['unit_number'],
    (string)$activity['lesson_number'],
]));
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <title><?= htmlspecialchars($activityTitle, ENT_QUOTES, 'UTF-8') ?> | EnglishSpeak</title>

    <style>
        :root{
            --blue:#2563eb;
            --blue-dark:#1d4ed8;
            --page:#edf4ff;
            --card:#fff;
            --text:#10213f;
            --muted:#64748b;
            --line:#d8e2f1;
            --shadow:0 24px 65px rgba(52,78,124,.18);
        }
        *{box-sizing:border-box}
        html,body{margin:0;min-height:100%;font-family:Arial,sans-serif;color:var(--text);background:var(--page)}
        button{font:inherit}
        .player{
            width:min(100%,620px);
            min-height:100dvh;
            margin:0 auto;
            padding:16px 16px 24px;
        }
        .topbar{
            display:flex;
            align-items:flex-start;
            justify-content:space-between;
            gap:14px;
            margin-bottom:14px;
        }
        .eyebrow{display:block;color:var(--blue);font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.08em}
        h1{margin:5px 0 0;font-size:26px;line-height:1.15}
        .path{margin:6px 0 0;color:var(--muted);font-size:12px}
        .top-actions{display:flex;gap:8px}
        .icon-button{
            display:inline-grid;
            width:42px;height:42px;
            place-items:center;
            border:1px solid var(--line);
            border-radius:12px;
            background:#fff;
            cursor:pointer;
        }
        .icon-button.active{border-color:var(--blue);background:#dbeafe;color:var(--blue)}
        .auto-play-button{
            min-height:42px;
            padding:0 15px;
            border:1px solid var(--blue);
            border-radius:12px;
            background:var(--blue);
            color:#fff;
            font-weight:800;
            cursor:pointer;
        }
        .auto-play-button.active{
            background:#ef4444;
            border-color:#ef4444;
        }
        .auto-toolbar{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            margin:0 0 12px;
            padding:10px 12px;
            border:1px solid var(--line);
            border-radius:13px;
            background:rgba(255,255,255,.72);
        }
        .auto-toolbar-label{
            color:var(--muted);
            font-size:12px;
            font-weight:800;
        }
        .speed-options{
            display:flex;
            gap:6px;
        }
        .speed-button{
            min-height:32px;
            padding:0 10px;
            border:1px solid var(--line);
            border-radius:9px;
            background:#fff;
            color:var(--text);
            font-size:12px;
            font-weight:800;
            cursor:pointer;
        }
        .speed-button.active{
            border-color:var(--blue);
            background:#dbeafe;
            color:var(--blue-dark);
        }
        .auto-status{
            min-width:105px;
            color:var(--muted);
            font-size:11px;
            font-weight:700;
            text-align:right;
        }
        .progress-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:7px;color:var(--muted);font-size:12px;font-weight:700}
        .progress-track{height:8px;overflow:hidden;border-radius:999px;background:#d7e2f2;margin-bottom:13px}
        .progress-fill{width:0;height:100%;border-radius:inherit;background:var(--blue);transition:width .25s ease}
        .stage{perspective:1500px}
        .study-card{
            position:relative;
            width:100%;
            height:min(66dvh,650px);
            min-height:450px;
            padding:0;
            border:0;
            background:transparent;
        }
        .face{
            position:absolute;inset:0;
            display:flex;flex-direction:column;
            align-items:center;justify-content:center;
            overflow:hidden;
            border-radius:28px;
            background:var(--card);
            box-shadow:var(--shadow);
            backface-visibility:hidden;
            -webkit-backface-visibility:hidden;
            transform-style:preserve-3d;
            transition:transform .45s ease;
        }
        .front{transform:rotateY(0)}
        .back{transform:rotateY(180deg);padding:34px;text-align:center}
        .study-card.flipped .front{transform:rotateY(-180deg)}
        .study-card.flipped .back{transform:rotateY(0)}
        .image-wrap{
            display:grid;
            width:100%;height:100%;
            place-items:center;
            padding:24px;
            border:0;
            background:#fff;
            cursor:pointer;
        }
        .image-wrap img{width:100%;height:100%;object-fit:contain}
        .fallback-letter{font-size:130px;font-weight:900;color:var(--blue)}
        .word{margin:0 0 9px;font-size:clamp(46px,10vw,76px);line-height:1.05}
        .ipa{min-height:28px;margin-bottom:18px;color:var(--blue);font-size:24px;font-weight:750}
        .meaning{margin:0;color:#334155;font-size:30px;font-weight:700;line-height:1.35}
        .example{margin:22px 0 0;color:var(--muted);font-size:17px;line-height:1.5}
        .listen{
            margin-top:26px;
            padding:13px 20px;
            border:0;border-radius:14px;
            background:var(--blue);color:#fff;
            font-weight:800;cursor:pointer;
        }
        .controls{
            display:grid;
            grid-template-columns:1fr 1.2fr 1fr;
            gap:10px;
            margin-top:14px;
        }
        .control{
            min-height:50px;
            border:1px solid var(--line);
            border-radius:13px;
            background:#fff;
            color:var(--text);
            font-weight:800;
            cursor:pointer;
        }
        .control.primary{background:var(--blue);border-color:var(--blue);color:#fff}
        .control:disabled{opacity:.42;cursor:not-allowed}
        .finish{
            display:none;
            padding:44px 24px;
            border-radius:24px;
            background:#fff;
            box-shadow:var(--shadow);
            text-align:center;
        }
        .finish.show{display:block}
        .finish h2{margin:12px 0 8px;font-size:34px}
        .finish p{color:var(--muted)}
        .finish-actions{display:flex;justify-content:center;gap:10px;margin-top:20px}
        .finish-actions button{min-height:46px;padding:0 18px;border-radius:12px;font-weight:800;cursor:pointer}
        .empty{padding:50px 24px;border-radius:20px;background:#fff;text-align:center}
        @media(max-width:650px){
            .player{width:100%;padding:11px 11px 18px}
            h1{font-size:22px}
            .study-card{height:calc(100dvh - 205px);min-height:430px;max-height:690px}
            .face{border-radius:22px}
            .image-wrap{padding:10px}
            .back{padding:23px}
            .meaning{font-size:26px}
            .controls{gap:7px;margin-top:10px}
            .control{min-height:48px;padding:0 7px;font-size:14px}
            .auto-toolbar{
                align-items:flex-start;
                flex-wrap:wrap;
                gap:8px;
            }
            .auto-status{
                width:100%;
                text-align:left;
            }
            .auto-play-button{
                padding:0 12px;
                font-size:13px;
            }
        }
        @media(prefers-reduced-motion:reduce){
            .face,.progress-fill{transition:none}
        }
    </style>
</head>

<body>
<main class="player">
    <header class="topbar">
        <div>
            <span class="eyebrow">Flashcards</span>
            <h1><?= htmlspecialchars($activityTitle, ENT_QUOTES, 'UTF-8') ?></h1>
            <p class="path">
                <?= htmlspecialchars($lessonPath . ' • ' . $setTitle, ENT_QUOTES, 'UTF-8') ?>
            </p>
        </div>

        <div class="top-actions">
            <button class="icon-button" id="shuffleButton" type="button" title="Shuffle">🔀</button>
            <button class="auto-play-button" id="autoButton" type="button">
                ▶ Auto Play
            </button>
        </div>
    </header>

    <?php if ($cards === []): ?>
        <section class="empty">
            <h2>No words yet</h2>
            <p>This Flashcard Set has no active words.</p>
        </section>
    <?php else: ?>
        <section id="gameArea">
            <div class="progress-row">
                <span id="progressLabel">1 / <?= count($cards) ?></span>
                <span id="modeLabel">Normal</span>
            </div>

            <div class="progress-track">
                <div class="progress-fill" id="progressFill"></div>
            </div>

            <div class="auto-toolbar">
                <span class="auto-toolbar-label">Speed</span>
                <div class="speed-options" role="group" aria-label="Auto Play speed">
                    <button class="speed-button" type="button" data-speed="slow">Slow</button>
                    <button class="speed-button active" type="button" data-speed="normal">Normal</button>
                    <button class="speed-button" type="button" data-speed="fast">Fast</button>
                </div>
                <span class="auto-status" id="autoStatus">Auto Play is off</span>
            </div>

            <div class="stage">
                <div class="study-card" id="studyCard">
                    <section class="face front">
                        <button class="image-wrap" id="imageButton" type="button">
                            <img id="cardImage" alt="" hidden>
                            <span class="fallback-letter" id="fallbackLetter">A</span>
                        </button>
                    </section>

                    <section class="face back" id="cardBack">
                        <h2 class="word" id="wordText"></h2>
                        <div class="ipa" id="ipaText"></div>
                        <p class="meaning" id="meaningText"></p>
                        <p class="example" id="exampleText"></p>
                        <button class="listen" id="listenButton" type="button">🔊 Listen</button>
                    </section>
                </div>
            </div>

            <div class="controls">
                <button class="control" id="previousButton" type="button">← Previous</button>
                <button class="control primary" id="flipButton" type="button">Flip</button>
                <button class="control" id="nextButton" type="button">Next →</button>
            </div>
        </section>

        <section class="finish" id="finishScreen">
            <div style="font-size:54px">🎉</div>
            <h2>Congratulations!</h2>
            <p>You reviewed all <?= count($cards) ?> flashcards.</p>
            <div class="finish-actions">
                <button class="control" id="replayButton" type="button">Replay</button>
                <button class="control primary" id="finishButton" type="button">
                    Back to Activities
                </button>
            </div>
        </section>
    <?php endif; ?>
</main>

<?php if ($cards !== []): ?>
<script>
const originalCards = <?= json_encode(
    $cards,
    JSON_UNESCAPED_UNICODE
    | JSON_UNESCAPED_SLASHES
    | JSON_HEX_TAG
    | JSON_HEX_AMP
    | JSON_HEX_APOS
    | JSON_HEX_QUOT
) ?>;

let cards = [...originalCards];
let currentIndex = 0;
let autoTimer = null;
let activeAudio = null;
let isAuto = false;
let isShuffled = false;
let autoPhase = 'front';
let autoSpeed = 'normal';

const autoTimings = {
    slow: { front: 2200, back: 3800 },
    normal: { front: 1400, back: 2800 },
    fast: { front: 800, back: 1700 }
};

const gameArea = document.getElementById('gameArea');
const finishScreen = document.getElementById('finishScreen');
const studyCard = document.getElementById('studyCard');
const cardBack = document.getElementById('cardBack');
const imageButton = document.getElementById('imageButton');
const cardImage = document.getElementById('cardImage');
const fallbackLetter = document.getElementById('fallbackLetter');
const wordText = document.getElementById('wordText');
const ipaText = document.getElementById('ipaText');
const meaningText = document.getElementById('meaningText');
const exampleText = document.getElementById('exampleText');
const listenButton = document.getElementById('listenButton');
const previousButton = document.getElementById('previousButton');
const nextButton = document.getElementById('nextButton');
const flipButton = document.getElementById('flipButton');
const shuffleButton = document.getElementById('shuffleButton');
const autoButton = document.getElementById('autoButton');
const speedButtons = [...document.querySelectorAll('.speed-button')];
const autoStatus = document.getElementById('autoStatus');
const progressLabel = document.getElementById('progressLabel');
const progressFill = document.getElementById('progressFill');
const modeLabel = document.getElementById('modeLabel');
const replayButton = document.getElementById('replayButton');
const finishButton = document.getElementById('finishButton');

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

function stopAudio() {
    if (activeAudio) {
        activeAudio.pause();
        activeAudio = null;
    }

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

function speakWithBrowser(text) {
    if (!('speechSynthesis' in window)) {
        return;
    }

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'en-US';
    utterance.rate = 0.78;
    window.speechSynthesis.speak(utterance);
}

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

    stopAudio();

    if (card.audio) {
        activeAudio = new Audio(card.audio);
        activeAudio.play().catch(() => speakWithBrowser(card.word));
        return;
    }

    speakWithBrowser(card.word);
}

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

    stopAudio();
    studyCard.classList.remove('flipped');

    wordText.textContent = card.word;
    ipaText.textContent = card.ipa || '';
    meaningText.textContent = card.meaning || '';
    exampleText.textContent = card.example || '';
    exampleText.hidden = !card.example;

    fallbackLetter.textContent = (card.word || '?').charAt(0).toUpperCase();

    if (card.image) {
        cardImage.src = card.image;
        cardImage.hidden = false;
        fallbackLetter.hidden = true;

        cardImage.onerror = () => {
            cardImage.hidden = true;
            fallbackLetter.hidden = false;
        };
    } else {
        cardImage.removeAttribute('src');
        cardImage.hidden = true;
        fallbackLetter.hidden = false;
    }

    progressLabel.textContent = `${currentIndex + 1} / ${cards.length}`;
    progressFill.style.width = `${((currentIndex + 1) / cards.length) * 100}%`;

    previousButton.disabled = currentIndex === 0;
    nextButton.textContent = currentIndex === cards.length - 1 ? 'Finish →' : 'Next →';

    const modes = [];
    if (isShuffled) modes.push('Shuffle');
    if (isAuto) modes.push('Auto Play');
    modeLabel.textContent = modes.length ? modes.join(' • ') : 'Normal';

    if (autoStatus) {
        autoStatus.textContent = isAuto
            ? `Playing • ${autoSpeed}`
            : 'Auto Play is off';
    }
}

function flipCard() {
    studyCard.classList.toggle('flipped');
}

function moveNext() {
    if (currentIndex >= cards.length - 1) {
        completeGame();
        return;
    }

    currentIndex++;
    renderCard();
}

function movePrevious() {
    if (currentIndex <= 0) {
        return;
    }

    currentIndex--;
    renderCard();
}

function completeGame() {
    stopAuto();
    stopAudio();
    gameArea.hidden = true;
    finishScreen.classList.add('show');
}

function replayGame() {
    stopAuto();
    currentIndex = 0;
    gameArea.hidden = false;
    finishScreen.classList.remove('show');
    renderCard();
}

function shuffleCards() {
    isShuffled = !isShuffled;

    if (isShuffled) {
        cards = [...cards];

        for (let i = cards.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [cards[i], cards[j]] = [cards[j], cards[i]];
        }
    } else {
        cards = [...originalCards];
    }

    currentIndex = 0;
    shuffleButton.classList.toggle('active', isShuffled);
    renderCard();
}

function scheduleAutoStep(delay) {
    if (!isAuto) {
        return;
    }

    if (autoTimer) {
        window.clearTimeout(autoTimer);
    }

    autoTimer = window.setTimeout(runAutoStep, delay);
}

function runAutoStep() {
    if (!isAuto) {
        return;
    }

    const timing = autoTimings[autoSpeed];

    if (autoPhase === 'front') {
        speakCurrent();
        autoPhase = 'back';
        scheduleAutoStep(timing.front);
        return;
    }

    if (autoPhase === 'back') {
        studyCard.classList.add('flipped');
        autoPhase = 'next';
        scheduleAutoStep(timing.back);
        return;
    }

    if (currentIndex >= cards.length - 1) {
        completeGame();
        return;
    }

    currentIndex++;
    autoPhase = 'front';
    renderCard();
    scheduleAutoStep(500);
}

function startAuto() {
    isAuto = true;
    autoPhase = 'front';

    autoButton.classList.add('active');
    autoButton.textContent = '⏸ Pause';

    renderCard();
    scheduleAutoStep(500);
}

function stopAuto() {
    isAuto = false;
    autoPhase = 'front';

    autoButton?.classList.remove('active');

    if (autoButton) {
        autoButton.textContent = '▶ Auto Play';
    }

    if (autoTimer) {
        window.clearTimeout(autoTimer);
        autoTimer = null;
    }

    stopAudio();

    if (autoStatus) {
        autoStatus.textContent = 'Auto Play is off';
    }

    if (modeLabel) {
        modeLabel.textContent = isShuffled ? 'Shuffle' : 'Normal';
    }
}

function toggleAuto() {
    if (isAuto) {
        stopAuto();
    } else {
        startAuto();
    }
}

imageButton.addEventListener('click', speakCurrent);
listenButton.addEventListener('click', event => {
    event.stopPropagation();
    speakCurrent();
});
cardBack.addEventListener('click', event => {
    if (!event.target.closest('#listenButton')) {
        flipCard();
    }
});
flipButton.addEventListener('click', flipCard);
previousButton.addEventListener('click', movePrevious);
nextButton.addEventListener('click', moveNext);
shuffleButton.addEventListener('click', shuffleCards);
autoButton.addEventListener('click', toggleAuto);

speedButtons.forEach(button => {
    button.addEventListener('click', () => {
        autoSpeed = button.dataset.speed || 'normal';

        speedButtons.forEach(item => {
            item.classList.toggle('active', item === button);
        });

        if (autoStatus) {
            autoStatus.textContent = isAuto
                ? `Playing • ${autoSpeed}`
                : `Ready • ${autoSpeed}`;
        }

        if (isAuto) {
            autoPhase = 'front';
            renderCard();
            scheduleAutoStep(350);
        }
    });
});

replayButton.addEventListener('click', replayGame);
finishButton.addEventListener('click', () => {
    window.location.href = '/EnglishSpeak/teacher/lesson-activities/index.php?lesson_id=<?= (int)$activity['lesson_id'] ?>';
});

document.addEventListener('keydown', event => {
    if (event.key === 'ArrowLeft') movePrevious();
    if (event.key === 'ArrowRight') moveNext();

    if (event.code === 'Space') {
        event.preventDefault();
        flipCard();
    }

    if (event.key.toLowerCase() === 'l') {
        speakCurrent();
    }
});

renderCard();
</script>
<?php endif; ?>
</body>
</html>
