<?php
declare(strict_types=1);

/**
 * EnglishSpeak — Speaking Challenge
 * Part 1: Listen, record, replay, next word.
 */

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') ?>
        | Speaking Challenge
    </title>

    <link rel="stylesheet" href="../assets/css/speaking.css?v=14">
</head>

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

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

    <?php if (count($items) === 0): ?>
        <section class="sp-empty">
            <div>🎤</div>
            <h2>No words available</h2>
            <p>This Flashcard Set does not contain active words yet.</p>

            <a href="../flashcards/edit.php?id=<?= (int)$setId ?>">
                Edit Flashcard Set
            </a>
        </section>
    <?php else: ?>
        <section class="sp-statusbar">
            <div>
                <small>Word</small>
                <strong id="wordNumber">1 / <?= count($items) ?></strong>
            </div>

            <div>
                <small>Recorded</small>
                <strong id="recordedCount">0</strong>
            </div>

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

        <div class="sp-progress">
            <i id="speakingProgress"></i>
        </div>

        <section class="sp-card">
            <div class="sp-image-box" id="speakingImageBox">
                <img id="speakingImage" alt="" hidden>
            </div>

            <div class="sp-word-block">
                <h2 id="speakingWord">Word</h2>
                <div id="speakingIpa" class="sp-ipa"></div>
</div>

            <button class="sp-listen-button" id="listenButton" type="button">
                <span>🔊</span>
                <strong>Listen</strong>
            </button>

            <section class="sp-record-panel">
                <button
                    class="sp-record-button"
                    id="recordButton"
                    type="button"
                    aria-label="Hold to speak"
                >
                    <span class="sp-record-icon" id="recordIcon">🎤</span>
                    <strong id="recordButtonText">Hold to Speak</strong>
                </button>

                <div class="sp-record-state" id="recordState">
                    Ready
                </div>

                <div class="sp-wave" id="recordWave" aria-hidden="true">
                    <i></i><i></i><i></i><i></i><i></i>
                    <i></i><i></i><i></i><i></i><i></i>
                </div>
            </section>


            <section class="sp-ai-feedback" id="aiFeedbackPanel" hidden>
                <div class="sp-ai-score">
                    <strong id="aiScore">0%</strong>
                    <span>Điểm phát âm</span>
                </div>

                <div class="sp-ai-message">
                    <strong id="aiPraise"></strong>
                    <p id="aiFeedbackText"></p>
                    <small id="aiFeedbackTip"></small>
                </div>

                <div class="sp-ai-progress" aria-hidden="true">
                    <span id="aiScoreProgressBar"></span>
                </div>
            </section>

            <section class="sp-playback-panel" id="playbackPanel" hidden>
                <audio id="recordingPlayer" controls preload="metadata"></audio>

                <div class="sp-playback-actions">
                    <button id="recordAgainButton" type="button">
                        Ghi âm lại
                    </button>
                </div>

                <p id="saveRecordingStatus" aria-live="polite"></p>
            </section>

            <div class="sp-navigation">
                <button id="previousWordButton" type="button">
                    ← Previous
                </button>

                <button id="nextWordButton" type="button">
                    Next →
                </button>
            </div>
        </section>

        <section class="sp-finish-panel" id="finishPanel" hidden>
            <div class="sp-finish-card sp-finish-card-result">
                <div class="sp-finish-icon" id="finishIcon">🎉</div>

                <h2 id="finishTitle">Hoàn thành bài luyện nói!</h2>

                <p class="sp-finish-message" id="finishMessage">
                    Nghe mẫu và luyện lại để phát âm hay hơn nhé.
                </p>

                <div class="sp-finish-score-box" id="finishScoreBox" hidden>
                    <strong id="finishAverageScore">-- / 100</strong>
                    <span>Điểm phát âm trung bình</span>
                </div>

                <p class="sp-finish-rating" id="finishRating" hidden></p>

                <p class="sp-finish-count">
                    Đã luyện:
                    <strong id="finalRecordedCount">0 / 0</strong>
                    từ
                </p>

                <button id="practiceAgainButton" type="button">
                    🔄 Luyện lại
                </button>

                <a href="index.php">
                    📚 Chọn chủ đề khác
                </a>
            </div>
        </section>
    <?php endif; ?>
</main>

<?php if (count($items) > 0): ?>
<script>
window.SPEAKING_SET_ID = <?= (int)$setId ?>;
window.SPEAKING_ITEMS = <?= json_encode(
    $items,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?>;
window.SPEAKING_SAVE_URL = '../api/save_recording.php';
window.SPEAKING_ASSESS_URL = '../api/pronunciation_assessment.php';
</script>

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