<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * File: teacher/flashcards/index.php
 *
 * Shared Flashcard Sets:
 * Word Library -> Flashcard Set -> Lesson Activity -> Student Game
 */

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

$pdo = getDbConnection();

$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$isAdmin = $currentUserRole === 'admin';

$pageTitle = 'Flashcard Sets';
$pageSubtitle = 'Create reusable word sets from the shared Word Library';
$activeTeacherNav = 'flashcards';

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$requestedLevelId = max(0, (int)($_GET['level_id'] ?? 0));

if (!in_array($status, ['', 'active', 'inactive'], true)) {
    $status = '';
}

/**
 * Current working book.
 * Teachers only see books actively assigned to them.
 * Admin can work with every active book.
 */
$books = [];
if ($isAdmin) {
    $books = $pdo->query(
        "SELECT id, name, slug
         FROM books
         WHERE status = 'active'
         ORDER BY sort_order, name"
    )->fetchAll(PDO::FETCH_ASSOC);
} else {
    $bookStmt = $pdo->prepare(
        "SELECT b.id, b.name, b.slug
         FROM teacher_content_assignments tca
         INNER JOIN books b ON b.id = tca.book_id
         WHERE tca.teacher_id = ?
           AND tca.status = 'active'
           AND b.status = 'active'
         GROUP BY b.id, b.name, b.slug, b.sort_order
         ORDER BY b.sort_order, b.name"
    );
    $bookStmt->execute([$currentUserId]);
    $books = $bookStmt->fetchAll(PDO::FETCH_ASSOC);
}

$allowedBookIds = array_map(
    static fn(array $book): int => (int)$book['id'],
    $books
);

$currentBookId = max(0, (int)($_SESSION['teacher_book_id'] ?? 0));

if (!in_array($currentBookId, $allowedBookIds, true)) {
    $currentBookId = $allowedBookIds[0] ?? 0;
    if ($currentBookId > 0) {
        $_SESSION['teacher_book_id'] = $currentBookId;
    }
}

$currentBookName = '';
foreach ($books as $book) {
    if ((int)$book['id'] === $currentBookId) {
        $currentBookName = (string)$book['name'];
        break;
    }
}

$levels = [];
if ($currentBookId > 0) {
    $levelStmt = $pdo->prepare(
        "SELECT id, name, level_number
         FROM levels
         WHERE book_id = ?
           AND status = 'active'
         ORDER BY sort_order, level_number, name"
    );
    $levelStmt->execute([$currentBookId]);
    $levels = $levelStmt->fetchAll(PDO::FETCH_ASSOC);
}

$allowedLevelIds = array_map(
    static fn(array $level): int => (int)$level['id'],
    $levels
);

$currentLevelId = in_array($requestedLevelId, $allowedLevelIds, true)
    ? $requestedLevelId
    : ($allowedLevelIds[0] ?? 0);

/**
 * @return array<string,array<string,mixed>>
 */
function fciColumns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    if ((int)$stmt->fetchColumn() === 0) {
        return [];
    }

    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

$setColumns = fciColumns($pdo, 'flashcard_sets');
$relationColumns = fciColumns($pdo, 'flashcard_set_words');
$activityColumns = fciColumns($pdo, 'activities');
$wordColumns = fciColumns($pdo, 'words');
$topicWordColumns = fciColumns($pdo, 'topic_words');
$topicColumns = fciColumns($pdo, 'topics');
$setBookColumns = fciColumns($pdo, 'flashcard_set_books');
$setLevelColumns = fciColumns($pdo, 'flashcard_set_levels');

$titleColumn = isset($setColumns['title'])
    ? 'title'
    : (isset($setColumns['name']) ? 'name' : 'id');

$descriptionColumn = isset($setColumns['description'])
    ? 'description'
    : null;

$statusColumn = isset($setColumns['status'])
    ? 'status'
    : null;

$updatedColumn = isset($setColumns['updated_at'])
    ? 'updated_at'
    : (isset($setColumns['created_at']) ? 'created_at' : 'id');

$setFk = isset($relationColumns['set_id'])
    ? 'set_id'
    : (isset($relationColumns['flashcard_set_id']) ? 'flashcard_set_id' : null);

$wordFk = isset($relationColumns['word_id']) ? 'word_id' : null;

$where = [];
$params = [];

if ($q !== '') {
    $searchParts = ["fs.`{$titleColumn}` LIKE :q"];

    if ($descriptionColumn !== null) {
        $searchParts[] = "fs.`{$descriptionColumn}` LIKE :q";
    }

    $where[] = '(' . implode(' OR ', $searchParts) . ')';
    $params[':q'] = '%' . $q . '%';
}

if ($status !== '' && $statusColumn !== null) {
    $where[] = "fs.`{$statusColumn}` = :status";
    $params[':status'] = $status;
}

if ($currentBookId > 0 && $setBookColumns !== []) {
    $where[] = "EXISTS (
        SELECT 1
        FROM flashcard_set_books fsb_filter
        WHERE fsb_filter.flashcard_set_id = fs.id
          AND fsb_filter.book_id = :current_book_id
    )";
    $params[':current_book_id'] = $currentBookId;
}

if ($currentLevelId > 0 && $setLevelColumns !== []) {
    $where[] = "EXISTS (
        SELECT 1
        FROM flashcard_set_levels fsl_filter
        WHERE fsl_filter.flashcard_set_id = fs.id
          AND fsl_filter.level_id = :current_level_id
    )";
    $params[':current_level_id'] = $currentLevelId;
}

$whereSql = $where !== [] ? 'WHERE ' . implode(' AND ', $where) : '';

$descriptionSelect = $descriptionColumn !== null
    ? "fs.`{$descriptionColumn}` AS description"
    : "'' AS description";

$statusSelect = $statusColumn !== null
    ? "fs.`{$statusColumn}` AS set_status"
    : "'active' AS set_status";

$ownerSelect = isset($setColumns['created_by_teacher_id'])
    ? 'fs.created_by_teacher_id AS created_by_teacher_id'
    : 'NULL AS created_by_teacher_id';

$wordCountSelect = '0 AS word_count';
$wordCountJoin = '';

if ($setFk !== null && $wordFk !== null) {
    $wordCountJoin = "
        LEFT JOIN (
            SELECT
                `{$setFk}` AS set_id,
                COUNT(DISTINCT `{$wordFk}`) AS word_count
            FROM flashcard_set_words
            GROUP BY `{$setFk}`
        ) wc ON wc.set_id = fs.id
    ";

    $wordCountSelect = 'COALESCE(wc.word_count, 0) AS word_count';
}

$activityUsageJoin = '';
$activityCountSelect = '0 AS activity_count';
$lessonCountSelect = '0 AS lesson_count';

$setContentJoin = '';
$thumbnailSelect = "'' AS thumbnail_path";
$topicsSelect = "'' AS topic_names";
$cefrSelect = "'' AS cefr_levels";

if (
    $setFk !== null
    && $wordFk !== null
    && isset($wordColumns['id'])
) {
    $hasWordImage = isset($wordColumns['image_path']);
    $hasWordCefr = isset($wordColumns['cefr_level']);
    $hasTopics =
        isset($topicWordColumns['word_id'])
        && isset($topicWordColumns['topic_id'])
        && isset($topicColumns['id'])
        && isset($topicColumns['name']);

    $thumbnailExpression = $hasWordImage
        ? "SUBSTRING_INDEX(
            GROUP_CONCAT(
                NULLIF(TRIM(w.image_path), '')
                ORDER BY fsw.id ASC
                SEPARATOR '||'
            ),
            '||',
            1
        )"
        : "''";

    $cefrExpression = $hasWordCefr
        ? "GROUP_CONCAT(
            DISTINCT NULLIF(TRIM(w.cefr_level), '')
            ORDER BY FIELD(
                w.cefr_level,
                'Pre-A1', 'A1', 'A2', 'B1', 'B2', 'C1', 'C2'
            )
            SEPARATOR ', '
        )"
        : "''";

    $topicJoin = '';
    $topicExpression = "''";

    if ($hasTopics) {
        $topicJoin = "
            LEFT JOIN topic_words tw ON tw.word_id = w.id
            LEFT JOIN topics t ON t.id = tw.topic_id
        ";

        $topicExpression = "GROUP_CONCAT(
            DISTINCT NULLIF(TRIM(t.name), '')
            ORDER BY t.name
            SEPARATOR ', '
        )";
    }

    $setContentJoin = "
        LEFT JOIN (
            SELECT
                fsw.`{$setFk}` AS set_id,
                {$thumbnailExpression} AS thumbnail_path,
                {$cefrExpression} AS cefr_levels,
                {$topicExpression} AS topic_names
            FROM flashcard_set_words fsw
            INNER JOIN words w ON w.id = fsw.`{$wordFk}`
            {$topicJoin}
            GROUP BY fsw.`{$setFk}`
        ) sc ON sc.set_id = fs.id
    ";

    $thumbnailSelect = "COALESCE(sc.thumbnail_path, '') AS thumbnail_path";
    $topicsSelect = "COALESCE(sc.topic_names, '') AS topic_names";
    $cefrSelect = "COALESCE(sc.cefr_levels, '') AS cefr_levels";
}

if (isset($activityColumns['flashcard_set_id'])) {
    $activityUsageJoin = "
        LEFT JOIN (
            SELECT
                flashcard_set_id,
                COUNT(*) AS activity_count,
                COUNT(DISTINCT lesson_id) AS lesson_count
            FROM activities
            WHERE flashcard_set_id IS NOT NULL
            GROUP BY flashcard_set_id
        ) au ON au.flashcard_set_id = fs.id
    ";

    $activityCountSelect = 'COALESCE(au.activity_count, 0) AS activity_count';
    $lessonCountSelect = 'COALESCE(au.lesson_count, 0) AS lesson_count';
}

$bookLabelJoin = '';
$bookLabelsSelect = "'' AS book_names";

$levelLabelJoin = '';
$levelNameSelect = "'' AS level_name";

if ($setLevelColumns !== [] && $setBookColumns !== []) {
    $levelLabelJoin = "
        LEFT JOIN (
            SELECT
                fsl.flashcard_set_id AS set_id,
                GROUP_CONCAT(
                    DISTINCT CONCAT(b_level.name, ' → ', lv_label.name)
                    ORDER BY b_level.sort_order, b_level.name, lv_label.sort_order, lv_label.level_number, lv_label.name
                    SEPARATOR ' · '
                ) AS level_name
            FROM flashcard_set_levels fsl
            INNER JOIN levels lv_label ON lv_label.id = fsl.level_id
            INNER JOIN books b_level ON b_level.id = lv_label.book_id
            INNER JOIN flashcard_set_books fsb_level
                    ON fsb_level.flashcard_set_id = fsl.flashcard_set_id
                   AND fsb_level.book_id = lv_label.book_id
            GROUP BY fsl.flashcard_set_id
        ) fl ON fl.set_id = fs.id
    ";
    $levelNameSelect = "COALESCE(fl.level_name, '') AS level_name";
}


if ($setBookColumns !== []) {
    $bookLabelJoin = "
        LEFT JOIN (
            SELECT
                fsb.flashcard_set_id AS set_id,
                GROUP_CONCAT(DISTINCT b.name ORDER BY b.sort_order, b.name SEPARATOR ' · ') AS book_names
            FROM flashcard_set_books fsb
            INNER JOIN books b ON b.id = fsb.book_id
            GROUP BY fsb.flashcard_set_id
        ) fb ON fb.set_id = fs.id
    ";
    $bookLabelsSelect = "COALESCE(fb.book_names, '') AS book_names";
}

$sql = "
    SELECT
        fs.id,
        {$ownerSelect},
        fs.`{$titleColumn}` AS set_title,
        {$descriptionSelect},
        {$statusSelect},
        {$wordCountSelect},
        {$activityCountSelect},
        {$lessonCountSelect},
        {$thumbnailSelect},
        {$topicsSelect},
        {$cefrSelect},
        {$bookLabelsSelect},
        {$levelNameSelect},
        fs.`{$updatedColumn}` AS updated_value
    FROM flashcard_sets fs
    {$wordCountJoin}
    {$activityUsageJoin}
    {$setContentJoin}
    {$bookLabelJoin}
    {$levelLabelJoin}
    {$whereSql}
    ORDER BY fs.`{$updatedColumn}` DESC, fs.id DESC
";

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

$summaryWhere = '';
$summaryParams = [];
$summaryConditions = [];
if ($currentBookId > 0 && $setBookColumns !== []) {
    $summaryConditions[] = "EXISTS (
        SELECT 1
        FROM flashcard_set_books fsb_summary
        WHERE fsb_summary.flashcard_set_id = flashcard_sets.id
          AND fsb_summary.book_id = ?
    )";
    $summaryParams[] = $currentBookId;
}
if ($currentLevelId > 0 && $setLevelColumns !== []) {
    $summaryConditions[] = "EXISTS (
        SELECT 1
        FROM flashcard_set_levels fsl_summary
        WHERE fsl_summary.flashcard_set_id = flashcard_sets.id
          AND fsl_summary.level_id = ?
    )";
    $summaryParams[] = $currentLevelId;
}
$summaryWhere = $summaryConditions !== [] ? 'WHERE ' . implode(' AND ', $summaryConditions) : '';

$summarySql = "
    SELECT
        COUNT(*) AS total_sets,
        " . ($statusColumn !== null
            ? "SUM(CASE WHEN `{$statusColumn}` = 'active' THEN 1 ELSE 0 END)"
            : "COUNT(*)") . " AS active_sets
    FROM flashcard_sets
    {$summaryWhere}
";
$summaryStmt = $pdo->prepare($summarySql);
$summaryStmt->execute($summaryParams);
$summary = $summaryStmt->fetch(PDO::FETCH_ASSOC) ?: [];

$totalSets = (int)($summary['total_sets'] ?? 0);
$activeSets = (int)($summary['active_sets'] ?? $totalSets);

$totalWords = 0;
$totalActivities = 0;

if (isset($activityColumns['flashcard_set_id'])) {
    $totalActivities = (int)$pdo->query(
        "SELECT COUNT(*)
         FROM activities
         WHERE flashcard_set_id IS NOT NULL"
    )->fetchColumn();
}

if ($setFk !== null && $wordFk !== null) {
    $totalWords = (int)$pdo->query(
        "SELECT COUNT(DISTINCT word_id)
         FROM flashcard_set_words"
    )->fetchColumn();
}

$message = (string)($_SESSION['flashcards_message'] ?? '');
$messageType = (string)($_SESSION['flashcards_message_type'] ?? 'success');

unset($_SESSION['flashcards_message'], $_SESSION['flashcards_message_type']);

ob_start();
?>

<style>
.fcs-page{display:grid;gap:18px}
.fcs-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.fcs-head h2{margin:4px 0 0;font-size:28px}
.fcs-kicker{display:block;color:#2563eb;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.fcs-subtitle{margin:7px 0 0;color:#64748b}
.fcs-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.fcs-stat{padding:16px 18px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.fcs-stat span{display:block;color:#64748b;font-size:12px;font-weight:750;text-transform:uppercase}
.fcs-stat strong{display:block;margin-top:6px;color:#0f172a;font-size:25px}
.fcs-toolbar{display:grid;grid-template-columns:minmax(220px,1fr) minmax(170px,220px) minmax(160px,210px) auto;gap:10px;padding:14px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.fcs-input,.fcs-select{width:100%;min-height:42px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.fcs-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.fcs-card{display:grid;gap:14px;padding:15px;border:1px solid #e5e7eb;border-radius:18px;background:#fff;transition:transform .2s ease,border-color .2s ease,box-shadow .2s ease}
.fcs-card:hover{transform:translateY(-3px);border-color:#93c5fd;box-shadow:0 14px 34px rgba(15,23,42,.09)}
.fcs-cover{
    position:relative;
    display:flex;
    align-items:center;
    justify-content:center;
    width:100%;
    height:150px;
    overflow:hidden;
    border-radius:14px;
    background:#f8fafc;
    border:1px solid #eef2f7;
}
.fcs-cover img{
    display:block;
    width:auto;
    height:auto;
    max-width:72%;
    max-height:72%;
    object-fit:contain;
    object-position:center;
    transition:transform .25s ease;
}
.fcs-card:hover .fcs-cover img{
    transform:scale(1.02);
}
.fcs-cover-placeholder{font-size:42px}
.fcs-card-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}
.fcs-icon{display:grid;place-items:center;width:42px;height:42px;border-radius:12px;background:#eff6ff;font-size:20px}
.fcs-title-wrap{min-width:0;flex:1}
.fcs-title-wrap h3{margin:0;color:#0f172a;font-size:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fcs-title-wrap p{margin:6px 0 0;color:#64748b;font-size:12px;line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.fcs-count{display:inline-flex;align-items:center;padding:5px 9px;border-radius:999px;background:#eef4ff;color:#2563eb;font-size:12px;font-weight:750;white-space:nowrap}
.fcs-tags{display:flex;flex-wrap:wrap;gap:6px;min-height:26px}
.fcs-tag{display:inline-flex;align-items:center;max-width:100%;padding:5px 8px;border-radius:999px;background:#f1f5f9;color:#475569;font-size:10px;font-weight:750;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fcs-tag-cefr{background:#ecfdf5;color:#047857}
.fcs-updated{color:#94a3b8;font-size:10px}
.fcs-meta{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.fcs-meta div{padding:10px;border-radius:11px;background:#f8fafc;text-align:center}
.fcs-meta span{display:block;color:#64748b;font-size:10px;font-weight:750;text-transform:uppercase}
.fcs-meta strong{display:block;margin-top:4px;color:#0f172a;font-size:14px}
.fcs-bottom{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:12px;border-top:1px solid #eef2f7}
.fcs-status{display:inline-flex;align-items:center;gap:6px;padding:5px 8px;border-radius:999px;font-size:11px;font-weight:750}
.fcs-status:before{content:"";width:7px;height:7px;border-radius:50%}
.fcs-active{background:#ecfdf3;color:#15803d}.fcs-active:before{background:#22c55e}
.fcs-hidden{background:#f1f5f9;color:#64748b}.fcs-hidden:before{background:#94a3b8}
.fcs-actions{display:flex;gap:7px}
.fcs-link{display:inline-flex;align-items:center;justify-content:center;gap:5px;min-height:34px;padding:0 10px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:12px;font-weight:750}
.fcs-link:hover{border-color:#2563eb;color:#1d4ed8}
.fcs-danger:hover{border-color:#ef4444;color:#dc2626}
.fcs-empty{grid-column:1/-1;padding:60px 20px;border:1px dashed #cbd5e1;border-radius:18px;background:#fff;text-align:center}
.fcs-empty div{font-size:43px}
.fcs-empty h3{margin:12px 0 6px}
.fcs-empty p{margin:0 0 18px;color:#64748b}
.fcs-message{padding:12px 15px;border-radius:12px;font-weight:650}
.fcs-success{border:1px solid #bbf7d0;background:#ecfdf3;color:#166534}
.fcs-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
@media(max-width:1050px){.fcs-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:760px){.fcs-head{flex-direction:column}.fcs-toolbar{grid-template-columns:1fr}.fcs-stats{grid-template-columns:1fr}}
@media(max-width:620px){.fcs-grid{grid-template-columns:1fr}.fcs-bottom{align-items:stretch;flex-direction:column}.fcs-actions{display:grid;grid-template-columns:repeat(3,1fr)}}
</style>

<div class="fcs-page">
    <div class="fcs-head">
        <div>
            <span class="fcs-kicker">Shared Content</span>
            <h2>Flashcard Sets</h2>
            <p class="fcs-subtitle">
                Select words once, then reuse the same Set across many learning Activities.
            </p>
        </div>

        <a class="button button-primary" href="create.php">
            + New Flashcard Set
        </a>
    </div>

    <?php if ($setBookColumns === []): ?>
        <div class="fcs-message fcs-error">
            Chưa có bảng flashcard_set_books. Hãy chạy file SQL đi kèm trước khi dùng bộ lọc theo sách.
        </div>
    <?php endif; ?>

    <?php if ($message !== ''): ?>
        <div class="fcs-message <?= $messageType === 'error' ? 'fcs-error' : 'fcs-success' ?>">
            <?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['deleted'])): ?>
        <div class="fcs-message fcs-success">Flashcard Set deleted successfully.</div>
    <?php endif; ?>

    <div class="fcs-stats">
        <div class="fcs-stat">
            <span>Total Sets</span>
            <strong><?= $totalSets ?></strong>
        </div>

        <div class="fcs-stat">
            <span>Active Sets</span>
            <strong><?= $activeSets ?></strong>
        </div>

        <div class="fcs-stat">
            <span>Shared Words</span>
            <strong><?= $totalWords ?></strong>
        </div>

        <div class="fcs-stat">
            <span>Activities Using Sets</span>
            <strong><?= $totalActivities ?></strong>
        </div>
    </div>

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

        <select class="fcs-select" name="level_id" onchange="this.form.submit()">
            <?php foreach ($levels as $level): ?>
                <option value="<?= (int)$level['id'] ?>" <?= $currentLevelId === (int)$level['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <?php if ($statusColumn !== null): ?>
            <select class="fcs-select" name="status" onchange="this.form.submit()">
                <option value="">All Status</option>
                <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Hidden</option>
            </select>
        <?php else: ?>
            <div></div>
        <?php endif; ?>

        <div style="display:flex;gap:8px">
            <button class="button button-primary" type="submit">Search</button>

            <?php if ($q !== '' || $status !== ''): ?>
                <a class="button button-secondary" href="index.php?level_id=<?= (int)$currentLevelId ?>">Reset</a>
            <?php endif; ?>
        </div>
    </form>

    <div class="fcs-grid">
        <?php if ($sets === []): ?>
            <div class="fcs-empty">
                <div>🃏</div>
                <h3>No Flashcard Sets yet</h3>
                <p>Create a reusable Set, then add words from the shared Word Library.</p>
                <a class="button button-primary" href="create.php">Create first Set</a>
            </div>
        <?php endif; ?>

        <?php foreach ($sets as $set): ?>
            <?php
                $isActive = (string)$set['set_status'] !== 'inactive';
                $setOwnerId = $set['created_by_teacher_id'] !== null
                    ? (int)$set['created_by_teacher_id']
                    : 0;
                $canManageSet = $isAdmin || ($setOwnerId > 0 && $setOwnerId === $currentUserId);
            ?>

            <article class="fcs-card">
                <a
                    class="fcs-cover"
                    href="preview.php?id=<?= (int)$set['id'] ?>"
                    aria-label="Preview <?= htmlspecialchars((string)$set['set_title'], ENT_QUOTES, 'UTF-8') ?>"
                >
                    <?php if (!empty($set['thumbnail_path'])): ?>
                        <img
                            src="<?= htmlspecialchars(es_url((string)$set['thumbnail_path']), ENT_QUOTES, 'UTF-8') ?>"
                            alt=""
                            loading="lazy"
                        >
                    <?php else: ?>
                        <span class="fcs-cover-placeholder">🃏</span>
                    <?php endif; ?>
                </a>

                <div class="fcs-card-top">
                    <div class="fcs-icon">🃏</div>

                    <div class="fcs-title-wrap">
                        <h3><?= htmlspecialchars((string)$set['set_title'], ENT_QUOTES, 'UTF-8') ?></h3>
                        <p>
                            <?= htmlspecialchars(
                                (string)($set['description'] ?: 'No description yet'),
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </p>
                    </div>

                    <span class="fcs-count"><?= (int)$set['word_count'] ?> words</span>
                </div>

                <div class="fcs-tags">
                    <?php if (!empty($set['level_name'])): ?>
                        <?php
                            $bookLevelPairs = array_values(array_filter(array_map(
                                static fn(string $value): string => trim($value),
                                explode(' · ', (string)$set['level_name'])
                            )));
                        ?>
                        <?php foreach ($bookLevelPairs as $bookLevelPair): ?>
                            <span class="fcs-tag" style="background:#eff6ff;color:#1d4ed8;">
                                📘 <?= htmlspecialchars($bookLevelPair, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endforeach; ?>
                    <?php elseif (!empty($set['book_names'])): ?>
                        <span class="fcs-tag" style="background:#fff7ed;color:#c2410c;">
                            📘 <?= htmlspecialchars((string)$set['book_names'], ENT_QUOTES, 'UTF-8') ?> → Chưa gắn Level
                        </span>
                    <?php else: ?>
                        <span class="fcs-tag" style="background:#fff7ed;color:#c2410c;">📘 Chưa gắn sách</span>
                    <?php endif; ?>

                    <?php if (!empty($set['cefr_levels'])): ?>
                        <span class="fcs-tag fcs-tag-cefr">
                            <?= htmlspecialchars((string)$set['cefr_levels'], ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    <?php endif; ?>

                    <?php if (!empty($set['topic_names'])): ?>
                        <span
                            class="fcs-tag"
                            title="<?= htmlspecialchars(mb_strimwidth((string)$set['topic_names'],0,24,'…'), ENT_QUOTES, 'UTF-8') ?>"
                        >
                            🏷 <?= htmlspecialchars((string)$set['topic_names'], ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    <?php endif; ?>

                    <?php if (empty($set['cefr_levels']) && empty($set['topic_names'])): ?>
                        <span class="fcs-tag">No CEFR or Topic yet</span>
                    <?php endif; ?>
                </div>

                <div class="fcs-meta">
                    <div>
                        <span>Words</span>
                        <strong><?= (int)$set['word_count'] ?></strong>
                    </div>

                    <div>
                        <span>Lessons</span>
                        <strong><?= (int)$set['lesson_count'] ?></strong>
                    </div>

                    <div>
                        <span>Activities</span>
                        <strong>🎮 <?= (int)$set['activity_count'] ?></strong>
                    </div>
                </div>

                <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;">
                    <span class="fcs-updated">
                        Updated <?= htmlspecialchars((string)$set['updated_value'], ENT_QUOTES, 'UTF-8') ?>
                    </span>
                </div>

                <div class="fcs-bottom">
                    <span class="fcs-status <?= $isActive ? 'fcs-active' : 'fcs-hidden' ?>">
                        <?= $isActive ? 'Active' : 'Hidden' ?>
                    </span>

                    <div class="fcs-actions">
                        <?php if ($canManageSet): ?>
                            <a class="fcs-link" href="edit.php?id=<?= (int)$set['id'] ?>">✏ Edit</a>
                        <?php endif; ?>
                        <a class="fcs-link" href="preview.php?id=<?= (int)$set['id'] ?>">▶ Preview</a>
                        <?php if ($canManageSet): ?>
                            <a class="fcs-link fcs-danger" href="delete.php?id=<?= (int)$set['id'] ?>">🗑 Delete</a>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    </div>
</div>

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