<?php
declare(strict_types=1);

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

$setId = filter_input(INPUT_GET, 'set_id', FILTER_VALIDATE_INT);

if (!$setId) {
    header('Location: index.php');
    exit;
}

$pdo = getDbConnection();

$setStmt = $pdo->prepare(
    'SELECT id, title, description
     FROM flashcard_sets
     WHERE id = ?
     LIMIT 1'
);
$setStmt->execute([$setId]);
$set = $setStmt->fetch(PDO::FETCH_ASSOC);

if (!$set) {
    header('Location: index.php');
    exit;
}

$wordStmt = $pdo->prepare(
    'SELECT
        w.id,
        w.word,
        w.meaning_vi,
        w.phonetic,
        w.image_path,
        w.audio_us_path
     FROM flashcard_set_words fsw
     INNER JOIN words w
        ON w.id = fsw.word_id
     WHERE fsw.set_id = ?
       AND w.status = ?
     ORDER BY fsw.order_no ASC, fsw.id ASC'
);

$wordStmt->execute([$setId, 'active']);
$rows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

$items = array_map(
    static fn(array $row): array => [
        'id' => (int)$row['id'],
        'word' => (string)$row['word'],
        'meaning' => trim((string)($row['meaning_vi'] ?? '')),
        'ipa' => trim((string)($row['phonetic'] ?? '')),
        'image' => !empty($row['image_path'])
            ? es_url((string)$row['image_path'])
            : '',
        'audio' => !empty($row['audio_us_path'])
            ? es_url((string)$row['audio_us_path'])
            : '',
    ],
    $rows
);
?>
<!doctype html>
<html lang="vi">
<head>
    <meta charset="utf-8">
    <meta
        name="viewport"
        content="width=device-width, initial-scale=1, viewport-fit=cover"
    >
    <meta name="theme-color" content="#eef4ff">

    <title>
        <?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?>
        | Quiz Challenge
    </title>

    <link rel="stylesheet" href="../assets/css/quiz.css?v=20">

<style id="quiz-layout-v20">
.qz-game-shell {
    box-sizing: border-box !important;
    width: min(580px, 100%) !important;
    max-width: 100% !important;
    margin-inline: auto !important;
    padding-inline: 14px !important;
    overflow-x: hidden !important;
}

.qz-question-card {
    box-sizing: border-box !important;
    width: 100% !important;
    max-width: 100% !important;
    min-width: 0 !important;
    margin-inline: 0 !important;
    padding: 16px !important;
    overflow: hidden !important;
}

.qz-image-prompt {
    box-sizing: border-box !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    width: 100% !important;
    max-width: 100% !important;
    min-width: 0 !important;
    margin: 0 0 24px !important;
    padding: 10px !important;
    position: relative !important;
    left: auto !important;
    right: auto !important;
    transform: none !important;
    overflow: hidden !important;
}

.qz-image-prompt img {
    display: block !important;
    width: auto !important;
    height: auto !important;
    max-width: 78% !important;
    max-height: 78% !important;
    margin: auto !important;
    position: static !important;
    transform: none !important;
    object-fit: contain !important;
    object-position: center center !important;
}

.qz-answer-grid,
.qz-feedback,
.qz-next-button {
    box-sizing: border-box !important;
    width: 100% !important;
    max-width: 100% !important;
    min-width: 0 !important;
    margin-inline: 0 !important;
}

@media (max-width: 430px) {
    .qz-game-shell {
        padding-inline: 10px !important;
    }

    .qz-question-card {
        padding: 13px !important;
    }
}
</style>

</head>

<body class="qz-play-body">
<main class="qz-game-shell" id="quizGame">
    <header class="qz-game-header">
        <div>
            <span>Quiz Challenge</span>
            <h1>
                <?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?>
            </h1>
        </div>

        <a href="index.php" aria-label="Close Quiz">✕</a>
    </header>

    <?php if (count($items) < 4): ?>
        <section class="qz-game-empty">
            <div>❓</div>
            <h2>Not enough words</h2>
            <p>A Quiz Challenge needs at least four active words.</p>

            <a href="../flashcards/edit.php?id=<?= (int)$setId ?>">
                Edit Flashcard Set
            </a>
        </section>
    <?php else: ?>
        <section class="qz-statusbar">
            <div>
                <small>Question</small>
                <strong id="questionNumber">1 / 1</strong>
            </div>

            <div>
                <small>Correct</small>
                <strong id="correctCount">0</strong>
            </div>

            <div>
                <small>Time</small>
                <strong id="quizTimer">00:00</strong>
            </div>

            <div>
                <small>XP</small>
                <strong id="quizXp">0</strong>
            </div>

            <div>
                <small>Coin</small>
                <strong id="quizCoins">0</strong>
            </div>
        </section>

        <div class="qz-game-progress">
            <i id="quizProgress"></i>
        </div>

        <section class="qz-question-card">
            <div class="qz-question-badge" id="questionBadge">
                Look and choose
            </div>

            <h2 id="questionInstruction">
                Choose the correct answer.
            </h2>

            <button
                class="qz-audio-prompt"
                id="audioPrompt"
                type="button"
                hidden
            >
                <span>🔊</span>
                <strong>Listen</strong>
            </button>

            <div class="qz-image-prompt" id="imagePrompt" hidden>
                <img id="questionImage" alt="">
            </div>

            <div class="qz-text-prompt" id="textPrompt" hidden></div>

            <div class="qz-answer-grid" id="answerGrid"></div>

            <p class="qz-feedback" id="quizFeedback">
                Choose one answer.
            </p>

            <button
                class="qz-next-button"
                id="nextQuestionButton"
                type="button"
                hidden
            >
                Next Question →
            </button>
        </section>

        <section class="qz-result-panel" id="resultPanel" hidden>
            <div class="qz-result-card">
                <div class="qz-result-icon" id="resultIcon">🏆</div>
                <div class="qz-result-stars" id="resultStars">⭐⭐⭐⭐⭐</div>

                <h2 id="resultTitle">Well done!</h2>

                <p id="resultMessage">
                    You finished the Quiz Challenge.
                </p>

                <div class="qz-result-stats">
                    <span>
                        <small>Correct</small>
                        <strong id="finalCorrect">0 / 0</strong>
                    </span>

                    <span>
                        <small>Accuracy</small>
                        <strong id="finalAccuracy">0%</strong>
                    </span>

                    <span>
                        <small>Time</small>
                        <strong id="finalTime">00:00</strong>
                    </span>

                    <span>
                        <small>XP</small>
                        <strong id="finalXp">0</strong>
                    </span>

                    <span>
                        <small>Coin</small>
                        <strong id="finalCoins">0</strong>
                    </span>
                </div>

                <section class="qz-achievements" id="achievementPanel">
                    <article>
                        <span>⚡</span>
                        <small>Fastest answer</small>
                        <strong id="fastestAnswer">—</strong>
                    </article>

                    <article>
                        <span>🎯</span>
                        <small>Perfect round</small>
                        <strong id="perfectRound">No</strong>
                    </article>
                </section>

                <section class="qz-wrong-review" id="wrongReview" hidden>
                    <h3>Words to review</h3>
                    <p>Tap any word to listen again.</p>
                    <div id="wrongReviewList"></div>
                </section>

                <button
                    class="qz-practice-wrong-button"
                    type="button"
                    id="practiceWrongButton"
                    hidden
                >
                    Practice Wrong Answers
                </button>

                <button type="button" id="playAgainButton">
                    Play Again
                </button>

                <a href="index.php">
                    Choose another set
                </a>
            </div>
        </section>
    <?php endif; ?>
</main>

<?php if (count($items) >= 4): ?>
<script>
window.QUIZ_SET_ID = <?= (int)$setId ?>;
window.QUIZ_ITEMS = <?= json_encode(
    $items,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?>;
</script>

<script src="../assets/js/quiz.js?v=20"></script>
<?php endif; ?>
</body>
</html>
