<?php
declare(strict_types=1);

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

$allowedTypes = [
    'memory' => [
        'title' => 'Memory',
        'icon' => '🧠',
        'description' => 'Find matching picture and word pairs.',
        'minimum' => 2,
        'options' => [4, 5, 6, 7, 8],
        'default' => 6,
        'target' => '../memory/play.php',
    ],
    'matching' => [
        'title' => 'Matching',
        'icon' => '🧩',
        'description' => 'Match each picture with the correct English word.',
        'minimum' => 2,
        'options' => [4, 5, 6, 7, 8],
        'default' => 4,
        'target' => '../matching/play.php',
    ],
    'quiz' => [
        'title' => 'Quiz',
        'icon' => '🎯',
        'description' => 'Choose the correct answer and review vocabulary.',
        'minimum' => 4,
        'options' => [5, 10, 15, 20],
        'default' => 5,
        'target' => '../quiz/play.php',
    ],
];

$type = strtolower(trim((string)($_GET['type'] ?? 'memory')));

if (!isset($allowedTypes[$type])) {
    header('Location: index.php');
    exit;
}

$template = $allowedTypes[$type];
$pdo = getDbConnection();

$stmt = $pdo->prepare(
    'SELECT
        fs.id,
        fs.title,
        fs.description,
        COUNT(fsw.id) AS word_count
     FROM flashcard_sets fs
     LEFT JOIN flashcard_set_words fsw ON fsw.set_id = fs.id
     GROUP BY fs.id, fs.title, fs.description
     HAVING COUNT(fsw.id) >= ?
     ORDER BY fs.updated_at DESC, fs.id DESC'
);
$stmt->execute([(int)$template['minimum']]);
$sets = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Create ' . $template['title'] . ' Activity';
$pageSubtitle = 'Choose a Flashcard Set and ready-made options';
$activeTeacherNav = 'games';

ob_start();
?>
<style>
.activity-create-shell {
    max-width: 980px;
    margin: 0 auto;
}

.activity-create-head {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 18px;
    margin-bottom: 20px;
}

.activity-create-title {
    display: flex;
    gap: 14px;
    align-items: flex-start;
}

.activity-create-icon {
    display: grid;
    width: 58px;
    height: 58px;
    flex: 0 0 58px;
    place-items: center;
    border-radius: 17px;
    background: #eef4ff;
    font-size: 29px;
}

.activity-create-head h2 {
    margin: 2px 0 5px;
}

.activity-create-head p {
    margin: 0;
    color: var(--muted);
}

.activity-step {
    margin-bottom: 16px;
    padding: 20px;
    border: 1px solid var(--border);
    border-radius: 18px;
    background: var(--surface);
}

.activity-step-head {
    display: flex;
    gap: 11px;
    align-items: center;
    margin-bottom: 16px;
}

.activity-step-number {
    display: grid;
    width: 30px;
    height: 30px;
    flex: 0 0 30px;
    place-items: center;
    border-radius: 50%;
    color: #fff;
    background: #2563eb;
    font-size: 13px;
    font-weight: 800;
}

.activity-step-head h3 {
    margin: 0;
    font-size: 17px;
}

.activity-step-head p {
    margin: 3px 0 0;
    color: var(--muted);
    font-size: 12px;
}

.activity-set-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.activity-set-option {
    position: relative;
}

.activity-set-option input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.activity-set-option label {
    display: flex;
    min-height: 94px;
    align-items: center;
    gap: 13px;
    padding: 14px;
    border: 1px solid var(--border);
    border-radius: 15px;
    background: #fff;
    cursor: pointer;
    transition: border-color .18s ease, box-shadow .18s ease, transform .18s ease;
}

.activity-set-option label:hover {
    transform: translateY(-1px);
    border-color: #bfdbfe;
}

.activity-set-option input:checked + label {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, .11);
}

.activity-set-thumb {
    display: grid;
    width: 44px;
    height: 44px;
    flex: 0 0 44px;
    place-items: center;
    border-radius: 13px;
    color: #2563eb;
    background: #eef4ff;
    font-weight: 900;
}

.activity-set-copy {
    min-width: 0;
    flex: 1;
}

.activity-set-copy strong {
    display: block;
    margin-bottom: 4px;
    color: var(--text);
}

.activity-set-copy small {
    display: block;
    overflow: hidden;
    color: var(--muted);
    text-overflow: ellipsis;
    white-space: nowrap;
}

.activity-set-count {
    padding: 5px 8px;
    border-radius: 999px;
    color: #1d4ed8;
    background: #eff6ff;
    font-size: 11px;
    font-weight: 800;
    white-space: nowrap;
}

.activity-word-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.activity-word-option {
    position: relative;
}

.activity-word-option input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.activity-word-option label {
    display: inline-flex;
    min-width: 72px;
    min-height: 46px;
    align-items: center;
    justify-content: center;
    padding: 0 14px;
    border: 1px solid var(--border);
    border-radius: 13px;
    color: #334155;
    background: #fff;
    font-weight: 800;
    cursor: pointer;
}

.activity-word-option input:checked + label {
    border-color: #2563eb;
    color: #1d4ed8;
    background: #eff6ff;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, .10);
}

.activity-word-option input:disabled + label {
    cursor: not-allowed;
    opacity: .35;
}

.activity-recommended {
    display: inline-flex;
    margin-top: 12px;
    padding: 6px 9px;
    border-radius: 999px;
    color: #166534;
    background: #dcfce7;
    font-size: 11px;
    font-weight: 800;
}

.activity-toggle-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 14px;
    padding: 14px;
    border: 1px solid var(--border);
    border-radius: 14px;
    background: #fff;
}

.activity-toggle-row strong {
    display: block;
    margin-bottom: 3px;
}

.activity-toggle-row small {
    color: var(--muted);
}

.activity-switch {
    position: relative;
    width: 48px;
    height: 28px;
    flex: 0 0 48px;
}

.activity-switch input {
    position: absolute;
    opacity: 0;
}

.activity-switch span {
    position: absolute;
    inset: 0;
    border-radius: 999px;
    background: #cbd5e1;
    cursor: pointer;
    transition: background .18s ease;
}

.activity-switch span::after {
    content: "";
    position: absolute;
    top: 4px;
    left: 4px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 2px 7px rgba(15, 23, 42, .18);
    transition: transform .18s ease;
}

.activity-switch input:checked + span {
    background: #2563eb;
}

.activity-switch input:checked + span::after {
    transform: translateX(20px);
}

.activity-create-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 18px;
}

.activity-create-footer .button {
    min-height: 46px;
    padding-inline: 18px;
}

.activity-empty {
    padding: 46px 20px;
    border: 1px dashed var(--border);
    border-radius: 17px;
    background: var(--surface);
    text-align: center;
}

.activity-empty div {
    margin-bottom: 8px;
    font-size: 42px;
}

.activity-empty p {
    color: var(--muted);
}

.activity-help {
    margin-top: 9px;
    color: var(--muted);
    font-size: 12px;
}

@media (max-width: 720px) {
    .activity-create-head {
        flex-direction: column;
    }

    .activity-set-grid {
        grid-template-columns: 1fr;
    }

    .activity-create-footer {
        flex-direction: column-reverse;
    }

    .activity-create-footer .button {
        width: 100%;
        justify-content: center;
    }
}
</style>

<div class="activity-create-shell">
    <div class="activity-create-head">
        <div class="activity-create-title">
            <span class="activity-create-icon"><?= $template['icon'] ?></span>
            <div>
                <span class="section-kicker">Game Studio</span>
                <h2>Create <?= htmlspecialchars($template['title'], ENT_QUOTES, 'UTF-8') ?> Activity</h2>
                <p><?= htmlspecialchars($template['description'], ENT_QUOTES, 'UTF-8') ?></p>
            </div>
        </div>

        <a class="button button-secondary" href="index.php">← Game Studio</a>
    </div>

    <?php if (!$sets): ?>
        <div class="activity-empty">
            <div>📚</div>
            <h3>No playable Flashcard Sets</h3>
            <p>
                This activity needs at least <?= (int)$template['minimum'] ?> words.
                Add more words to a Flashcard Set first.
            </p>
            <a class="button button-primary" href="../flashcards/">Manage Flashcards</a>
        </div>
    <?php else: ?>
        <form id="activityCreateForm" data-target="<?= htmlspecialchars($template['target'], ENT_QUOTES, 'UTF-8') ?>">
            <section class="activity-step">
                <div class="activity-step-head">
                    <span class="activity-step-number">1</span>
                    <div>
                        <h3>Choose a Flashcard Set</h3>
                        <p>Select the vocabulary source for this activity.</p>
                    </div>
                </div>

                <div class="activity-set-grid">
                    <?php foreach ($sets as $index => $set): ?>
                        <div class="activity-set-option">
                            <input
                                type="radio"
                                name="set_id"
                                id="activitySet<?= (int)$set['id'] ?>"
                                value="<?= (int)$set['id'] ?>"
                                data-word-count="<?= (int)$set['word_count'] ?>"
                                <?= $index === 0 ? 'checked' : '' ?>
                            >
                            <label for="activitySet<?= (int)$set['id'] ?>">
                                <span class="activity-set-thumb">
                                    <?= htmlspecialchars(
                                        mb_strtoupper(mb_substr((string)$set['title'], 0, 1)),
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </span>
                                <span class="activity-set-copy">
                                    <strong><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?></strong>
                                    <small>
                                        <?= htmlspecialchars(
                                            trim((string)($set['description'] ?? '')) !== ''
                                                ? (string)$set['description']
                                                : 'Ready to reuse in learning activities.',
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </small>
                                </span>
                                <span class="activity-set-count"><?= (int)$set['word_count'] ?> words</span>
                            </label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="activity-step">
                <div class="activity-step-head">
                    <span class="activity-step-number">2</span>
                    <div>
                        <h3>Choose Words to Use</h3>
                        <p>Only valid choices for the selected Flashcard Set remain available.</p>
                    </div>
                </div>

                <div class="activity-word-options" id="wordOptions">
                    <?php foreach ($template['options'] as $option): ?>
                        <div class="activity-word-option">
                            <input
                                type="radio"
                                name="limit"
                                id="wordLimit<?= (int)$option ?>"
                                value="<?= (int)$option ?>"
                                <?= (int)$option === (int)$template['default'] ? 'checked' : '' ?>
                            >
                            <label for="wordLimit<?= (int)$option ?>"><?= (int)$option ?></label>
                        </div>
                    <?php endforeach; ?>

                    <div class="activity-word-option">
                        <input type="radio" name="limit" id="wordLimitAll" value="all">
                        <label for="wordLimitAll" id="allWordsLabel">All</label>
                    </div>
                </div>

                <span class="activity-recommended">⭐ Ready-made choices — no number entry required</span>
                <div class="activity-help" id="wordOptionHelp"></div>
            </section>

            <section class="activity-step">
                <div class="activity-step-head">
                    <span class="activity-step-number">3</span>
                    <div>
                        <h3>Game Settings</h3>
                        <p>Recommended defaults are already selected.</p>
                    </div>
                </div>

                <div class="activity-toggle-row">
                    <div>
                        <strong>Shuffle words</strong>
                        <small>Use a different order each time the game starts.</small>
                    </div>
                    <label class="activity-switch">
                        <input type="checkbox" name="shuffle" value="1" checked>
                        <span></span>
                    </label>
                </div>
            </section>

            <div class="activity-create-footer">
                <a class="button button-secondary" href="index.php">Cancel</a>
                <button class="button button-primary" type="submit">
                    Create Activity
                </button>
            </div>
        </form>
    <?php endif; ?>
</div>

<script>
(() => {
    "use strict";

    const form = document.getElementById("activityCreateForm");

    if (!form) {
        return;
    }

    const setInputs = Array.from(form.querySelectorAll('input[name="set_id"]'));
    const limitInputs = Array.from(form.querySelectorAll('input[name="limit"]'));
    const allLabel = document.getElementById("allWordsLabel");
    const help = document.getElementById("wordOptionHelp");

    function updateWordOptions() {
        const selectedSet = form.querySelector('input[name="set_id"]:checked');

        if (!selectedSet) {
            return;
        }

        const wordCount = Number(selectedSet.dataset.wordCount || 0);
        let firstAvailable = null;
        let checkedAvailable = false;

        limitInputs.forEach((input) => {
            if (input.value === "all") {
                input.disabled = false;
                if (allLabel) {
                    allLabel.textContent = `All (${wordCount})`;
                }
            } else {
                input.disabled = Number(input.value) > wordCount;
            }

            if (!input.disabled && !firstAvailable) {
                firstAvailable = input;
            }

            if (input.checked && !input.disabled) {
                checkedAvailable = true;
            }
        });

        if (!checkedAvailable) {
            const preferred = limitInputs
                .filter((input) => !input.disabled && input.value !== "all")
                .sort((a, b) => Number(b.value) - Number(a.value))[0];

            (preferred || firstAvailable)?.click();
        }

        if (help) {
            help.textContent = `${wordCount} words are available in this Flashcard Set.`;
        }
    }

    setInputs.forEach((input) => {
        input.addEventListener("change", updateWordOptions);
    });

    form.addEventListener("submit", (event) => {
        event.preventDefault();

        const selectedSet = form.querySelector('input[name="set_id"]:checked');
        const selectedLimit = form.querySelector('input[name="limit"]:checked');
        const shuffle = form.querySelector('input[name="shuffle"]')?.checked;

        if (!selectedSet || !selectedLimit) {
            window.alert("Please choose a Flashcard Set and the number of words.");
            return;
        }

        const params = new URLSearchParams();
        params.set("set_id", selectedSet.value);
        params.set("limit", selectedLimit.value);
        params.set("shuffle", shuffle ? "1" : "0");
        params.set("from", "game-studio");

        window.location.href = `${form.dataset.target}?${params.toString()}`;
    });

    updateWordOptions();
})();
</script>

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