<?php
declare(strict_types=1);

/**
 * EnglishSpeak — Flashcards
 * Student Preview
 *
 * Front:
 * - Image only
 * - Click/tap image to hear pronunciation
 *
 * Back:
 * - English word
 * - IPA
 * - Vietnamese meaning
 * - Listen button
 */

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

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

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

$pdo = getDbConnection();

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

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

$wordStmt = $pdo->prepare(
    'SELECT
        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 = ?
     ORDER BY fsw.order_no ASC, fsw.id ASC'
);
$wordStmt->execute([$id]);
$words = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

$cards = array_map(
    static fn(array $word): array => [
        'word' => (string)$word['word'],
        'meaning' => (string)($word['meaning_vi'] ?? ''),
        'ipa' => (string)($word['phonetic'] ?? ''),
        'image' => !empty($word['image_path'])
            ? es_url((string)$word['image_path'])
            : '',
        'audio' => !empty($word['audio_us_path'])
            ? es_url((string)$word['audio_us_path'])
            : '',
    ],
    $words
);
?>
<!doctype html>
<html lang="vi">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?> | EnglishSpeak</title>

    <style>
        :root {
            --blue: #2563eb;
            --blue-dark: #1d4ed8;
            --page: #edf4ff;
            --card: #ffffff;
            --text: #14213d;
            --muted: #6b7280;
            --line: #d8e2f1;
            --shadow: 0 24px 65px rgba(52, 78, 124, .19);
        }

        * {
            box-sizing: border-box;
        }

        body {
            min-height: 100vh;
            margin: 0;
            color: var(--text);
            background: var(--page);
            font-family: Arial, sans-serif;
        }

        button,
        a {
            font: inherit;
        }

        .preview-shell {
            width: 580px;
            min-height: 100dvh;
            margin: 0 auto;
            padding: 18px 18px 24px;
            background: var(--page);
        }

        .preview-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 18px;
            margin-bottom: 26px;
        }

        .preview-kicker {
            display: block;
            margin-bottom: 9px;
            color: #23395d;
            font-size: 12px;
            text-transform: uppercase;
        }

        .preview-header h1 {
            margin: 0;
            font-size: 30px;
        }

        .header-actions {
            display: flex;
            gap: 12px;
        }

        .header-actions a {
            color: #5b2b82;
        }

        .progress-label {
            margin-bottom: 5px;
            font-size: 14px;
        }

        .progress-track {
            height: 8px;
            margin-bottom: 16px;
            overflow: hidden;
            border-radius: 999px;
            background: #d7e2f2;
        }

        .progress-fill {
            width: 0;
            height: 100%;
            border-radius: inherit;
            background: var(--blue);
            transition: width .25s ease;
        }

        .card-stage {
            perspective: 1500px;
        }

        .study-card {
            position: relative;
            display: block;
            width: 100%;
            height: min(68dvh, 650px);
            padding: 0;
            border: 0;
            background: transparent;
        }

        .card-face {
            position: absolute;
            inset: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            border-radius: 28px;
            background: var(--card);
            box-shadow: var(--shadow);
            backface-visibility: hidden;
            -webkit-backface-visibility: hidden;
            transform-style: preserve-3d;
            transition: transform .48s ease;
        }

        .card-front {
            transform: rotateY(0deg);
        }

        .card-back {
            padding: 42px;
            transform: rotateY(180deg);
        }

        .study-card.flipped .card-front {
            transform: rotateY(-180deg);
        }

        .study-card.flipped .card-back {
            transform: rotateY(0deg);
        }

        .image-button {
            display: grid;
            grid-template-rows: minmax(0, 1fr) auto;
            width: 100%;
            height: 100%;
            padding: 26px 30px 18px;
            place-items: center;
            gap: 10px;
            border: 0;
            background: transparent;
            cursor: pointer;
        }

        .image-button img {
            display: block;
            width: auto;
            height: auto;
            max-width: 88%;
            max-height: 88%;
            object-fit: contain;
            object-position: center bottom;
            transition: transform .25s ease;
        }

        .image-button:hover img {
            transform: scale(1.04);
        }

        .image-listen-hint {
            color: #64748b;
            font-size: 13px;
            font-weight: 600;
            line-height: 1.35;
            text-align: center;
            user-select: none;
        }

        .back-word {
            margin: 0 0 9px;
            font-size: clamp(48px, 9vw, 78px);
            line-height: 1.05;
            text-align: center;
        }

        .back-ipa {
            min-height: 33px;
            margin-bottom: 20px;
            color: var(--blue);
            font-size: clamp(20px, 4vw, 28px);
            font-weight: 700;
            text-align: center;
        }

        .back-meaning {
            max-width: 680px;
            margin: 0;
            color: #334155;
            font-size: clamp(25px, 5vw, 36px);
            font-weight: 600;
            line-height: 1.45;
            text-align: center;
        }

        .listen-again {
            display: inline-flex;
            align-items: center;
            gap: 9px;
            margin-top: 30px;
            padding: 13px 21px;
            border: 0;
            border-radius: 14px;
            color: #fff;
            background: var(--blue);
            font-weight: 800;
            cursor: pointer;
        }

        .listen-again:hover {
            background: var(--blue-dark);
        }

        .controls {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 12px;
            margin-top: 18px;
        }

        .control-button {
            min-height: 50px;
            border: 1px solid var(--line);
            border-radius: 13px;
            color: #0f172a;
            background: #fff;
            font-weight: 800;
            cursor: pointer;
        }

        .control-button:hover:not(:disabled) {
            border-color: #aabbd6;
            background: #f8fbff;
        }

        .control-button.flip {
            color: #fff;
            border-color: var(--blue);
            background: var(--blue);
        }

        .control-button:disabled {
            cursor: not-allowed;
            opacity: .45;
        }

        .empty {
            padding: 50px 24px;
            border-radius: 20px;
            background: #fff;
            text-align: center;
        }

        @media (max-width: 650px) {
            body {
                background: var(--page);
            }

            .preview-shell {
                width: 100%;
                min-height: 100dvh;
                padding: 12px 12px 18px;
            }

            .preview-header {
                align-items: center;
                margin-bottom: 14px;
            }

            .preview-header h1 {
                font-size: 24px;
            }

            .preview-kicker {
                font-size: 10px;
                margin-bottom: 5px;
            }

            .header-actions {
                gap: 9px;
                font-size: 13px;
            }

            .progress-label {
                font-size: 12px;
            }

            .progress-track {
                margin-bottom: 10px;
            }

            .study-card {
                height: calc(100dvh - 210px);
                min-height: 430px;
                max-height: 680px;
            }

            .card-face {
                border-radius: 22px;
            }

            .image-button {
                padding: 14px 16px 12px;
                gap: 8px;
            }

            .image-button img {
                max-width: 88%;
                max-height: 88%;
            }

            .image-listen-hint {
                font-size: 12px;
            }

            .controls {
                gap: 8px;
                margin-top: 10px;
            }

            .control-button {
                min-height: 48px;
                padding: 0 8px;
                border-radius: 12px;
                font-size: 14px;
            }

            .card-back {
                padding: 24px;
            }

            .back-word {
                font-size: clamp(44px, 14vw, 68px);
            }

            .back-meaning {
                font-size: clamp(23px, 7vw, 34px);
            }
        }

        @media (prefers-reduced-motion: reduce) {
            .study-card,
            .progress-fill {
                transition: none;
            }
        }
    </style>
</head>

<body>
<main class="preview-shell">
    <header class="preview-header">
        <div>
            <span class="preview-kicker">Student Preview</span>
            <h1>📚 <?= htmlspecialchars(ucfirst((string)$set['title']), ENT_QUOTES, 'UTF-8') ?></h1>
            <div style="margin-top:5px;color:#64748b;font-size:13px;font-weight:600;">
                Flashcards
            </div>
        </div>

        <nav class="header-actions">
            <a href="edit.php?id=<?= (int)$id ?>">Edit</a>
            <a href="index.php">Close</a>
        </nav>
    </header>

    <?php if (empty($cards)): ?>
        <section class="empty">
            <h2>Bộ Flashcards chưa có từ</h2>
            <p>Hãy quay lại Editor và thêm từ từ Word Library.</p>
        </section>
    <?php else: ?>
        <div class="progress-label" id="progressLabel"></div>

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

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

                </section>

                <section class="card-face card-back">
                    <h2 class="back-word" id="backWord"></h2>
                    <div class="back-ipa" id="backIpa"></div>
                    <p class="back-meaning" id="backMeaning"></p>

                    <button class="listen-again" id="listenAgain" type="button">
                        🔊 Nghe lại
                    </button>
                </section>
            </div>
        </div>

        <div class="controls">
            <button class="control-button" id="previousButton" type="button">
                ← Previous
            </button>

            <button class="control-button flip" id="flipButton" type="button">
                Flip
            </button>

            <button class="control-button" id="nextButton" type="button">
                Next →
            </button>
        </div>
    <?php endif; ?>
</main>

<?php if (!empty($cards)): ?>
<script>
const cards = <?= json_encode(
    $cards,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
) ?>;

let currentIndex = 0;
let activeAudio = null;

const studyCard = document.getElementById('studyCard');
const imageButton = document.getElementById('imageButton');
const cardImage = document.getElementById('cardImage');
const backWord = document.getElementById('backWord');
const backIpa = document.getElementById('backIpa');
const backMeaning = document.getElementById('backMeaning');
const listenAgain = document.getElementById('listenAgain');
const previousButton = document.getElementById('previousButton');
const nextButton = document.getElementById('nextButton');
const flipButton = document.getElementById('flipButton');
const progressLabel = document.getElementById('progressLabel');
const progressFill = document.getElementById('progressFill');

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


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

    studyCard.classList.remove('flipped');

    backWord.textContent = card.word;
    backIpa.textContent = card.ipa || '';
    backMeaning.textContent = card.meaning || 'Chưa có nghĩa tiếng Việt.';

    if (card.image) {
        cardImage.src = card.image;
        cardImage.alt = '';
        cardImage.hidden = false;

        cardImage.onerror = () => {
            cardImage.hidden = true;
        };
    } else {
        cardImage.removeAttribute('src');
        cardImage.hidden = true;
    }

    progressLabel.textContent = `Card ${currentIndex + 1} of ${cards.length}`;
    progressFill.style.width = `${((currentIndex + 1) / cards.length) * 100}%`;

    previousButton.disabled = currentIndex === 0;
    nextButton.disabled = currentIndex === cards.length - 1;
}

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

    if (studyCard.classList.contains('flipped')) {
        window.setTimeout(speakCurrentCard, 200);
    }
}

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

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

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

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

    speakWithBrowser(card.word);
}

function speakWithBrowser(word) {
    if (!('speechSynthesis' in window)) {
        return;
    }

    const utterance = new SpeechSynthesisUtterance(word);
    utterance.lang = 'en-US';
    utterance.rate = 0.78;
    speechSynthesis.speak(utterance);
}

function moveCard(direction) {
    const newIndex = currentIndex + direction;

    if (newIndex < 0 || newIndex >= cards.length) {
        return;
    }

    currentIndex = newIndex;
    renderCard();
    window.setTimeout(speakCurrentCard, 250);
}

imageButton.addEventListener('click', speakCurrentCard);
listenAgain.addEventListener('click', event => {
    event.stopPropagation();
    speakCurrentCard();
});

flipButton.addEventListener('click', flipCard);

document.querySelector('.card-back').addEventListener('click', event => {
    if (event.target.closest('#listenAgain')) {
        return;
    }

    flipCard();
});

previousButton.addEventListener('click', () => moveCard(-1));
nextButton.addEventListener('click', () => moveCard(1));

document.addEventListener('keydown', event => {
    if (event.key === 'ArrowLeft') {
        moveCard(-1);
    } else if (event.key === 'ArrowRight') {
        moveCard(1);
    } else if (event.code === 'Space') {
        event.preventDefault();
        flipCard();
    } else if (event.key.toLowerCase() === 'l') {
        speakCurrentCard();
    }
});

renderCard();
</script>
<?php endif; ?>
</body>
</html>
