<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Activity Preview
 * File: teacher/activity-preview/index.php
 *
 * Preview only:
 * - Reads Activity
 * - Reads Activity Settings
 * - Reads linked learning content
 * - Renders a teacher-only student preview
 * - Does not save scores, XP, progress or recordings
 */

require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$pdo = getDbConnection();

$pageTitle = 'Activity Preview';
$pageSubtitle = 'Preview the student learning experience';
$activeTeacherNav = 'content';

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

function eapTableExists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    return (int)$stmt->fetchColumn() > 0;
}

function eapColumns(PDO $pdo, string $table): array
{
    if (!eapTableExists($pdo, $table)) {
        return [];
    }

    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);

    return array_column($rows, null, 'Field');
}

function eapFirstColumn(array $columns, array $candidates): ?string
{
    foreach ($candidates as $candidate) {
        if (isset($columns[$candidate])) {
            return $candidate;
        }
    }

    return null;
}

function eapTypeLabel(string $type): string
{
    return match ($type) {
        'flashcards' => 'Flashcards',
        'listen_repeat', 'pronunciation' => 'Listen & Repeat',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'quiz' => 'Quiz',
        'speaking' => 'Speaking',
        'sentence_builder' => 'Sentence Builder',
        'reading' => 'Reading',
        'writing' => 'Writing',
        'worksheet' => 'Worksheet',
        'vocabulary', 'word_list' => 'Word List',
        default => ucwords(str_replace(['_', '-'], ' ', $type ?: 'Activity')),
    };
}

function eapTypeIcon(string $type): string
{
    return match ($type) {
        'flashcards' => '🃏',
        'listen_repeat', 'pronunciation' => '🔊',
        'memory' => '🧠',
        'matching' => '🧩',
        'quiz' => '🎯',
        'speaking' => '🎤',
        'sentence_builder' => '🧱',
        'reading' => '📚',
        'writing' => '✏️',
        'worksheet' => '📄',
        'vocabulary', 'word_list' => '📄',
        default => '🎮',
    };
}

function eapAssetUrl(string $path): string
{
    $path = trim($path);

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

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

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

function eapBool(array $settings, string $key, bool $default = false): bool
{
    return array_key_exists($key, $settings)
        ? (bool)$settings[$key]
        : $default;
}

function eapInt(array $settings, string $key, int $default): int
{
    return isset($settings[$key]) ? (int)$settings[$key] : $default;
}

$activityColumns = eapColumns($pdo, 'activities');
$lessonColumns = eapColumns($pdo, 'lessons');
$unitColumns = eapColumns($pdo, 'units');
$levelColumns = eapColumns($pdo, 'levels');
$bookColumns = eapColumns($pdo, 'books');

if ($activityId <= 0 || $activityColumns === []) {
    http_response_code(404);
    exit('Activity not found.');
}

$titleColumn = eapFirstColumn($activityColumns, ['title', 'name']);
$typeColumn = eapFirstColumn($activityColumns, ['activity_type', 'type']);
$descriptionColumn = eapFirstColumn($activityColumns, ['instructions', 'description']);

$titleExpression = $titleColumn ? "a.`{$titleColumn}`" : "'Activity'";
$typeExpression = $typeColumn ? "a.`{$typeColumn}`" : "'activity'";
$descriptionExpression = $descriptionColumn ? "a.`{$descriptionColumn}`" : "''";
$setExpression = isset($activityColumns['flashcard_set_id'])
    ? 'a.flashcard_set_id'
    : 'NULL';
$xpExpression = isset($activityColumns['xp_reward'])
    ? 'a.xp_reward'
    : '0';
$passExpression = isset($activityColumns['passing_score'])
    ? 'a.passing_score'
    : '0';

$stmt = $pdo->prepare(
    "SELECT
        a.id,
        a.lesson_id,
        {$titleExpression} AS activity_title,
        {$typeExpression} AS activity_type,
        {$descriptionExpression} AS activity_description,
        {$setExpression} AS flashcard_set_id,
        {$xpExpression} AS xp_reward,
        {$passExpression} AS passing_score,
        l.lesson_number,
        l.title AS lesson_title,
        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,
        lv.id AS level_id,
        lv.name AS level_name,
        b.id AS book_id,
        b.name AS book_name
     FROM activities a
     INNER JOIN lessons l ON l.id = a.lesson_id
     INNER JOIN units u ON u.id = l.unit_id
     INNER JOIN levels lv ON lv.id = u.level_id
     INNER JOIN books b ON b.id = u.book_id
     WHERE a.id = ?
     LIMIT 1"
);
$stmt->execute([$activityId]);
$activity = $stmt->fetch(PDO::FETCH_ASSOC);

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

$activityType = (string)$activity['activity_type'];

/* ---------- Activity Settings ---------- */

$settings = [];

if (eapTableExists($pdo, 'activity_settings')) {
    $settingsStmt = $pdo->prepare(
        'SELECT settings_json
         FROM activity_settings
         WHERE activity_id = ?
         LIMIT 1'
    );
    $settingsStmt->execute([$activityId]);

    $settingsJson = $settingsStmt->fetchColumn();

    if (is_string($settingsJson) && $settingsJson !== '') {
        $decoded = json_decode($settingsJson, true);

        if (is_array($decoded)) {
            $settings = $decoded;
        }
    }
}

$resourceType = trim((string)($settings['resource_type'] ?? ''));
$resourceId = max(
    0,
    (int)($settings['resource_id'] ?? $activity['flashcard_set_id'] ?? 0)
);

$xpReward = eapInt(
    $settings,
    'xp_reward',
    (int)($activity['xp_reward'] ?? 0)
);

$passingScore = eapInt(
    $settings,
    'reward_passing_score',
    eapInt($settings, 'passing_score', (int)($activity['passing_score'] ?? 0))
);

$studentInstructions = trim(
    (string)($settings['student_instructions'] ?? $activity['activity_description'] ?? '')
);

$currentUnitDisplay = trim(
    (string)$activity['unit_number']
    . ((string)$activity['unit_title'] !== ''
        ? ' - ' . (string)$activity['unit_title']
        : '')
);

/* ---------- Learning Content ---------- */

$contentTitle = '';
$contentItems = [];

if ($resourceType === '') {
    $resourceType = in_array(
        $activityType,
        ['flashcards', 'listen_repeat', 'pronunciation', 'memory', 'matching', 'vocabulary', 'word_list'],
        true
    )
        ? 'flashcard_set'
        : ($activityType === 'quiz'
            ? 'quiz_set'
            : (in_array($activityType, ['speaking', 'sentence_builder'], true)
                ? 'sentence_set'
                : ''));
}

if ($resourceType === 'flashcard_set' && $resourceId > 0 && eapTableExists($pdo, 'flashcard_sets')) {
    $setColumns = eapColumns($pdo, 'flashcard_sets');
    $setLabelColumn = eapFirstColumn($setColumns, ['title', 'name', 'set_name', 'label']);

    if ($setLabelColumn) {
        $setStmt = $pdo->prepare(
            "SELECT `{$setLabelColumn}`
             FROM flashcard_sets
             WHERE id = ?
             LIMIT 1"
        );
        $setStmt->execute([$resourceId]);
        $contentTitle = (string)($setStmt->fetchColumn() ?: '');
    }

    $relationTable = null;

    foreach (['flashcard_set_words', 'flashcard_set_items', 'set_words'] as $candidate) {
        if (eapTableExists($pdo, $candidate)) {
            $relationTable = $candidate;
            break;
        }
    }

    if ($relationTable && eapTableExists($pdo, 'words')) {
        $relationColumns = eapColumns($pdo, $relationTable);
        $wordColumns = eapColumns($pdo, 'words');

        $setFk = eapFirstColumn($relationColumns, ['flashcard_set_id', 'set_id']);
        $wordFk = eapFirstColumn($relationColumns, ['word_id', 'vocabulary_id']);
        $wordLabel = eapFirstColumn(
            $wordColumns,
            ['word', 'term', 'english', 'text', 'title', 'name']
        );
        $wordImage = eapFirstColumn(
            $wordColumns,
            ['image', 'image_path', 'image_url', 'thumbnail']
        );
        $wordIpa = eapFirstColumn(
            $wordColumns,
            ['ipa', 'phonetic', 'phonetics']
        );
        $wordMeaning = eapFirstColumn(
            $wordColumns,
            ['meaning_vi', 'vietnamese', 'meaning', 'translation']
        );
        $wordAudio = eapFirstColumn(
            $wordColumns,
            ['audio', 'audio_path', 'audio_url', 'tts_audio']
        );

        if ($setFk && $wordFk && $wordLabel) {
            $imageSelect = $wordImage
                ? "w.`{$wordImage}` AS item_image"
                : "'' AS item_image";

            $ipaSelect = $wordIpa
                ? "w.`{$wordIpa}` AS item_ipa"
                : "'' AS item_ipa";

            $meaningSelect = $wordMeaning
                ? "w.`{$wordMeaning}` AS item_meaning"
                : "'' AS item_meaning";

            $audioSelect = $wordAudio
                ? "w.`{$wordAudio}` AS item_audio"
                : "'' AS item_audio";

            $orderSql = isset($relationColumns['sort_order'])
                ? 'r.sort_order, r.id'
                : 'r.id';

            $itemStmt = $pdo->prepare(
                "SELECT
                    w.id,
                    w.`{$wordLabel}` AS item_text,
                    {$imageSelect},
                    {$ipaSelect},
                    {$meaningSelect},
                    {$audioSelect}
                 FROM `{$relationTable}` r
                 INNER JOIN words w ON w.id = r.`{$wordFk}`
                 WHERE r.`{$setFk}` = ?
                 ORDER BY {$orderSql}"
            );
            $itemStmt->execute([$resourceId]);
            $contentItems = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
}

if (
    $resourceType === 'sentence_set'
    && $resourceId > 0
    && eapTableExists($pdo, 'sentence_sets')
) {
    $setColumns = eapColumns($pdo, 'sentence_sets');
    $labelColumn = eapFirstColumn(
        $setColumns,
        ['title', 'name', 'set_name', 'label']
    );

    if ($labelColumn !== null) {
        $setStmt = $pdo->prepare(
            "SELECT `{$labelColumn}`
             FROM sentence_sets
             WHERE id = ?
             LIMIT 1"
        );
        $setStmt->execute([$resourceId]);
        $contentTitle = (string)($setStmt->fetchColumn() ?: '');
    }

    $sentenceRelationTable = null;

    foreach (['sentence_set_sentences', 'sentence_set_items'] as $candidate) {
        if (eapTableExists($pdo, $candidate)) {
            $sentenceRelationTable = $candidate;
            break;
        }
    }

    if (
        $sentenceRelationTable !== null
        && eapTableExists($pdo, 'sentences')
    ) {
        $relationColumns = eapColumns($pdo, $sentenceRelationTable);
        $sentenceColumns = eapColumns($pdo, 'sentences');

        $setFk = eapFirstColumn(
            $relationColumns,
            ['sentence_set_id', 'set_id']
        );
        $sentenceFk = eapFirstColumn(
            $relationColumns,
            ['sentence_id', 'item_id']
        );
        $sentenceTextColumn = eapFirstColumn(
            $sentenceColumns,
            ['sentence_text', 'sentence', 'text', 'content']
        );
        $sentenceImageColumn = eapFirstColumn(
            $sentenceColumns,
            ['image_path', 'image', 'image_url']
        );
        $sentenceIpaColumn = eapFirstColumn(
            $sentenceColumns,
            ['ipa', 'phonetic']
        );
        $sentenceMeaningColumn = eapFirstColumn(
            $sentenceColumns,
            ['vietnamese_meaning', 'meaning_vi', 'vietnamese', 'meaning']
        );
        $sentenceAudioColumn = eapFirstColumn(
            $sentenceColumns,
            ['audio_us_path', 'audio_path', 'audio', 'audio_url']
        );

        if (
            $setFk !== null
            && $sentenceFk !== null
            && $sentenceTextColumn !== null
        ) {
            $imageSelect = $sentenceImageColumn !== null
                ? "s.`{$sentenceImageColumn}` AS item_image"
                : "'' AS item_image";

            $ipaSelect = $sentenceIpaColumn !== null
                ? "s.`{$sentenceIpaColumn}` AS item_ipa"
                : "'' AS item_ipa";

            $meaningSelect = $sentenceMeaningColumn !== null
                ? "s.`{$sentenceMeaningColumn}` AS item_meaning"
                : "'' AS item_meaning";

            $audioSelect = $sentenceAudioColumn !== null
                ? "s.`{$sentenceAudioColumn}` AS item_audio"
                : "'' AS item_audio";

            $orderColumn = eapFirstColumn(
                $relationColumns,
                ['display_order', 'sort_order', 'order_no', 'position']
            );

            $orderSql = $orderColumn !== null
                ? "r.`{$orderColumn}` ASC, r.id ASC"
                : 'r.id ASC';

            // Sentence Library records may use different status labels
            // across project versions. The Sentence Set relation itself is
            // the source of truth, so do not filter valid linked sentences.
            $sentenceStatusWhere = '';

            $itemStmt = $pdo->prepare(
                "SELECT
                    s.id,
                    s.`{$sentenceTextColumn}` AS item_text,
                    {$imageSelect},
                    {$ipaSelect},
                    {$meaningSelect},
                    {$audioSelect}
                 FROM `{$sentenceRelationTable}` r
                 INNER JOIN sentences s
                    ON s.id = r.`{$sentenceFk}`
                 WHERE r.`{$setFk}` = ?
                 {$sentenceStatusWhere}
                 ORDER BY {$orderSql}"
            );
            $itemStmt->execute([$resourceId]);
            $contentItems = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
}

if ($resourceType === 'quiz_set' && $resourceId > 0 && eapTableExists($pdo, 'quiz_sets')) {
    $setColumns = eapColumns($pdo, 'quiz_sets');
    $labelColumn = eapFirstColumn($setColumns, ['title', 'name', 'set_name', 'label']);

    if ($labelColumn) {
        $stmt = $pdo->prepare(
            "SELECT `{$labelColumn}` FROM quiz_sets WHERE id = ? LIMIT 1"
        );
        $stmt->execute([$resourceId]);
        $contentTitle = (string)($stmt->fetchColumn() ?: '');
    }
}

if (
    $contentTitle !== ''
    && preg_match('/^unit\s*\d+(?:\s+vocabulary)?$/i', str_replace('-', ' ', $contentTitle))
) {
    $contentTitle = $currentUnitDisplay;
}

if ($contentTitle === '' && $resourceId > 0) {
    $contentTitle = $currentUnitDisplay;
}

$cardsPerSession = max(1, eapInt($settings, 'cards_per_session', 8));
$pairs = max(2, eapInt($settings, 'pairs', 6));
$previewLimit = match ($activityType) {
    'memory', 'matching' => $pairs,
    'sentence_builder' => max(
        1,
        eapInt(
            $settings,
            'sentence_count',
            eapInt($settings, 'cards_per_session', 8)
        )
    ),
    default => $cardsPerSession,
};

$previewItems = array_slice($contentItems, 0, $previewLimit);

$difficulty = match ($activityType) {
    'vocabulary', 'word_list', 'flashcards' => 'Easy',
    'listen_repeat', 'pronunciation', 'matching', 'memory' => 'Medium',
    'quiz', 'speaking', 'sentence_builder' => 'Advanced',
    default => 'Medium',
};

$estimatedMinutes = match ($activityType) {
    'vocabulary', 'word_list' => max(1, (int)ceil(count($previewItems) / 4)),
    'flashcards' => max(2, (int)ceil(count($previewItems) / 3)),
    'listen_repeat', 'pronunciation', 'speaking' => max(3, count($previewItems)),
    'memory', 'matching' => max(3, (int)ceil(count($previewItems) / 2)),
    'quiz' => max(3, eapInt($settings, 'question_count', 10)),
    'sentence_builder' => max(2, count($previewItems)),
    default => 3,
};

$studentRuntimeMap = [
    'vocabulary' => '../../student/student-runtime/index.php',
    'word_list' => '../../student/student-runtime/index.php',
    'flashcards' => '../../student/student-runtime/index.php',
    'listen_repeat' => '../../student/student-runtime/index.php',
    'pronunciation' => '../../student/student-runtime/index.php',
    'memory' => '../../student/student-runtime/index.php',
    'matching' => '../../student/student-runtime/index.php',
    'quiz' => '../../student/student-runtime/index.php',
    'speaking' => '../../student/student-runtime/index.php',
    'sentence_builder' => '../../student/student-runtime/index.php',
];

$studentRuntimeUrl = ($studentRuntimeMap[$activityType] ?? '../../student/student-runtime/index.php')
    . '?preview=1&activity_id=' . $activityId;

$pageTitle = 'Activity Preview';
$pageSubtitle = (string)$activity['activity_title'];

ob_start();
?>

<style>
.eap-page{display:grid;gap:18px}
.eap-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.eap-kicker{display:block;color:#ea580c;font-size:12px;font-weight:850;letter-spacing:.09em;text-transform:uppercase}
.eap-head h2{margin:4px 0 0;color:#0f172a;font-size:28px}
.eap-path{display:flex;flex-wrap:wrap;gap:6px 10px;margin-top:9px;color:#64748b;font-size:13px}
.eap-actions{display:flex;gap:9px;flex-wrap:wrap}
.eap-banner{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:13px 16px;border:1px solid #bfdbfe;border-radius:14px;background:#eff6ff;color:#1d4ed8}
.eap-banner strong{display:block}
.eap-banner small{display:block;margin-top:3px;color:#3b82f6}
.eap-layout{display:grid;grid-template-columns:minmax(0,1fr) 330px;gap:20px;align-items:start}
.eap-stage{padding:28px;border:1px solid #e5e7eb;border-radius:20px;background:linear-gradient(180deg,#f8fafc,#eef4ff)}
.eap-student-shell{width:min(540px,100%);min-height:720px;margin:0 auto;overflow:hidden;border:1px solid #dbe2ea;border-radius:30px;background:#fff;box-shadow:0 24px 60px rgba(15,23,42,.14)}
.eap-student-top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:15px 17px;border-bottom:1px solid #eef2f7}
.eap-student-top strong{color:#0f172a}
.eap-progress{color:#64748b;font-size:12px;font-weight:750}
.eap-student-content{display:grid;gap:18px;padding:24px}
.eap-instructions{padding:11px 13px;border-radius:12px;background:#fff7ed;color:#9a3412;font-size:13px;line-height:1.5}
.eap-word-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
.eap-word-row{display:flex;align-items:center;gap:11px;padding:13px;border:1px solid #e5e7eb;border-radius:14px;background:#fff}
.eap-thumb{display:grid;place-items:center;width:46px;height:46px;flex:0 0 46px;overflow:hidden;border-radius:11px;background:#f1f5f9;font-size:20px}
.eap-thumb img{width:100%;height:100%;object-fit:cover}
.eap-word-meta{min-width:0}
.eap-word-meta strong{display:block;overflow:hidden;color:#0f172a;text-overflow:ellipsis;white-space:nowrap}
.eap-word-meta small{display:block;margin-top:2px;color:#64748b}
.eap-flashcard{display:grid;gap:16px;text-align:center}
.eap-card-image{display:grid;place-items:center;min-height:270px;overflow:hidden;border:1px solid #e5e7eb;border-radius:22px;background:#f8fafc;font-size:72px}
.eap-card-image img{width:100%;height:270px;object-fit:contain}
.eap-word-large{font-size:32px;font-weight:850;color:#0f172a}
.eap-ipa{color:#64748b;font-size:14px}
.eap-controls{display:flex;justify-content:center;gap:10px;flex-wrap:wrap}
.eap-student-button{min-height:44px;padding:0 17px;border:0;border-radius:13px;background:#2563eb;color:#fff;font:inherit;font-weight:800;cursor:pointer}
.eap-student-button.secondary{background:#eef2ff;color:#3730a3}
.eap-grid-game{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}
.eap-tile{display:grid;place-items:center;min-height:96px;padding:9px;border:1px solid #dbe2ea;border-radius:14px;background:#fff;color:#0f172a;font-weight:800;text-align:center}
.eap-tile img{width:58px;height:58px;object-fit:contain}
.eap-speaking{display:grid;gap:16px;text-align:center}
.eap-mic{display:grid;place-items:center;width:96px;height:96px;margin:12px auto;border-radius:50%;background:#fee2e2;font-size:42px}
.eap-empty{padding:34px 20px;border:1px dashed #cbd5e1;border-radius:16px;background:#fff;color:#64748b;text-align:center;line-height:1.6}
.eap-side{display:grid;gap:14px}
.eap-card{padding:18px;border:1px solid #e5e7eb;border-radius:17px;background:#fff}
.eap-card h3{margin:0 0 12px;color:#0f172a;font-size:16px}
.eap-data{display:grid;gap:10px}
.eap-data-row{display:flex;justify-content:space-between;gap:12px;padding-bottom:9px;border-bottom:1px solid #f1f5f9;color:#64748b;font-size:13px}
.eap-data-row:last-child{padding-bottom:0;border-bottom:0}
.eap-data-row strong{color:#0f172a;text-align:right}
.eap-chip{display:inline-flex;padding:5px 9px;border-radius:999px;background:#eef2ff;color:#4338ca;font-size:11px;font-weight:800}
.eap-runtime-ready{padding:13px;border:1px solid #c7d2fe;border-radius:13px;background:#eef2ff;color:#3730a3;font-size:12px;line-height:1.5}
.eap-runtime-button{display:flex;justify-content:center;align-items:center;min-height:42px;margin-top:11px;border-radius:11px;background:#4f46e5;color:#fff;text-decoration:none;font-weight:800}
@media(max-width:980px){.eap-layout{grid-template-columns:1fr}.eap-side{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:680px){.eap-head{flex-direction:column}.eap-side{grid-template-columns:1fr}.eap-word-list{grid-template-columns:1fr}.eap-grid-game{grid-template-columns:repeat(2,minmax(0,1fr))}.eap-stage{padding:10px}.eap-student-shell{min-height:640px;border-radius:20px}}
</style>

<div class="eap-page">
    <div class="eap-head">
        <div>
            <span class="eap-kicker">Teacher Preview</span>
            <h2><?= eapTypeIcon($activityType) ?> <?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?></h2>

            <div class="eap-path">
                <span><strong><?= htmlspecialchars((string)$activity['book_name'], ENT_QUOTES, 'UTF-8') ?></strong></span>
                <span>›</span>
                <span><?= htmlspecialchars((string)$activity['level_name'], ENT_QUOTES, 'UTF-8') ?></span>
                <span>›</span>
                <span><?= htmlspecialchars((string)$activity['unit_number'], ENT_QUOTES, 'UTF-8') ?></span>
                <span>›</span>
                <span><?= htmlspecialchars((string)$activity['lesson_title'], ENT_QUOTES, 'UTF-8') ?></span>
            </div>
        </div>

        <div class="eap-actions">
            <a
                class="button button-secondary"
                href="../activity-settings/index.php?activity_id=<?= (int)$activityId ?>"
            >
                ← Settings
            </a>

            <a
                class="button button-secondary"
                href="../lesson-activities/index.php?lesson_id=<?= (int)$activity['lesson_id'] ?>"
            >
                Activities
            </a>

            <a
                class="button button-primary"
                href="<?= htmlspecialchars($studentRuntimeUrl, ENT_QUOTES, 'UTF-8') ?>"
            >
                Open Student View
            </a>
        </div>
    </div>

    <div class="eap-banner">
        <div>
            <strong>Preview mode</strong>
            <small>Scores, XP, recordings and student progress are not saved.</small>
        </div>

        <span class="eap-chip"><?= htmlspecialchars(eapTypeLabel($activityType), ENT_QUOTES, 'UTF-8') ?></span>
    </div>

    <div class="eap-layout">
        <main class="eap-stage">
            <div class="eap-student-shell">
                <div class="eap-student-top">
                    <strong><?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?></strong>
                    <span class="eap-progress">
                        <?= count($previewItems) ?> item<?= count($previewItems) === 1 ? '' : 's' ?>
                    </span>
                </div>

                <div class="eap-student-content">
                    <?php if ($studentInstructions !== ''): ?>
                    <div class="eap-instructions">
                        <?= nl2br(htmlspecialchars($studentInstructions, ENT_QUOTES, 'UTF-8')) ?>
                    </div>
                    <?php endif; ?>

                    <?php if ($activityType === 'vocabulary' || $activityType === 'word_list'): ?>
                        <?php if ($previewItems === []): ?>
                            <div class="eap-empty">
                                No words are available in the linked Flashcard Set.
                            </div>
                        <?php else: ?>
                            <div class="eap-word-list">
                                <?php foreach ($previewItems as $item): ?>
                                <div class="eap-word-row">
                                    <div class="eap-thumb">
                                        <?php if ((string)$item['item_image'] !== ''): ?>
                                            <img
                                                src="<?= htmlspecialchars(eapAssetUrl((string)$item['item_image']), ENT_QUOTES, 'UTF-8') ?>"
                                                alt=""
                                            >
                                        <?php else: ?>
                                            🔤
                                        <?php endif; ?>
                                    </div>

                                    <div class="eap-word-meta">
                                        <strong><?= htmlspecialchars((string)$item['item_text'], ENT_QUOTES, 'UTF-8') ?></strong>

                                        <?php if ((string)$item['item_ipa'] !== ''): ?>
                                            <small><?= htmlspecialchars((string)$item['item_ipa'], ENT_QUOTES, 'UTF-8') ?></small>
                                        <?php endif; ?>

                                        <?php if ((string)$item['item_meaning'] !== ''): ?>
                                            <small><?= htmlspecialchars((string)$item['item_meaning'], ENT_QUOTES, 'UTF-8') ?></small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                    <?php elseif ($activityType === 'flashcards'): ?>
                        <?php $first = $previewItems[0] ?? null; ?>

                        <?php if (!$first): ?>
                            <div class="eap-empty">
                                No cards are available in the linked Flashcard Set.
                            </div>
                        <?php else: ?>
                            <div class="eap-flashcard">
                                <div class="eap-card-image" id="previewCardImage">
                                    <?php if ((string)$first['item_image'] !== ''): ?>
                                        <img
                                            src="<?= htmlspecialchars(eapAssetUrl((string)$first['item_image']), ENT_QUOTES, 'UTF-8') ?>"
                                            alt=""
                                        >
                                    <?php else: ?>
                                        🖼️
                                    <?php endif; ?>
                                </div>

                                <div>
                                    <div class="eap-word-large" id="previewCardWord">
                                        <?= htmlspecialchars((string)$first['item_text'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>

                                    <?php if (eapBool($settings, 'show_ipa', true)): ?>
                                    <div class="eap-ipa" id="previewCardIpa">
                                        <?= htmlspecialchars((string)$first['item_ipa'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                    <?php endif; ?>
                                </div>

                                <div class="eap-controls">
                                    <button type="button" class="eap-student-button secondary" id="previewListen">
                                        🔊 Listen
                                    </button>
                                    <button type="button" class="eap-student-button" id="previewNext">
                                        Next
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>

                    <?php elseif (in_array($activityType, ['listen_repeat', 'pronunciation', 'speaking'], true)): ?>
                        <?php $first = $previewItems[0] ?? null; ?>

                        <div class="eap-speaking">
                            <div class="eap-card-image">
                                <?php if ($first && (string)$first['item_image'] !== ''): ?>
                                    <img
                                        src="<?= htmlspecialchars(eapAssetUrl((string)$first['item_image']), ENT_QUOTES, 'UTF-8') ?>"
                                        alt=""
                                    >
                                <?php else: ?>
                                    🎤
                                <?php endif; ?>
                            </div>

                            <div class="eap-word-large">
                                <?= htmlspecialchars((string)($first['item_text'] ?? $activity['activity_title']), ENT_QUOTES, 'UTF-8') ?>
                            </div>

                            <div class="eap-controls">
                                <button type="button" class="eap-student-button secondary">🔊 Listen</button>
                                <button type="button" class="eap-student-button">🎤 Hold to Speak</button>
                            </div>

                            <div class="eap-mic">🎙️</div>
                        </div>

                    <?php elseif (in_array($activityType, ['memory', 'matching'], true)): ?>
                        <?php if ($previewItems === []): ?>
                            <div class="eap-empty">
                                No words are available for this game preview.
                            </div>
                        <?php else: ?>
                            <div class="eap-grid-game">
                                <?php foreach ($previewItems as $item): ?>
                                    <div class="eap-tile">
                                        <?php if ((string)$item['item_image'] !== ''): ?>
                                            <img
                                                src="<?= htmlspecialchars(eapAssetUrl((string)$item['item_image']), ENT_QUOTES, 'UTF-8') ?>"
                                                alt=""
                                            >
                                        <?php else: ?>
                                            <?= htmlspecialchars((string)$item['item_text'], ENT_QUOTES, 'UTF-8') ?>
                                        <?php endif; ?>
                                    </div>

                                    <div class="eap-tile">
                                        <?= htmlspecialchars((string)$item['item_text'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                    <?php elseif ($activityType === 'sentence_builder'): ?>
                        <?php if ($previewItems === []): ?>
                            <div class="eap-empty">
                                No sentences are available in the linked Sentence Set.
                            </div>
                        <?php else: ?>
                            <div class="eap-speaking">
                                <div class="eap-card-image">
                                    <?php
                                    $firstSentence = $previewItems[0] ?? null;
                                    ?>
                                    <?php if ($firstSentence && (string)($firstSentence['item_image'] ?? '') !== ''): ?>
                                        <img
                                            src="<?= htmlspecialchars(
                                                eapAssetUrl((string)$firstSentence['item_image']),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>"
                                            alt=""
                                        >
                                    <?php else: ?>
                                        🧱
                                    <?php endif; ?>
                                </div>

                                <div class="eap-word-large">
                                    <?= htmlspecialchars(
                                        (string)($firstSentence['item_text'] ?? ''),
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </div>

                                <div class="eap-word-list">
                                    <?php foreach ($previewItems as $index => $item): ?>
                                        <div class="eap-word-row">
                                            <div class="eap-thumb">
                                                <?= (int)$index + 1 ?>
                                            </div>
                                            <div class="eap-word-meta">
                                                <strong><?= htmlspecialchars(
                                                    (string)($item['item_text'] ?? ''),
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ) ?></strong>
                                                <?php if ((string)($item['item_meaning'] ?? '') !== ''): ?>
                                                    <small><?= htmlspecialchars(
                                                        (string)$item['item_meaning'],
                                                        ENT_QUOTES,
                                                        'UTF-8'
                                                    ) ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>

                                <div class="eap-controls">
                                    <a
                                        class="eap-student-button"
                                        href="<?= htmlspecialchars(
                                            $studentRuntimeUrl,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>"
                                        style="display:inline-flex;align-items:center;text-decoration:none"
                                    >
                                        Open Student View
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>

                    <?php elseif ($activityType === 'quiz'): ?>
                        <div class="eap-empty">
                            <strong>Quiz Preview</strong><br>
                            The linked Quiz Set is ready for the student player.<br>
                            Full question rendering will be connected when Quiz Set Manager is completed.
                        </div>

                    <?php else: ?>
                        <div class="eap-empty">
                            <strong><?= htmlspecialchars(eapTypeLabel($activityType), ENT_QUOTES, 'UTF-8') ?> Preview</strong><br>
                            This Activity is configured and ready for its student player.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>

        <aside class="eap-side">
            <section class="eap-card">
                <h3>Activity</h3>

                <div class="eap-data">
                    <div class="eap-data-row">
                        <span>Game Template</span>
                        <strong><?= htmlspecialchars(eapTypeLabel($activityType), ENT_QUOTES, 'UTF-8') ?></strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Content</span>
                        <strong><?= htmlspecialchars($contentTitle !== '' ? $contentTitle : 'Not linked', ENT_QUOTES, 'UTF-8') ?></strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Items</span>
                        <strong><?= count($previewItems) ?></strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Difficulty</span>
                        <strong><?= htmlspecialchars($difficulty, ENT_QUOTES, 'UTF-8') ?></strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Estimated Time</span>
                        <strong><?= $estimatedMinutes ?> min</strong>
                    </div>
                </div>
            </section>

            <section class="eap-card">
                <h3>Completion &amp; Rewards</h3>

                <div class="eap-data">
                    <div class="eap-data-row">
                        <span>XP Reward</span>
                        <strong><?= $xpReward ?> XP</strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Passing Score</span>
                        <strong><?= $passingScore ?>%</strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Try Again</span>
                        <strong><?= eapBool($settings, 'allow_retry', true) ? 'Allowed' : 'Disabled' ?></strong>
                    </div>
                </div>
            </section>

            <section class="eap-card">
                <h3>Student Runtime</h3>

                <div class="eap-runtime-ready">
                    Trang này là bản xem nhanh dành cho giáo viên. Nút
                    <strong>Open Student View</strong> đã chuẩn bị sẵn đường dẫn
                    <code>preview=1&amp;activity_id=<?= (int)$activityId ?></code>
                    để kết nối Student Runtime thật ở bước tiếp theo.

                    <a
                        class="eap-runtime-button"
                        href="<?= htmlspecialchars($studentRuntimeUrl, ENT_QUOTES, 'UTF-8') ?>"
                    >
                        Open Student View
                    </a>
                </div>
            </section>

            <section class="eap-card">
                <h3>Preview Notes</h3>

                <div class="eap-data">
                    <div class="eap-data-row">
                        <span>Student progress</span>
                        <strong>Not saved</strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Scores</span>
                        <strong>Not saved</strong>
                    </div>

                    <div class="eap-data-row">
                        <span>Recordings</span>
                        <strong>Not saved</strong>
                    </div>
                </div>
            </section>
        </aside>
    </div>
</div>

<script>
(function () {
    var cards = <?= json_encode(
        array_map(
            static function (array $item): array {
                return [
                    'text' => (string)($item['item_text'] ?? ''),
                    'ipa' => (string)($item['item_ipa'] ?? ''),
                    'image' => eapAssetUrl((string)($item['item_image'] ?? '')),
                    'audio' => eapAssetUrl((string)($item['item_audio'] ?? '')),
                ];
            },
            $previewItems
        ),
        JSON_UNESCAPED_UNICODE
        | JSON_UNESCAPED_SLASHES
        | JSON_HEX_TAG
        | JSON_HEX_AMP
        | JSON_HEX_APOS
        | JSON_HEX_QUOT
    ) ?>;

    var currentIndex = 0;
    var nextButton = document.getElementById('previewNext');
    var listenButton = document.getElementById('previewListen');
    var word = document.getElementById('previewCardWord');
    var ipa = document.getElementById('previewCardIpa');
    var imageBox = document.getElementById('previewCardImage');

    function escapeHtml(value) {
        return String(value).replace(/[&<>"']/g, function (character) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[character];
        });
    }

    function renderCard() {
        if (!cards.length || !word || !imageBox) {
            return;
        }

        var card = cards[currentIndex];

        word.textContent = card.text || '';

        if (ipa) {
            ipa.textContent = card.ipa || '';
        }

        imageBox.innerHTML = card.image
            ? '<img src="' + escapeHtml(card.image) + '" alt="">'
            : '🖼️';
    }

    nextButton?.addEventListener('click', function () {
        if (!cards.length) {
            return;
        }

        currentIndex = (currentIndex + 1) % cards.length;
        renderCard();
    });

    listenButton?.addEventListener('click', function () {
        if (!cards.length) {
            return;
        }

        var card = cards[currentIndex];

        if (card.audio) {
            var audio = new Audio(card.audio);
            audio.play().catch(function () {});
            return;
        }

        if ('speechSynthesis' in window && card.text) {
            window.speechSynthesis.cancel();

            var utterance = new SpeechSynthesisUtterance(card.text);
            utterance.lang = 'en-US';
            utterance.rate = 0.82;

            window.speechSynthesis.speak(utterance);
        }
    });

    function hideGlobalAddButton() {
        document.querySelectorAll('button, a').forEach(function (element) {
            var label = (element.textContent || '').replace(/\s+/g, ' ').trim();

            if (label === 'Add' || label === '+ Add') {
                element.style.setProperty('display', 'none', 'important');
            }
        });
    }

    hideGlobalAddButton();

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', hideGlobalAddButton);
    }

    window.addEventListener('load', hideGlobalAddButton);
    setTimeout(hideGlobalAddButton, 250);
})();
</script>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
