<?php
declare(strict_types=1);

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

$pdo = getDbConnection();

$pageTitle = 'Listen & Repeat';
$pageSubtitle = 'Reuse Flashcard Sets for pronunciation practice';
$activeTeacherNav = 'listen-repeat';

$q = trim((string)($_GET['q'] ?? ''));

$sql = "SELECT
            fs.id,
            fs.title,
            fs.description,
            fs.updated_at,
            COUNT(DISTINCT fsw.id) AS word_count,
            COUNT(DISTINCT CASE
                WHEN w.audio_us_path IS NOT NULL AND w.audio_us_path <> ''
                THEN w.id
            END) AS audio_count,
            COUNT(DISTINCT CASE
                WHEN w.image_path IS NOT NULL AND w.image_path <> ''
                THEN w.id
            END) AS image_count
        FROM flashcard_sets fs
        LEFT JOIN flashcard_set_words fsw ON fsw.set_id = fs.id
        LEFT JOIN words w ON w.id = fsw.word_id";

$params = [];

if ($q !== '') {
    $sql .= " WHERE fs.title LIKE ? OR fs.description LIKE ?";
    $params = ["%{$q}%", "%{$q}%"];
}

$sql .= " GROUP BY fs.id, fs.title, fs.description, fs.updated_at
          ORDER BY fs.updated_at DESC, fs.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sets = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>
<link rel="stylesheet" href="../assets/css/listen-repeat.css?v=2">

<style>
    .lr-studio-summary {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin: 0 0 18px;
    }

    .lr-studio-summary > div {
        display: flex;
        align-items: center;
        gap: 9px;
        padding: 9px 13px;
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 11px;
        color: #64748b;
        font-size: 13px;
    }

    .lr-studio-summary strong {
        color: #0f172a;
        font-size: 14px;
    }

    .lr-set-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin: 14px 0 16px;
    }

    .lr-meta-chip {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        min-height: 30px;
        padding: 5px 9px;
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 999px;
        color: #475569;
        font-size: 12px;
        font-weight: 600;
    }

    .lr-meta-chip.is-ready {
        background: #ecfdf5;
        border-color: #bbf7d0;
        color: #15803d;
    }

    .lr-meta-chip.is-warning {
        background: #fff7ed;
        border-color: #fed7aa;
        color: #c2410c;
    }

    .lr-set-actions {
        align-items: center;
    }

    .lr-start-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 7px;
    }

    .lr-card-secondary-link {
        color: #475569;
        font-size: 13px;
        font-weight: 600;
        text-decoration: none;
    }

    .lr-card-secondary-link:hover {
        color: #2563eb;
        text-decoration: underline;
    }

    @media (max-width: 700px) {
        .lr-page-head {
            align-items: flex-start;
            gap: 14px;
        }

        .lr-set-actions {
            align-items: stretch;
        }

        .lr-set-actions .button {
            width: 100%;
        }
    }
</style>

<div class="lr-page-head">
    <div>
        <span class="section-kicker">Learning Content</span>
        <h2>Listen &amp; Repeat</h2>
        <p>Choose a Flashcard Set and start pronunciation practice immediately.</p>
    </div>

    <a class="button button-secondary" href="../flashcards/">
        Manage Flashcards
    </a>
</div>

<div class="lr-studio-summary" aria-label="Listen and Repeat summary">
    <div>
        <span>Flashcard Sets</span>
        <strong><?= count($sets) ?></strong>
    </div>
    <div>
        <span>Practice mode</span>
        <strong>Listen + Repeat</strong>
    </div>
    <div>
        <span>Voice</span>
        <strong>American English</strong>
    </div>
</div>

<form class="lr-toolbar" method="get">
    <input
        type="search"
        name="q"
        value="<?= htmlspecialchars($q, ENT_QUOTES, 'UTF-8') ?>"
        placeholder="Search Flashcard Sets..."
        autocomplete="off"
    >

    <?php if ($q !== ''): ?>
        <a class="button button-secondary" href="index.php">Clear</a>
    <?php endif; ?>
</form>

<div class="lr-grid">
    <?php if (!$sets): ?>
        <div class="lr-empty">
            <div class="lr-empty-icon">🔊</div>

            <?php if ($q !== ''): ?>
                <h3>No matching Flashcard Sets</h3>
                <p>Try another keyword or clear the current search.</p>
                <a class="button button-secondary" href="index.php">Clear Search</a>
            <?php else: ?>
                <h3>No Flashcard Sets available</h3>
                <p>Create a Flashcard Set first, then return here to practise pronunciation.</p>
                <a class="button button-primary" href="../flashcards/create.php">
                    Create Flashcard Set
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php foreach ($sets as $set):
        $wordCount = (int)$set['word_count'];
        $audioCount = (int)$set['audio_count'];
        $imageCount = (int)$set['image_count'];
        $missingAudio = max(0, $wordCount - $audioCount);
        $missingImages = max(0, $wordCount - $imageCount);
    ?>
        <article class="lr-set-card">
            <div class="lr-set-icon">🔊</div>

            <div class="lr-set-content">
                <div class="lr-set-topline">
                    <h3><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?></h3>
                    <span><?= $wordCount ?> words</span>
                </div>

                <?php if (!empty($set['description'])): ?>
                    <p><?= htmlspecialchars((string)$set['description'], ENT_QUOTES, 'UTF-8') ?></p>
                <?php else: ?>
                    <p>Listen, repeat, and reveal the answer when ready.</p>
                <?php endif; ?>

                <div class="lr-set-meta" aria-label="Set readiness">
                    <span class="lr-meta-chip">🇺🇸 American English</span>
                    <span class="lr-meta-chip">🔁 Listen + Repeat</span>

                    <?php if ($wordCount > 0 && $missingAudio === 0): ?>
                        <span class="lr-meta-chip is-ready">✓ All audio ready</span>
                    <?php elseif ($wordCount > 0): ?>
                        <span class="lr-meta-chip is-warning">
                            ⚠ <?= $missingAudio ?> missing audio
                        </span>
                    <?php endif; ?>

                    <?php if ($wordCount > 0 && $missingImages === 0): ?>
                        <span class="lr-meta-chip is-ready">✓ All images ready</span>
                    <?php elseif ($wordCount > 0): ?>
                        <span class="lr-meta-chip is-warning">
                            ⚠ <?= $missingImages ?> missing images
                        </span>
                    <?php endif; ?>
                </div>

                <div class="lr-set-actions">
                    <?php if ($wordCount > 0): ?>
                        <a
                            class="button button-primary lr-start-button"
                            href="play.php?id=<?= (int)$set['id'] ?>"
                        >
                            <span>▶</span>
                            Start Practice
                        </a>
                    <?php else: ?>
                        <a
                            class="button button-secondary"
                            href="../flashcards/edit.php?id=<?= (int)$set['id'] ?>"
                        >
                            Add Words
                        </a>
                    <?php endif; ?>

                    <a
                        class="lr-card-secondary-link"
                        href="../flashcards/edit.php?id=<?= (int)$set['id'] ?>"
                    >
                        Edit Set
                    </a>
                </div>
            </div>
        </article>
    <?php endforeach; ?>
</div>

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