<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$isPreview = (int)($_GET['preview'] ?? 0) === 1;
$isTeacher = !empty($_SESSION['user_id'])
    && in_array((string)($_SESSION['user_role'] ?? ''), ['teacher', 'admin'], true);
$isStudent = !empty($_SESSION['student_id']);

if ($isPreview) {
    if (!$isTeacher) {
        $_SESSION['teacher_return_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');
        header('Location: ../teacher/login.php');
        exit;
    }
} elseif (!$isStudent) {
    $_SESSION['student_return_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/student_activity_navigation.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)));
$isRuntime = (int)($_GET['runtime'] ?? 0) === 1;
$runtimeIndex = max(0, (int)($_GET['runtime_index'] ?? 0));
$runtimeTotal = max(0, (int)($_GET['runtime_total'] ?? 0));

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

function sfColumns(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 sfAssetUrl(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 = sfColumns($pdo, 'activities');
$relationColumns = sfColumns($pdo, 'flashcard_set_words');
$wordColumns = sfColumns($pdo, 'words');
$exampleColumns = sfColumns($pdo, 'word_examples');

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

$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 Flashcards chưa đầy đủ.');
}

$activityStatusWhere = isset($activityColumns['status'])
    ? "AND a.status = 'active'"
    : '';

$contextStmt = $pdo->prepare(
    "SELECT
        a.id AS activity_id,
        a.flashcard_set_id,
        a.xp_reward AS xp_reward,
        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,
]);
$activity = $contextStmt->fetch(PDO::FETCH_ASSOC);

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

/*
 * Điều hướng dùng hàm chung.
 * Nút Tiếp tục chỉ mở URL này; không xử lý XP, score hay progress.
 */
$nextActivityUrl = englishSpeakGetNextActivityUrl($pdo, $activityId);
if ($isPreview && str_contains($nextActivityUrl, 'student-runtime/index.php')) {
    $nextActivityUrl .= (str_contains($nextActivityUrl, '?') ? '&' : '?') . 'preview=1';
}

$xpReward = max(0, (int)($activity['xp_reward'] ?? 0));
if ($xpReward <= 0) {
    $xpReward = 10;
}

$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)$activity['flashcard_set_id']]);
$rows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

$cards = 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' => sfAssetUrl((string)($row['image_path'] ?? '')),
            'audio' => sfAssetUrl((string)($row['audio_path'] ?? '')),
        ];
    },
    $rows
);

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

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

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

$lessonFinishedUrl = 'lesson-finished.php?' . http_build_query([
    'lesson_id' => (int)$activity['lesson_id'],
]);

if ($isPreview) {
    $backUrl = '../teacher/activity-preview/index.php?' . http_build_query([
        'activity_id' => (int)$activity['activity_id'],
    ]);
} else {
    $backUrl = 'student-activities.php?' . http_build_query([
        'book' => (string)$activity['book_slug'],
        'level' => (string)$activity['level_slug'],
        'level_id' => (int)$activity['level_id'],
        'unit_id' => (int)$activity['unit_id'],
        'lesson_id' => (int)$activity['lesson_id'],
        'lesson' => $displayLessonNumber,
    ]);

    $_SESSION['last_learning_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <title>Flashcards | EnglishSpeak</title>

    <style>
        :root{
            --blue:#198fe3;
            --blue-dark:#0868c7;
            --blue-soft:#eaf5ff;
            --page:#f4f8fc;
            --card:#fff;
            --text:#15314b;
            --muted:#718399;
            --line:#dfe8f0;
            --shadow:0 7px 22px rgba(31,71,108,.10);
            --width:520px;
        }
        *{box-sizing:border-box}
        html,body{
            margin:0;
            min-height:100%;
            font-family:"Segoe UI",Tahoma,Arial,sans-serif;
            background:var(--page);
            color:var(--text)
        }
        body{display:flex;justify-content:center}
        button,a{font:inherit;-webkit-tap-highlight-color:transparent}
        .app{
            width:min(100%,var(--width));
            min-height:100dvh;
            padding:0 14px 24px;
            background:#fff;
            box-shadow:0 0 28px rgba(30,79,115,.08)
        }
        .topbar{
            position:sticky;
            top:0;
            z-index:40;
            display:grid;
            grid-template-columns:46px minmax(0,1fr) 46px;
            align-items:center;
            gap:9px;
            min-height:76px;
            margin:0 -14px 14px;
            padding:12px 14px;
            background:linear-gradient(135deg,#3488ef,#17b8e4);
            color:#fff;
            box-shadow:0 5px 15px rgba(31,135,210,.22)
        }
        .back-link,.shuffle{
            display:grid;
            width:44px;
            height:44px;
            place-items:center;
            border:0;
            border-radius:50%;
            background:rgba(255,255,255,.15);
            color:#fff;
            text-decoration:none;
            font-size:24px;
            font-weight:850;
            cursor:pointer
        }
        .shuffle{font-size:20px}
        .shuffle.active{background:#fff;color:var(--blue-dark)}
        .heading{text-align:center;min-width:0}
        .heading strong{
            display:block;
            font-size:22px;
            line-height:1.15
        }
        .heading small{
            display:block;
            margin-top:4px;
            color:rgba(255,255,255,.92);
            font-size:12px;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis
        }
        .lesson-intro{
            display:grid;
            grid-template-columns:66px minmax(0,1fr);
            align-items:center;
            gap:14px;
            margin-bottom:15px;
            padding:16px;
            border-radius:20px;
            background:linear-gradient(135deg,#edf6ff,#e6f1ff)
        }
        .lesson-intro__icon{
            width:62px;
            height:70px;
            display:grid;
            place-items:center;
            border-radius:14px;
            font-size:42px
        }
        .lesson-intro strong{
            display:block;
            color:#111;
            font-size:16px
        }
        .lesson-intro h2{
            margin:4px 0 0;
            color:var(--blue-dark);
            font-size:20px
        }
        .lesson-intro p{
            margin:6px 0 0;
            color:#405870;
            font-size:13px;
            line-height:1.4
        }
        .progress-row{
            display:flex;
            justify-content:space-between;
            gap:10px;
            color:#344c64;
            font-size:13px;
            font-weight:750
        }
        .progress-track{
            height:9px;
            overflow:hidden;
            margin:8px 0 14px;
            border-radius:999px;
            background:#dceaf5
        }
        .progress-fill{
            width:0;
            height:100%;
            border-radius:inherit;
            background:linear-gradient(90deg,#1c7ce4,#18a9e7);
            transition:width .22s ease
        }
        .auto-box{
            display:grid;
            grid-template-columns:1fr auto;
            align-items:center;
            gap:9px;
            margin-bottom:14px
        }
        .auto-button{
            min-height:46px;
            padding:0 15px;
            border:1px solid #c9dceb;
            border-radius:14px;
            background:#fff;
            color:var(--text);
            font-size:13px;
            font-weight:850;
            cursor:pointer
        }
        .auto-button.active{border-color:#ef4444;color:#dc2626}
        .speed{display:flex;gap:5px}
        .speed button{
            min-height:38px;
            padding:0 9px;
            border:1px solid #c9dceb;
            border-radius:11px;
            background:#fff;
            color:var(--text);
            font-size:10px;
            font-weight:800;
            cursor:pointer
        }
        .speed button.active{
            border-color:var(--blue);
            background:var(--blue-soft);
            color:var(--blue-dark)
        }
        .stage{position:relative}
        .study-card{
            position:relative;
            width:100%;
            height:calc(100dvh - 365px);
            min-height:390px;
            max-height:590px;
            border:0;
            background:transparent
        }
        .face{
            position:absolute;
            inset:0;
            display:flex;
            flex-direction:column;
            align-items:center;
            justify-content:center;
            overflow:hidden;
            border:1px solid #e4eaf0;
            border-radius:22px;
            background:#fff;
            box-shadow:var(--shadow);
            transition:opacity .22s ease,transform .22s ease
        }
        .front{z-index:2;opacity:1;visibility:visible;pointer-events:auto;transform:scale(1)}
        .card-back{
            z-index:1;
            opacity:0;
            visibility:hidden;
            pointer-events:none;
            padding:26px;
            text-align:center;
            transform:scale(.97)
        }
        .study-card.flipped .front{
            z-index:1;
            opacity:0;
            visibility:hidden;
            pointer-events:none;
            transform:scale(.97)
        }
        .study-card.flipped .card-back{
            z-index:2;
            opacity:1;
            visibility:visible;
            pointer-events:auto;
            transform:scale(1)
        }
        .image-button{
            display:grid;
            width:100%;
            height:100%;
            place-items:center;
            padding:22px 22px 72px;
            border:0;
            background:#fff;
            cursor:pointer
        }
        .image-button img{max-width:300px;max-height:300px;width:92%;height:92%;object-fit:contain}
        .fallback{color:var(--blue);font-size:112px;font-weight:900}
        .word{
            margin:0 0 8px;
            color:var(--blue-dark);
            font-size:clamp(42px,13vw,68px);
            line-height:1.05
        }
        .ipa{min-height:26px;color:#126fc7;font-size:20px;font-weight:700}
        .meaning{margin:14px 0 0;color:#263f56;font-size:24px;font-weight:700}
        .example{
            margin:20px 0 0;
            padding:11px 14px;
            border:1px solid #d5e5f6;
            border-radius:12px;
            background:#edf6ff;
            color:#3d6591;
            font-size:15px;
            line-height:1.5
        }
        .card-back>*{max-width:100%}
        .listen{
            min-height:46px;
            margin-top:22px;
            padding:0 18px;
            border:0;
            border-radius:14px;
            background:var(--blue);
            color:#fff;
            font-weight:850;
            cursor:pointer
        }
        .tap-hint{
            position:absolute;
            left:0;
            right:0;
            bottom:14px;
            color:var(--muted);
            font-size:12px;
            text-align:center;
            pointer-events:none
        }
        .controls{
            display:grid;
            grid-template-columns:1fr 1.15fr 1fr;
            gap:9px;
            margin-top:13px
        }
        .control{
            min-height:50px;
            border:1px solid #cbddeb;
            border-radius:14px;
            background:#fff;
            color:var(--text);
            font-size:13px;
            font-weight:850;
            cursor:pointer
        }
        .control.primary{
            border-color:var(--blue);
            background:linear-gradient(135deg,#237fe1,#159ddd);
            color:#fff
        }
        .control:disabled{opacity:.45;cursor:not-allowed}
        .finish{
            display:none;
            min-height:calc(100dvh - 110px);
            padding:38px 18px 24px;
            align-items:center;
            justify-content:center;
            flex-direction:column;
            text-align:center
        }
        .finish.show{display:flex}
        .finish__icon{font-size:68px}
        .finish h2{
            margin:15px 0 8px;
            color:#123e62;
            font-size:36px
        }
        .finish>p{
            margin:0;
            color:var(--muted);
            font-size:16px;
            line-height:1.5
        }
        .finish-summary{
            width:100%;
            margin-top:24px;
            padding:4px 18px;
            border:1px solid #d9e4ed;
            border-radius:18px;
            background:#fff;
            box-shadow:var(--shadow)
        }
        .finish-row{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:12px;
            min-height:62px;
            border-bottom:1px solid #e4ebf1;
            font-size:16px
        }
        .finish-row:last-child{border-bottom:0}
        .finish-row strong{color:var(--blue-dark);font-size:19px}
        .finish-message{
            width:100%;
            margin-top:16px;
            padding:16px;
            border:1px solid #bde7c8;
            border-radius:17px;
            background:#eefbf1;
            color:#16823b;
            font-size:15px;
            font-weight:750;
            line-height:1.45
        }
        .finish-actions{
            display:grid;
            grid-template-columns:1fr;
            gap:10px;
            width:100%;
            margin-top:18px
        }
        .finish-actions .control{min-height:54px;font-size:15px}
        .empty{
            padding:50px 20px;
            border-radius:20px;
            background:#fff;
            text-align:center
        }
        @media(max-width:430px){
            .app{padding-left:11px;padding-right:11px}
            .topbar{margin-left:-11px;margin-right:-11px;padding-left:11px;padding-right:11px}
            .lesson-intro{grid-template-columns:58px minmax(0,1fr);gap:11px;padding:14px}
            .lesson-intro__icon{width:56px;height:62px;font-size:38px}
            .lesson-intro h2{font-size:18px}
            .study-card{height:calc(100dvh - 365px);min-height:365px}
            .word{font-size:clamp(38px,12vw,56px)}
            .meaning{font-size:21px}
            .controls{grid-template-columns:1fr 1.05fr 1fr}
        }
        @media(max-width:370px){
            .auto-box{grid-template-columns:1fr}
            .speed{justify-content:space-between}
            .speed button{flex:1}
            .study-card{height:calc(100dvh - 410px);min-height:340px}
            .control{font-size:12px}
        }
        @media(prefers-reduced-motion:reduce){
            .face,.progress-fill{transition:none}
        }

        .lesson-intro--minimal{
            grid-template-columns:52px minmax(0,1fr);
            min-height:72px;
            padding:12px 14px;
        }
        .lesson-intro--minimal .lesson-intro__icon{
            width:48px;
            height:48px;
            font-size:30px;
        }
        .lesson-intro--minimal strong{
            font-size:18px;
        }
    
/* EnglishSpeak XP popup */
.xp-popup {
    position: fixed;
    z-index: 10000;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: rgba(18, 49, 74, .38);
    backdrop-filter: blur(5px);
}
.xp-popup.show { display: flex; }
.xp-popup__card {
    width: min(100%, 350px);
    padding: 24px 20px 20px;
    border-radius: 24px;
    background: #fff;
    box-shadow: 0 18px 50px rgba(18, 49, 74, .24);
    text-align: center;
    animation: xpPopupIn .25s ease-out;
}
.xp-popup__icon {
    width: 76px;
    height: 76px;
    display: grid;
    place-items: center;
    margin: 0 auto 10px;
    border-radius: 50%;
    background: linear-gradient(135deg, #fff6bf, #ffe06e);
    font-size: 42px;
}
.xp-popup__title {
    margin: 0;
    color: #15314b;
    font-size: 27px;
    line-height: 1.2;
}
.xp-popup__text {
    margin: 7px 0 0;
    color: #718399;
    font-size: 14px;
}
.xp-popup__score {
    margin: 17px 0;
    color: #f39c12;
    font-size: 36px;
    font-weight: 900;
    line-height: 1;
}
.xp-popup__score:empty { display:none; }
.xp-popup__button {
    width: 100%;
    min-height: 52px;
    border: 0;
    border-radius: 15px;
    background: linear-gradient(135deg, #237fe1, #159ddd);
    color: #fff;
    font-weight: 850;
    cursor: pointer;
}
@keyframes xpPopupIn {
    from { opacity: 0; transform: translateY(14px) scale(.96); }
    to { opacity: 1; transform: translateY(0) scale(1); }
}

</style>
</head>

<body>
<main class="app">
    <?php if ($isPreview): ?>
        <div style="margin:12px 0;padding:10px 14px;border:1px solid #bfdbfe;border-radius:14px;background:#eff6ff;color:#1d4ed8;font-size:13px;font-weight:700;text-align:center">
            Preview mode — Không lưu XP hoặc tiến trình học sinh.
        </div>
    <?php endif; ?>
    <header class="topbar">
        <a class="back-link" href="<?= htmlspecialchars($backUrl, ENT_QUOTES, 'UTF-8') ?>" aria-label="Quay lại">←</a>

        <div class="heading">
            <strong>Unit <?= $displayUnitNumber ?></strong>
            <small><?= htmlspecialchars((string)$activity['unit_title'], ENT_QUOTES, 'UTF-8') ?></small>
        </div>

        <button class="shuffle" id="shuffleButton" type="button" title="Đảo thẻ" aria-label="Đảo thẻ">🔀</button>
    </header>

    <?php if ($cards !== []): ?>
        <section class="lesson-intro lesson-intro--minimal">
            <div class="lesson-intro__icon" aria-hidden="true">🃏</div>
            <div>
                <strong>Flashcards</strong>
            </div>
        </section>
    <?php endif; ?>

    <?php if ($cards === []): ?>
        <section class="empty">
            <h2>Chưa có từ vựng</h2>
            <p>Hoạt động này chưa có thẻ đang hoạt động.</p>
        </section>
    <?php else: ?>
        <section id="gameArea">
            <div class="progress-row">
                <span id="progressLabel">1 / <?= count($cards) ?></span>
                <span id="modeLabel">Bình thường</span>
            </div>

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

            <div class="auto-box">
                <button class="auto-button" id="autoButton" type="button">▶ Tự động</button>

                <div class="speed" aria-label="Tốc độ tự động">
                    <button type="button" data-speed="slow">Chậm</button>
                    <button class="active" type="button" data-speed="normal">Vừa</button>
                    <button type="button" data-speed="fast">Nhanh</button>
                </div>
            </div>

            <div class="stage">
                <div class="study-card" id="studyCard">
                    <section class="face front">
                        <button class="image-button" id="imageButton" type="button">
                            <img id="cardImage" alt="" hidden>
                            <span class="fallback" id="fallbackLetter">A</span>
                        </button>
                        <div class="tap-hint">Chạm vào hình để nghe phát âm</div>
                    </section>

                    <section class="face card-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">🔊 Nghe phát âm</button>
                    </section>
                </div>
            </div>

            <div class="controls">
                <button class="control" id="previousButton" type="button">← Trước</button>
                <button class="control primary" id="flipButton" type="button">Lật thẻ</button>
                <button class="control" id="nextButton" type="button">Tiếp →</button>
            </div>
        </section>

        <section class="finish" id="finishScreen">
            <div class="finish__icon" aria-hidden="true">🎉</div>
            <h2>Finished!</h2>

            <div class="finish-summary">
                <div class="finish-row">
                    <span>Thẻ đã xem</span>
                    <strong><?= count($cards) ?> / <?= count($cards) ?></strong>
                </div>
                <div class="finish-row">
                    <span>Điểm</span>
                    <strong>100/100</strong>
                </div>
                <div class="finish-row" id="finishXpRow" hidden>
                    <span>XP kiếm được</span>
                    <strong id="finishXpValue"></strong>
                </div>
            </div>

            <div class="finish-actions">
                <?php if ($nextActivityUrl !== ''): ?>
                    <a
                        class="control primary"
                        id="nextActivityButton"
                        style="display:grid;place-items:center;text-decoration:none"
                        href="<?= htmlspecialchars($nextActivityUrl, ENT_QUOTES, 'UTF-8') ?>"
                    >
                        → Next
                    </a>
                <?php endif; ?>

                <button class="control<?= $nextActivityUrl !== '' ? '' : ' primary' ?>" id="replayButton" type="button">↻ Again</button>

                <a
                    class="control"
                    style="display:grid;place-items:center;text-decoration:none"
                    href="<?= htmlspecialchars($backUrl, ENT_QUOTES, 'UTF-8') ?>"
                >
                    ☰ Back
                </a>
            </div>
        </section>
    <?php endif; ?>
</main>


<?php if (!$isPreview): ?>
<div class="xp-popup" id="xpPopup" role="dialog" aria-modal="true" aria-labelledby="xpPopupTitle">
    <div class="xp-popup__card">
        <div class="xp-popup__icon" aria-hidden="true">⭐</div>
        <h2 class="xp-popup__title" id="xpPopupTitle">Great!</h2>
        <p class="xp-popup__text" id="xpPopupText"></p>
        <div class="xp-popup__score" id="xpPopupScore"></div>
        <button class="xp-popup__button" id="xpPopupButton" type="button">View Result</button>
    </div>
</div>
<?php endif; ?>

<?php if ($cards !== []): ?>
<script>

function showXpPopup(result){
    const popup = document.getElementById('xpPopup');
    const title = document.getElementById('xpPopupTitle');
    const text = document.getElementById('xpPopupText');
    const score = document.getElementById('xpPopupScore');

    if (!popup || !title || !text || !score || !result) {
        return;
    }

    const xpAdded = Number(
        result.xp_added
        ?? result.xp_awarded
        ?? result.xp_earned
        ?? result.awarded_xp
        ?? result.xp
        ?? 0
    );
    const eventType = String(
        result.xp_event_type
        ?? result.event_type
        ?? result.xp_type
        ?? ''
    );

    if (xpAdded > 0) {
        title.textContent = 'Great!';
        text.hidden = false;
        score.textContent = `+${xpAdded} XP`;

        if (eventType === 'completion') {
            text.textContent = 'Completion Reward';
        } else if (eventType === 'new_best') {
            text.textContent = 'New Best Reward';
        } else {
            text.textContent = 'Practice Reward';
        }
    } else {
        /*
         * Đã hết Practice XP trong ngày:
         * vẫn khen và hiển thị kết quả học tập, không nhắc hết XP.
         */
        title.textContent = 'Great!';
        text.textContent = '';
        text.hidden = true;
        score.textContent = '100%';
    }

    popup.classList.add('show');
}

function hideXpPopup(){
    const popup = document.getElementById('xpPopup');
    if (popup) {
        popup.classList.remove('show');
    }
}

const isPreview = <?= $isPreview ? 'true' : 'false' ?>;
const activityId = <?= (int)$activityId ?>;
const nextActivityUrl = <?= json_encode(
    $nextActivityUrl,
    JSON_UNESCAPED_UNICODE
    | JSON_UNESCAPED_SLASHES
    | JSON_HEX_TAG
    | JSON_HEX_AMP
    | JSON_HEX_APOS
    | JSON_HEX_QUOT
) ?>;
const lessonFinishedUrl = <?= json_encode(
    $lessonFinishedUrl,
    JSON_UNESCAPED_UNICODE
    | JSON_UNESCAPED_SLASHES
    | JSON_HEX_TAG
    | JSON_HEX_AMP
    | JSON_HEX_APOS
    | JSON_HEX_QUOT
) ?>;

let latestProgressResult = null;

document.getElementById('xpPopupButton')?.addEventListener('click', () => {
    // Chỉ đóng popup để học sinh xem trang kết quả.
    // Việc chuyển sang Activity kế tiếp hoặc Lesson Completed
    // sẽ do nút "Tiếp tục" ở trang kết quả xử lý như trước.
    hideXpPopup();
});

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 activeAudio = null;
let autoTimer = null;
let isAuto = false;
let isShuffled = false;
let autoPhase = 'front';
let autoSpeed = 'normal';
let savingProgress = false;
let progressSavedForRun = false;
let startedAt = Date.now();

const timings = {
    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 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 imageButton = document.getElementById('imageButton');
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('[data-speed]')];
const progressLabel = document.getElementById('progressLabel');
const progressFill = document.getElementById('progressFill');
const modeLabel = document.getElementById('modeLabel');
const replayButton = document.getElementById('replayButton');

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

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

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

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

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

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

    stopAudio();

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

    speakFallback(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
        ? 'Hoàn thành →'
        : 'Tiếp →';

    const modes = [];
    if (isShuffled) modes.push('Đảo thẻ');
    if (isAuto) modes.push('Tự động');
    modeLabel.textContent = modes.length ? modes.join(' • ') : 'Bình thường';
}

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

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

    stopAuto();
    currentIndex--;
    renderCard();
}

function moveNext() {
    stopAuto();

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

    currentIndex++;
    renderCard();
}

async function saveProgress() {
    if (isPreview || savingProgress || progressSavedForRun) {
        return null;
    }

    savingProgress = true;

    try {
        const elapsed = Date.now() - startedAt;

        const response = await fetch('/EnglishSpeak/api/save-activity-progress.php', {
            method: 'POST',
            credentials: 'same-origin',
            cache: 'no-store',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                activity_id: activityId,
                score: 100,
                duration: elapsed,
                completed: true,
                passing_score: 80,
                preview: false
            })
        });

        const result = await response.json().catch(() => null);

        if (!response.ok || !result || result.ok === false) {
            throw new Error(result?.message || 'Could not save progress.');
        }

        progressSavedForRun = true;
        return result;
    } catch (error) {
        console.warn('Could not save Flashcards progress:', error);
        return null;
    } finally {
        savingProgress = false;
    }
}

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

    const progressResult = await saveProgress();
    latestProgressResult = progressResult;

    if (!isPreview && progressResult) {
        const xpAdded = Number(
            progressResult.xp_added
            ?? progressResult.xp_awarded
            ?? progressResult.xp_earned
            ?? progressResult.awarded_xp
            ?? progressResult.xp
            ?? 0
        );
        const xpRow = document.getElementById('finishXpRow');
        const xpValue = document.getElementById('finishXpValue');
        if (xpRow && xpValue && xpAdded > 0) {
            xpValue.textContent = `+${xpAdded} XP`;
            xpRow.hidden = false;
        }

        showXpPopup(progressResult);
    }
}

function replayGame() {
    stopAuto();
    currentIndex = 0;
    startedAt = Date.now();
    savingProgress = false;
    progressSavedForRun = false;
    gameArea.hidden = false;
    finishScreen.classList.remove('show');
    const xpRow = document.getElementById('finishXpRow');
    if (xpRow) xpRow.hidden = true;
    hideXpPopup();
    renderCard();
}

function shuffleCards() {
    stopAuto();
    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 scheduleAuto(delay) {
    if (!isAuto) {
        return;
    }

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

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

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

    const timing = timings[autoSpeed];

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

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

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

    currentIndex++;
    autoPhase = 'front';
    renderCard();
    scheduleAuto(450);
}

function startAuto() {
    isAuto = true;
    autoPhase = 'front';
    autoButton.classList.add('active');
    autoButton.textContent = '⏸ Tạm dừng';
    renderCard();
    scheduleAuto(400);
}

function stopAuto() {
    isAuto = false;
    autoPhase = 'front';
    autoButton.classList.remove('active');
    autoButton.textContent = '▶ Tự động';

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

function toggleAuto() {
    isAuto ? stopAuto() : 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);
replayButton.addEventListener('click', replayGame);

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

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

        if (isAuto) {
            autoPhase = 'front';
            renderCard();
            scheduleAuto(300);
        }
    });
});

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>
