<?php
declare(strict_types=1);

session_start();

if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
$pdo = getDbConnection();

$bookSlug = trim((string)($_GET['book'] ?? ''));
$levelSlug = trim((string)($_GET['level'] ?? ''));
$levelId = max(0, (int)($_GET['level_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? ($_GET['id'] ?? 0)));
$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));
$activityId = max(0, (int)($_GET['activity_id'] ?? ($_GET['activity'] ?? 0)));

if (
    $bookSlug === ''
    || $levelId <= 0
    || $unitId <= 0
    || $lessonId <= 0
    || $activityId <= 0
) {
    header('Location: student-learning.php');
    exit;
}

function swlColumns(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 studentAssetUrl(string $path): string
{
    $path = trim($path);

    if ($path === '') {
        return '';
    }

    if (
        str_starts_with($path, 'http://')
        || str_starts_with($path, 'https://')
        || str_starts_with($path, 'data:')
        || str_starts_with($path, '/')
    ) {
        return $path;
    }

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

$activityColumns = swlColumns($pdo, 'activities');
$relationColumns = swlColumns($pdo, 'flashcard_set_words');
$wordColumns = swlColumns($pdo, 'words');
$exampleColumns = swlColumns($pdo, 'word_examples');

if (
    $activityColumns === []
    || $relationColumns === []
    || $wordColumns === []
    || !isset($activityColumns['flashcard_set_id'])
) {
    http_response_code(500);
    exit('Thiếu bảng dữ liệu Word List.');
}

$activityTitleColumn = isset($activityColumns['title'])
    ? 'title'
    : (isset($activityColumns['name']) ? 'name' : 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'
        : (isset($wordColumns['audio']) ? 'audio' : null));

if (
    $activityTitleColumn === null
    || $setFk === null
    || $wordFk === null
    || $wordTextColumn === null
) {
    http_response_code(500);
    exit('Cấu trúc dữ liệu Word List chưa đầy đủ.');
}

/*
|--------------------------------------------------------------------------
| Xác nhận đúng Book → Level → Unit → Lesson → Activity
|--------------------------------------------------------------------------
*/
$activityStatusWhere = isset($activityColumns['status'])
    ? "AND a.status = 'active'"
    : '';

$contextStmt = $pdo->prepare(
    "SELECT
        a.id AS activity_id,
        a.flashcard_set_id,
        a.`{$activityTitleColumn}` AS activity_title,

        le.id AS lesson_id,
        le.lesson_number,
        le.title AS lesson_title,

        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,

        l.id AS level_id,
        l.name AS level_name,
        l.slug AS level_slug,

        b.id AS book_id,
        b.name AS book_name,
        b.slug AS book_slug
     FROM activities a
     INNER JOIN lessons le
        ON le.id = a.lesson_id
     INNER JOIN units u
        ON u.id = le.unit_id
     INNER JOIN levels l
        ON l.id = u.level_id
     INNER JOIN books b
        ON b.id = l.book_id
     WHERE a.id = ?
       AND le.id = ?
       AND u.id = ?
       AND l.id = ?
       AND b.slug = ?
       {$activityStatusWhere}
     LIMIT 1"
);
$contextStmt->execute([
    $activityId,
    $lessonId,
    $unitId,
    $levelId,
    $bookSlug,
]);
$activityData = $contextStmt->fetch(PDO::FETCH_ASSOC);

if (!$activityData) {
    http_response_code(404);
    exit('Không tìm thấy hoạt động trong cấp độ đã chọn.');
}

$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 = "'' AS example_en";

if ($exampleColumns !== [] && isset($exampleColumns['word_id'], $exampleColumns['example_en'])) {
    $exampleStatus = isset($exampleColumns['status'])
        ? "AND we.status = 'active'"
        : '';

    $exampleOrder = isset($exampleColumns['sort_order'])
        ? 'we.sort_order ASC, we.id ASC'
        : 'we.id ASC';

    $exampleSelect = "
        (
            SELECT we.example_en
            FROM word_examples we
            WHERE we.word_id = w.id
              {$exampleStatus}
            ORDER BY {$exampleOrder}
            LIMIT 1
        ) AS example_en
    ";
}

$wordStatusWhere = isset($wordColumns['status'])
    ? "AND w.status = 'active'"
    : '';

$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}` = ?
       {$wordStatusWhere}
     ORDER BY fsw.`{$orderColumn}` ASC, fsw.id ASC"
);
$wordStmt->execute([(int)$activityData['flashcard_set_id']]);
$wordRows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

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

$_SESSION['last_learning_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');

$rawUnitNumber = trim((string)$activityData['unit_number']);
$rawLessonNumber = trim((string)$activityData['lesson_number']);

$displayUnitNumber = preg_match('/(\d+)/', $rawUnitNumber, $unitMatch)
    ? (int)$unitMatch[1]
    : $rawUnitNumber;

$displayLessonNumber = preg_match('/(\d+)/', $rawLessonNumber, $lessonMatch)
    ? (int)$lessonMatch[1]
    : $rawLessonNumber;

$pageTitle = 'Unit ' . $displayUnitNumber;
$pageSubtitle = (string)$activityData['unit_title'];
$showBack = true;
$backUrl = 'student-activities.php?' . http_build_query([
    'book' => (string)$activityData['book_slug'],
    'level' => (string)$activityData['level_slug'],
    'level_id' => (int)$activityData['level_id'],
    'unit_id' => (int)$activityData['unit_id'],
    'lesson_id' => (int)$activityData['lesson_id'],
    'lesson' => $displayLessonNumber,
]);
$activeStudentNav = 'learning';

include __DIR__ . '/../includes/student-layout-start.php';
?>

<style>
:root {
    --es-blue: #198fe3;
    --es-blue-dark: #187ac3;
    --es-blue-soft: #eaf5ff;
    --es-bg: #f4f8fc;
    --es-surface: #fff;
    --es-text: #15314b;
    --es-muted: #718399;
    --es-line: #e0e8f0;
    --es-shadow: 0 6px 20px rgba(31, 71, 108, .10);
    --es-width: 520px;
    --es-nav-height: 78px;
}

* {
    box-sizing: border-box;
}

html,
body {
    margin: 0 !important;
    min-height: 100%;
    background: var(--es-bg) !important;
    color: var(--es-text) !important;
    font-family: "Segoe UI", Tahoma, Arial, sans-serif !important;
}

body {
    padding-bottom: calc(var(--es-nav-height) + env(safe-area-inset-bottom) + 16px) !important;
}

.student-app {
    width: min(100%, var(--es-width)) !important;
    min-height: 100vh !important;
    margin: 0 auto !important;
    background: #fff !important;
    box-shadow: 0 0 26px rgba(24, 67, 101, .08);
}

/* Header */
.student-header {
    position: sticky !important;
    top: 0 !important;
    z-index: 40 !important;
    display: grid !important;
    grid-template-columns: 48px minmax(0, 1fr) 48px !important;
    align-items: center !important;
    gap: 8px !important;
    min-height: 76px !important;
    padding: 12px 14px !important;
    background: linear-gradient(135deg, #3488ef, #17b8e4) !important;
    color: #fff !important;
    box-shadow: 0 5px 15px rgba(31, 135, 210, .22) !important;
}

.student-back {
    width: 44px !important;
    height: 44px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 50% !important;
    background: rgba(255,255,255,.14) !important;
    color: #fff !important;
    box-shadow: none !important;
    text-decoration: none !important;
    font-size: 29px !important;
    line-height: 1 !important;
}

.student-header__text {
    min-width: 0 !important;
    text-align: center !important;
}

.student-header__text h1 {
    margin: 0 !important;
    color: #fff !important;
    font-size: 23px !important;
    font-weight: 800 !important;
    line-height: 1.15 !important;
}

.student-header__text p {
    margin: 4px 0 0 !important;
    overflow: hidden !important;
    color: rgba(255,255,255,.92) !important;
    font-size: 12.5px !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-header__spacer {
    width: 44px !important;
    height: 44px !important;
    border-radius: 50% !important;
    background: rgba(255,255,255,.13) !important;
}

.student-header__spacer::before {
    content: "🔊";
    width: 100%;
    height: 100%;
    display: grid;
    place-items: center;
    font-size: 21px;
}

.student-content {
    width: 100% !important;
    padding: 18px 18px 28px !important;
}

/* Lesson intro */
.word-intro {
    display: grid;
    grid-template-columns: 70px minmax(0, 1fr);
    align-items: center;
    gap: 16px;
    padding: 18px;
    border-radius: 20px;
    background: linear-gradient(135deg, #edf6ff, #e6f1ff);
}

.word-intro__icon {
    width: 66px;
    height: 76px;
    display: grid;
    place-items: center;
    border-radius: 14px;
    font-size: 45px;
}

.word-intro__unit {
    display: block;
    margin-bottom: 4px;
    color: #111;
    font-size: 17px;
    font-weight: 800;
}

.word-intro h2 {
    margin: 0;
    color: #0868c7;
    font-size: 20px;
    line-height: 1.25;
}

.word-intro p {
    margin: 7px 0 0;
    color: #405870;
    font-size: 13.5px;
    line-height: 1.4;
}

/* Search */
.word-search {
    position: sticky;
    top: 84px;
    z-index: 20;
    padding: 18px 0 12px;
    background: #fff;
}

.word-search input {
    width: 100%;
    min-height: 54px;
    padding: 0 18px 0 48px;
    border: 1.5px solid #ccd5df;
    border-radius: 28px;
    outline: none;
    background:
        #fff
        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' viewBox='0 0 24 24' fill='none' stroke='%236c7990' stroke-width='2.3' stroke-linecap='round'%3E%3Ccircle cx='11' cy='11' r='7.5'/%3E%3Cpath d='m20 20-4-4'/%3E%3C/svg%3E")
        no-repeat 17px center;
    color: var(--es-text);
    font-size: 15px;
}

.word-search input:focus {
    border-color: var(--es-blue);
    box-shadow: 0 0 0 4px rgba(25, 143, 227, .10);
}

/* Word cards */
.word-list {
    display: grid;
    gap: 14px;
}

.word-card {
    display: grid;
    grid-template-columns: 112px minmax(0, 1fr) 52px;
    align-items: start;
    gap: 12px;
    padding: 18px 16px 14px;
    border: 1px solid #e5e9ee;
    border-radius: 18px;
    background: #fff;
    box-shadow: var(--es-shadow);
}

.word-card__image {
    width: 104px;
    height: 104px;
    display: grid;
    place-items: center;
    overflow: hidden;
    border-radius: 16px;
    background: #f7fbff;
}

.word-card__image img {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: contain;
}

.word-card__placeholder {
    font-size: 54px;
}

.word-card__body {
    min-width: 0;
    padding-top: 2px;
}

.word-card__word {
    color: #0869c9;
    font-size: 22px;
    font-weight: 800;
    line-height: 1.15;
}

.word-card__ipa {
    min-height: 20px;
    margin-top: 6px;
    color: #126fc7;
    font-size: 16px;
    font-style: italic;
}

.word-card__meaning {
    margin-top: 8px;
    color: #171717;
    font-size: 14.5px;
    line-height: 1.35;
}

.sound-button {
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border: 0;
    border-radius: 50%;
    background: #13a5e8;
    color: #fff;
    cursor: pointer;
    font-size: 22px;
    box-shadow: 0 5px 12px rgba(19, 165, 232, .20);
    -webkit-tap-highlight-color: transparent;
}

.sound-button:active {
    transform: scale(.95);
}

.word-card__example {
    grid-column: 2 / 4;
    margin-top: -2px;
    padding: 9px 12px;
    border: 1px solid #d5e5f6;
    border-radius: 11px;
    background: #edf6ff;
    color: #3d6591;
    font-size: 13.5px;
    line-height: 1.4;
}

.word-empty {
    padding: 30px 20px;
    border: 1px dashed #b8ccdd;
    border-radius: 18px;
    background: #f8fcff;
    color: var(--es-muted);
    text-align: center;
}

.word-empty strong {
    display: block;
    margin-bottom: 6px;
    color: var(--es-text);
    font-size: 17px;
}

/* Bottom nav — fixed and styled */
.student-nav {
    position: fixed !important;
    z-index: 9999 !important;
    left: 50% !important;
    bottom: 0 !important;
    width: min(100%, var(--es-width)) !important;
    min-height: var(--es-nav-height) !important;
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
    padding: 7px 8px calc(7px + env(safe-area-inset-bottom)) !important;
    border-top: 1px solid #dde3ea !important;
    background: rgba(255,255,255,.98) !important;
    box-shadow: 0 -6px 18px rgba(32, 65, 93, .11) !important;
    transform: translateX(-50%) !important;
    backdrop-filter: blur(14px);
}

.student-nav__item {
    position: relative !important;
    display: flex !important;
    flex-direction: column !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 2px !important;
    min-width: 0 !important;
    color: #536070 !important;
    text-decoration: none !important;
}

.student-nav__icon {
    width: 42px !important;
    height: 34px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 12px !important;
    font-family: "Segoe UI Emoji","Apple Color Emoji","Noto Color Emoji",sans-serif !important;
    font-size: 23px !important;
}

.student-nav__label {
    overflow: hidden !important;
    max-width: 100% !important;
    color: inherit !important;
    font-size: 11.5px !important;
    font-weight: 700 !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-nav__item.is-active {
    color: #1589e4 !important;
}

.student-nav__item.is-active .student-nav__icon {
    background: #e8f4ff !important;
}

.student-nav__item.is-active::after {
    content: "";
    position: absolute;
    top: -7px;
    width: 54px;
    height: 3px;
    border-radius: 999px;
    background: #1589e4;
}

@media (max-width: 430px) {
    .student-content {
        padding: 14px 12px 24px !important;
    }

    .word-intro {
        grid-template-columns: 60px minmax(0, 1fr);
        gap: 12px;
        padding: 14px;
    }

    .word-intro__icon {
        width: 58px;
        height: 66px;
        font-size: 39px;
    }

    .word-intro h2 {
        font-size: 18px;
    }

    .word-card {
        grid-template-columns: 80px minmax(0, 1fr) 44px;
        gap: 10px;
        padding: 13px 12px 12px;
    }

    .word-card__image {
        width: 76px;
        height: 76px;
    }

    .word-card__placeholder {
        font-size: 42px;
    }

    .word-card__word {
        font-size: 19px;
    }

    .word-card__ipa {
        margin-top: 4px;
        font-size: 14px;
    }

    .word-card__meaning {
        margin-top: 5px;
        font-size: 13px;
    }

    .sound-button {
        width: 42px;
        height: 42px;
        font-size: 19px;
    }

    .word-card__example {
        grid-column: 1 / -1;
        margin-top: 0;
    }
}

@media (max-width: 350px) {
    .word-card {
        grid-template-columns: 66px minmax(0, 1fr) 40px;
        gap: 8px;
    }

    .word-card__image {
        width: 62px;
        height: 62px;
    }

    .word-card__word {
        font-size: 17px;
    }

    .student-nav__label {
        font-size: 10.5px !important;
    }
}

.word-intro--minimal {
    grid-template-columns: 52px minmax(0, 1fr);
    min-height: 72px;
    padding: 12px 14px;
}

.word-intro--minimal .word-intro__icon {
    width: 48px;
    height: 48px;
    font-size: 30px;
}

.word-intro--minimal .word-intro__unit {
    margin: 0;
    color: #111;
    font-size: 18px;
    font-weight: 800;
}


.word-image-button {
    padding: 0;
    border: 0;
    cursor: pointer;
    -webkit-tap-highlight-color: transparent;
}

.word-image-button:active {
    transform: scale(.97);
}

.word-card__example {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.word-card__example-text {
    min-width: 0;
    flex: 1;
}

.example-sound-button {
    flex: 0 0 34px;
    width: 34px;
    height: 34px;
    display: grid;
    place-items: center;
    border: 0;
    border-radius: 50%;
    background: #ffffff;
    color: #168ed9;
    cursor: pointer;
    font-size: 16px;
    box-shadow: 0 2px 8px rgba(24, 93, 143, .12);
    -webkit-tap-highlight-color: transparent;
}

.example-sound-button:active {
    transform: scale(.94);
}

</style>

<section class="word-intro word-intro--minimal">
    <div class="word-intro__icon" aria-hidden="true">📘</div>
    <div>
        <span class="word-intro__unit">Word List</span>
    </div>
</section>

<div class="word-search">
    <input
        type="search"
        data-word-search
        placeholder="Tìm từ..."
        autocomplete="off"
        aria-label="Tìm từ"
    >
</div>

<section class="word-list" aria-label="Danh sách từ vựng">
    <?php if ($words === []): ?>
        <div class="word-empty">
            <strong>Chưa có từ vựng</strong>
            Bài học này chưa có dữ liệu từ.
        </div>
    <?php endif; ?>

    <?php foreach ($words as $item): ?>
        <?php
        $word = trim((string)($item['word'] ?? ''));
        $ipa = trim((string)($item['ipa'] ?? ''));
        $meaning = trim((string)($item['meaning'] ?? ''));
        $example = trim((string)($item['example'] ?? ''));
        $image = (string)($item['image'] ?? '');
        $audio = (string)($item['audio'] ?? '');
        $search = mb_strtolower($word . ' ' . $meaning, 'UTF-8');
        ?>
        <article
            class="word-card"
            data-word-card
            data-search="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>"
        >
            <button
                class="word-card__image word-image-button"
                type="button"
                data-speak="<?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>"
                data-audio="<?= htmlspecialchars($audio, ENT_QUOTES, 'UTF-8') ?>"
                aria-label="Nghe từ <?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>"
            >
                <?php if ($image !== ''): ?>
                    <img
                        src="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>"
                        alt="<?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>"
                        loading="lazy"
                    >
                <?php else: ?>
                    <span class="word-card__placeholder" aria-hidden="true">🖼️</span>
                <?php endif; ?>
            </button>

            <div class="word-card__body">
                <div class="word-card__word">
                    <?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>
                </div>

                <?php if ($ipa !== ''): ?>
                    <div class="word-card__ipa">
                        <?= htmlspecialchars($ipa, ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>

                <?php if ($meaning !== ''): ?>
                    <div class="word-card__meaning">
                        <?= htmlspecialchars($meaning, ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>
            </div>

            <button
                class="sound-button"
                type="button"
                data-speak="<?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>"
                data-audio="<?= htmlspecialchars($audio, ENT_QUOTES, 'UTF-8') ?>"
                aria-label="Nghe từ <?= htmlspecialchars($word, ENT_QUOTES, 'UTF-8') ?>"
            >🔊</button>

            <?php if ($example !== ''): ?>
                <div class="word-card__example">
                    <span class="word-card__example-text">
                        <?= htmlspecialchars($example, ENT_QUOTES, 'UTF-8') ?>
                    </span>

                    <button
                        class="example-sound-button"
                        type="button"
                        data-speak="<?= htmlspecialchars($example, ENT_QUOTES, 'UTF-8') ?>"
                        data-audio=""
                        aria-label="Nghe câu ví dụ <?= htmlspecialchars($example, ENT_QUOTES, 'UTF-8') ?>"
                    >🔊</button>
                </div>
            <?php endif; ?>
        </article>
    <?php endforeach; ?>
</section>

<script>
(() => {
    const searchInput = document.querySelector('[data-word-search]');
    const cards = [...document.querySelectorAll('[data-word-card]')];

    searchInput?.addEventListener('input', () => {
        const keyword = searchInput.value.trim().toLocaleLowerCase('vi');

        cards.forEach((card) => {
            const value = (card.dataset.search || '').toLocaleLowerCase('vi');
            card.hidden = keyword !== '' && !value.includes(keyword);
        });
    });

    document.addEventListener('click', (event) => {
        const button = event.target.closest('[data-speak]');
        if (!button) {
            return;
        }

        const word = button.dataset.speak || '';
        const audioUrl = button.dataset.audio || '';

        if (audioUrl !== '') {
            const audio = new Audio(audioUrl);
            audio.play().catch(() => speak(word));
            return;
        }

        speak(word);
    });

    function speak(word) {
        if (word === '' || !('speechSynthesis' in window)) {
            return;
        }

        window.speechSynthesis.cancel();

        const utterance = new SpeechSynthesisUtterance(word);
        utterance.lang = 'en-US';
        utterance.rate = 0.72;
        window.speechSynthesis.speak(utterance);
    }
})();
</script>

<?php include __DIR__ . '/../includes/student-layout-end.php'; ?>
