<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Create/Edit Sentence Set
 * File: teacher/sentence-sets/create.php
 */

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

$pdo = getDbConnection();

$pageTitle = 'Sentence Set';
$pageSubtitle = 'Create or manage a reusable sentence set';
$activeTeacherNav = 'content';

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

function sscTableExists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    return (int)$stmt->fetchColumn() > 0;
}

function sscColumns(PDO $pdo, string $table): array
{
    if (!sscTableExists($pdo, $table)) {
        return [];
    }

    $rows = $pdo
        ->query("SHOW COLUMNS FROM `{$table}`")
        ->fetchAll(PDO::FETCH_ASSOC);

    return array_column($rows, null, 'Field');
}

function sscFirstColumn(array $columns, array $candidates): ?string
{
    foreach ($candidates as $candidate) {
        if (isset($columns[$candidate])) {
            return $candidate;
        }
    }

    return null;
}

function sscClean(string $value): string
{
    $value = trim($value);
    $value = preg_replace('/\s+/u', ' ', $value) ?? $value;

    return trim($value);
}

function sscNormalizeWord(string $value): string
{
    $value = mb_strtolower(trim($value), 'UTF-8');
    $value = preg_replace('/[^\p{L}\p{N}\']+/u', '', $value) ?? $value;

    return trim($value);
}

function sscSentenceTokens(string $sentence): array
{
    $sentence = mb_strtolower($sentence, 'UTF-8');
    $parts = preg_split('/[^\p{L}\p{N}\']+/u', $sentence) ?: [];

    return array_values(array_filter(array_map(
        static fn(string $part): string => sscNormalizeWord($part),
        $parts
    )));
}

function sscAssetUrl(string $path): string
{
    $path = trim($path);

    if ($path === '') {
        return '';
    }

    if (
        str_starts_with($path, 'http://')
        || str_starts_with($path, 'https://')
        || str_starts_with($path, 'data:')
        || str_starts_with($path, '/')
    ) {
        return $path;
    }

    return '/EnglishSpeak/' . ltrim($path, './');
}

if (
    !sscTableExists($pdo, 'sentence_sets')
    || !sscTableExists($pdo, 'sentence_set_sentences')
    || !sscTableExists($pdo, 'sentence_set_books')
    || !sscTableExists($pdo, 'sentence_set_levels')
    || !sscTableExists($pdo, 'sentences')
) {
    http_response_code(500);
    exit('Sentence Set tables are missing.');
}

$setColumns = sscColumns($pdo, 'sentence_sets');
if (!isset($setColumns['created_by_teacher_id'])) { http_response_code(500); exit('Run ADD_OWNER_COLUMN.sql first.'); }
$sentenceColumns = sscColumns($pdo, 'sentences');
$setItemColumns = sscColumns($pdo, 'sentence_set_sentences');
$hasDisplayOrder = isset($setItemColumns['display_order']);

/*
 * Book + Level scope.
 * Admin can use every active Book.
 * Teachers only use Books actively assigned to them.
 */
$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;
    }
}

$levelsByBook = [];
if ($allowedBookIds !== []) {
    $levelPlaceholders = implode(',', array_fill(0, count($allowedBookIds), '?'));
    $allLevelStmt = $pdo->prepare(
        "SELECT id, book_id, level_number, name, slug
         FROM levels
         WHERE book_id IN ({$levelPlaceholders})
           AND status = 'active'
         ORDER BY book_id, sort_order, level_number, name"
    );
    $allLevelStmt->execute($allowedBookIds);

    foreach ($allLevelStmt->fetchAll(PDO::FETCH_ASSOC) as $levelRow) {
        $levelsByBook[(int)$levelRow['book_id']][] = $levelRow;
    }
}

/*
 * EnglishSpeak uses a direct relationship:
 * sentences.topic_id -> topics.id
 */
$hasTopicFilter = isset($sentenceColumns['topic_id'])
    && sscTableExists($pdo, 'topics');

if (!$hasTopicFilter) {
    http_response_code(500);
    exit('Topic filter requires sentences.topic_id and the topics table.');
}

$textColumn = sscFirstColumn(
    $sentenceColumns,
    ['sentence_text', 'sentence', 'text', 'content']
);
$meaningColumn = sscFirstColumn(
    $sentenceColumns,
    ['vietnamese_meaning', 'meaning_vi', 'meaning']
);
$statusColumn = isset($sentenceColumns['status']) ? 'status' : null;
$imageColumn = sscFirstColumn(
    $sentenceColumns,
    ['image_path', 'image', 'image_url']
);
$imageSelect = $imageColumn !== null
    ? "s.`{$imageColumn}` AS image_path"
    : "'' AS image_path";

$audioColumn = sscFirstColumn(
    $sentenceColumns,
    ['audio_path', 'audio_url', 'audio']
);

if ($textColumn === null) {
    http_response_code(500);
    exit('Sentence text column is missing.');
}

/*
 * Sync Word Library examples into Sentence Library.
 *
 * Source:
 *   topics -> topic_words -> words -> word_examples
 *
 * Result:
 *   each active Word example becomes a real row in `sentences`
 *   for the same Topic, so Sentence Sets still store only sentence_id.
 *
 * This keeps the existing Sentence Set / Speaking architecture intact.
 * Existing sentence text + Topic combinations are reused, not duplicated.
 */
if (
    sscTableExists($pdo, 'words')
    && sscTableExists($pdo, 'word_examples')
    && sscTableExists($pdo, 'topic_words')
    && isset($sentenceColumns['topic_id'])
) {
    try {
        $wordExampleRows = $pdo->query(
            "SELECT
                w.id AS word_id,
                COALESCE(w.image_path, '') AS image_path,
                COALESCE(we.audio_path, '') AS audio_path,
                TRIM(we.example_en) AS example_en,
                COALESCE(we.example_vi, '') AS example_vi,
                tw.topic_id
             FROM words w
             INNER JOIN word_examples we
                ON we.word_id = w.id
               AND we.status = 'active'
             INNER JOIN topic_words tw
                ON tw.word_id = w.id
             INNER JOIN topics t
                ON t.id = tw.topic_id
               AND t.status = 'active'
             WHERE w.status = 'active'
               AND TRIM(COALESCE(we.example_en, '')) <> ''
             ORDER BY tw.topic_id ASC, w.id ASC, we.sort_order ASC, we.id ASC"
        )->fetchAll(PDO::FETCH_ASSOC);

        if ($wordExampleRows !== []) {
            $findSentence = $pdo->prepare(
                "SELECT id
                 FROM sentences
                 WHERE LOWER(TRIM(`{$textColumn}`)) = LOWER(TRIM(?))
                   AND topic_id = ?
                 LIMIT 1"
            );

            foreach ($wordExampleRows as $wordExampleRow) {
                $exampleEn = sscClean((string)($wordExampleRow['example_en'] ?? ''));
                $exampleVi = trim((string)($wordExampleRow['example_vi'] ?? ''));
                $topicId = max(0, (int)($wordExampleRow['topic_id'] ?? 0));

                if ($exampleEn === '' || $topicId <= 0) {
                    continue;
                }

                $findSentence->execute([$exampleEn, $topicId]);
                $existingSentenceId = (int)($findSentence->fetchColumn() ?: 0);

                if ($existingSentenceId > 0) {
                    // Fill missing metadata from Word Library without overwriting teacher edits.
                    $updateParts = [];
                    $updateParams = [];

                    if ($meaningColumn !== null && $exampleVi !== '') {
                        $updateParts[] =
                            "`{$meaningColumn}` = CASE
                                WHEN COALESCE(TRIM(`{$meaningColumn}`), '') = '' THEN ?
                                ELSE `{$meaningColumn}`
                             END";
                        $updateParams[] = $exampleVi;
                    }

                    if ($imageColumn !== null && trim((string)$wordExampleRow['image_path']) !== '') {
                        $updateParts[] =
                            "`{$imageColumn}` = CASE
                                WHEN COALESCE(TRIM(`{$imageColumn}`), '') = '' THEN ?
                                ELSE `{$imageColumn}`
                             END";
                        $updateParams[] = trim((string)$wordExampleRow['image_path']);
                    }

                    if ($audioColumn !== null && trim((string)$wordExampleRow['audio_path']) !== '') {
                        $updateParts[] =
                            "`{$audioColumn}` = CASE
                                WHEN COALESCE(TRIM(`{$audioColumn}`), '') = '' THEN ?
                                ELSE `{$audioColumn}`
                             END";
                        $updateParams[] = trim((string)$wordExampleRow['audio_path']);
                    }

                    if ($updateParts !== []) {
                        $updateParams[] = $existingSentenceId;
                        $updateSentence = $pdo->prepare(
                            'UPDATE sentences SET ' . implode(', ', $updateParts) . ' WHERE id = ?'
                        );
                        $updateSentence->execute($updateParams);
                    }

                    continue;
                }

                $insertColumns = ["`{$textColumn}`", '`topic_id`'];
                $insertValues = [$exampleEn, $topicId];

                if ($meaningColumn !== null) {
                    $insertColumns[] = "`{$meaningColumn}`";
                    $insertValues[] = $exampleVi;
                }

                if ($imageColumn !== null) {
                    $insertColumns[] = "`{$imageColumn}`";
                    $insertValues[] = trim((string)$wordExampleRow['image_path']);
                }

                if ($audioColumn !== null) {
                    $insertColumns[] = "`{$audioColumn}`";
                    $insertValues[] = trim((string)$wordExampleRow['audio_path']);
                }

                if ($statusColumn !== null) {
                    $insertColumns[] = "`{$statusColumn}`";
                    $insertValues[] = 'active';
                }

                $placeholders = implode(', ', array_fill(0, count($insertColumns), '?'));
                $insertSentence = $pdo->prepare(
                    'INSERT INTO sentences (' . implode(', ', $insertColumns) . ')
                     VALUES (' . $placeholders . ')'
                );
                $insertSentence->execute($insertValues);
            }
        }
    } catch (Throwable $syncException) {
        // Do not block Sentence Set editing if legacy data/schema differs.
        error_log('Sentence Set Word Library sync error: ' . $syncException->getMessage());
    }
}

$setId = max(0, (int)($_GET['id'] ?? $_POST['id'] ?? 0));
$pageTitle = $setId > 0 ? 'Edit Sentence Set' : 'Create Sentence Set';
$pageSubtitle = $setId > 0
    ? 'Update this reusable sentence set'
    : 'Create a reusable sentence set';

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

$selectedIds = [];

if ($incomingIds !== '') {
    foreach (explode(',', $incomingIds) as $rawId) {
        $id = max(0, (int)$rawId);

        if ($id > 0) {
            $selectedIds[$id] = $id;
        }
    }
}

$set = [
    'id' => 0,
    'title' => '',
    'description' => '',
    'status' => 'active',
];

$linkedBookIds = [];
$linkedLevelIdsByBook = [];

if ($setId > 0) {
    $setStmt = $pdo->prepare(
        'SELECT id, title, description, status, created_by_teacher_id
         FROM sentence_sets
         WHERE id = ?
         LIMIT 1'
    );
    $setStmt->execute([$setId]);
    $loadedSet = $setStmt->fetch(PDO::FETCH_ASSOC);

    if (!$loadedSet) {
        http_response_code(404);
        exit('Sentence Set not found.');
    }

    if (!$isAdmin && ($loadedSet['created_by_teacher_id'] === null || (int)$loadedSet['created_by_teacher_id'] !== $currentUserId)) { http_response_code(403); exit('Bạn không có quyền sửa Set này.'); }
    $set = $loadedSet;

    $linkedBookStmt = $pdo->prepare(
        'SELECT book_id
         FROM sentence_set_books
         WHERE sentence_set_id = ?
         ORDER BY book_id'
    );
    $linkedBookStmt->execute([$setId]);
    $linkedBookIds = array_map('intval', $linkedBookStmt->fetchAll(PDO::FETCH_COLUMN));

    $linkedLevelStmt = $pdo->prepare(
        "SELECT l.book_id, sslev.level_id
         FROM sentence_set_levels sslev
         INNER JOIN levels l ON l.id = sslev.level_id
         WHERE sslev.sentence_set_id = ?
         ORDER BY sslev.id"
    );
    $linkedLevelStmt->execute([$setId]);
    foreach ($linkedLevelStmt->fetchAll(PDO::FETCH_ASSOC) as $linkedLevelRow) {
        $bookId = (int)$linkedLevelRow['book_id'];
        if (!isset($linkedLevelIdsByBook[$bookId])) {
            $linkedLevelIdsByBook[$bookId] = (int)$linkedLevelRow['level_id'];
        }
    }

    $itemOrderSql = $hasDisplayOrder
        ? 'ORDER BY display_order ASC, id ASC'
        : 'ORDER BY id ASC';

    $itemsStmt = $pdo->prepare(
        'SELECT sentence_id
         FROM sentence_set_sentences
         WHERE sentence_set_id = ?
         ' . $itemOrderSql
    );
    $itemsStmt->execute([$setId]);

    foreach ($itemsStmt->fetchAll(PDO::FETCH_COLUMN) as $sentenceId) {
        $selectedIds[(int)$sentenceId] = (int)$sentenceId;
    }
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $wasCreatingSet = $setId <= 0;

    try {
        $title = sscClean((string)($_POST['title'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $status = trim((string)($_POST['status'] ?? 'active')) === 'inactive'
            ? 'inactive'
            : 'active';

        $postedBookIds = array_values(array_unique(array_filter(
            array_map('intval', (array)($_POST['book_ids'] ?? [])),
            static fn(int $bookId): bool => $bookId > 0
        )));
        $postedBookIds = array_values(array_intersect($postedBookIds, $allowedBookIds));

        $postedLevelIds = [];
        foreach ((array)($_POST['level_ids'] ?? []) as $bookIdRaw => $levelIdRaw) {
            $bookIdKey = (int)$bookIdRaw;
            $levelIdValue = (int)$levelIdRaw;
            if ($bookIdKey > 0 && $levelIdValue > 0) {
                $postedLevelIds[$bookIdKey] = $levelIdValue;
            }
        }

        $postedIds = $_POST['sentence_ids'] ?? [];
        $orderedIds = [];

        if (is_array($postedIds)) {
            foreach ($postedIds as $rawId) {
                $sentenceId = max(0, (int)$rawId);

                if ($sentenceId > 0 && !in_array($sentenceId, $orderedIds, true)) {
                    $orderedIds[] = $sentenceId;
                }
            }
        }

        if ($title === '') {
            throw new RuntimeException('Sentence Set name is required.');
        }

        if ($postedBookIds === []) {
            throw new RuntimeException('Hãy chọn ít nhất 1 sách.');
        }

        if ($currentBookId <= 0 || !in_array($currentBookId, $postedBookIds, true)) {
            throw new RuntimeException('Set phải thuộc sách đang làm việc.');
        }

        $validLevelStmt = $pdo->prepare(
            "SELECT id
             FROM levels
             WHERE id = ?
               AND book_id = ?
               AND status = 'active'
             LIMIT 1"
        );

        foreach ($postedBookIds as $postedBookId) {
            $postedLevelId = (int)($postedLevelIds[$postedBookId] ?? 0);

            if ($postedLevelId <= 0) {
                throw new RuntimeException('Mỗi sách được chọn phải có Lớp / Level tương ứng.');
            }

            $validLevelStmt->execute([$postedLevelId, $postedBookId]);
            if (!$validLevelStmt->fetchColumn()) {
                throw new RuntimeException('Level đã chọn không thuộc đúng sách.');
            }
        }

        if ($orderedIds === []) {
            throw new RuntimeException('Choose at least one sentence.');
        }

        $placeholders = implode(',', array_fill(0, count($orderedIds), '?'));
        $validStmt = $pdo->prepare(
            "SELECT id
             FROM sentences
             WHERE id IN ({$placeholders})"
        );
        $validStmt->execute($orderedIds);
        $validIds = array_map('intval', $validStmt->fetchAll(PDO::FETCH_COLUMN));

        if (count($validIds) !== count($orderedIds)) {
            throw new RuntimeException('One or more sentences are invalid.');
        }

        $pdo->beginTransaction();

        if ($setId > 0) {
            $update = $pdo->prepare(
                'UPDATE sentence_sets
                 SET title = ?, description = ?, status = ?
                 WHERE id = ?'
            );
            $update->execute([$title, $description, $status, $setId]);
        } else {
            $insert = $pdo->prepare(
                'INSERT INTO sentence_sets
                    (title, description, status, created_by_teacher_id)
                 VALUES (?, ?, ?, ?)'
            );
            $insert->execute([$title, $description, $status, $isAdmin ? null : $currentUserId]);
            $setId = (int)$pdo->lastInsertId();
        }

        $deleteBookLinks = $pdo->prepare(
            'DELETE FROM sentence_set_books WHERE sentence_set_id = ?'
        );
        $deleteBookLinks->execute([$setId]);

        $insertBookLink = $pdo->prepare(
            'INSERT INTO sentence_set_books (sentence_set_id, book_id)
             VALUES (?, ?)'
        );
        foreach ($postedBookIds as $postedBookId) {
            $insertBookLink->execute([$setId, $postedBookId]);
        }

        $deleteLevelLinks = $pdo->prepare(
            'DELETE FROM sentence_set_levels WHERE sentence_set_id = ?'
        );
        $deleteLevelLinks->execute([$setId]);

        $insertLevelLink = $pdo->prepare(
            'INSERT INTO sentence_set_levels (sentence_set_id, level_id)
             VALUES (?, ?)'
        );
        foreach ($postedBookIds as $postedBookId) {
            $insertLevelLink->execute([$setId, (int)$postedLevelIds[$postedBookId]]);
        }

        $deleteItems = $pdo->prepare(
            'DELETE FROM sentence_set_sentences
             WHERE sentence_set_id = ?'
        );
        $deleteItems->execute([$setId]);

        if ($hasDisplayOrder) {
            $insertItem = $pdo->prepare(
                'INSERT INTO sentence_set_sentences
                    (sentence_set_id, sentence_id, display_order)
                 VALUES (?, ?, ?)'
            );

            foreach ($orderedIds as $index => $sentenceId) {
                $insertItem->execute([
                    $setId,
                    $sentenceId,
                    $index + 1,
                ]);
            }
        } else {
            $insertItem = $pdo->prepare(
                'INSERT INTO sentence_set_sentences
                    (sentence_set_id, sentence_id)
                 VALUES (?, ?)'
            );

            foreach ($orderedIds as $sentenceId) {
                $insertItem->execute([
                    $setId,
                    $sentenceId,
                ]);
            }
        }

        $pdo->commit();

        header(
            'Location: edit.php?id=' . (int)$setId . '&save=' . ($wasCreatingSet ? 'created' : 'ok'),
            true,
            302
        );
        exit;
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $error = $exception->getMessage();
        $set['title'] = (string)($_POST['title'] ?? '');
        $set['description'] = (string)($_POST['description'] ?? '');
        $set['status'] = (string)($_POST['status'] ?? 'active');

        $linkedBookIds = $postedBookIds ?? [];
        $linkedLevelIdsByBook = $postedLevelIds ?? [];

        $selectedIds = [];
        foreach ((array)($_POST['sentence_ids'] ?? []) as $rawId) {
            $id = max(0, (int)$rawId);

            if ($id > 0) {
                $selectedIds[$id] = $id;
            }
        }
    }
}

if ($setId <= 0 && $linkedBookIds === [] && $currentBookId > 0) {
    $linkedBookIds = [$currentBookId];
}

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

$topicsStmt = $pdo->query(
    "SELECT id, name AS topic_name
     FROM topics
     WHERE status = 'active'
     ORDER BY name ASC"
);
$topics = $topicsStmt->fetchAll(PDO::FETCH_ASSOC);

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

if ($search !== '') {
    $parts = ["s.`{$textColumn}` LIKE ?"];
    $params[] = '%' . $search . '%';

    if ($meaningColumn !== null) {
        $parts[] = "s.`{$meaningColumn}` LIKE ?";
        $params[] = '%' . $search . '%';
    }

    $where[] = '(' . implode(' OR ', $parts) . ')';
}

if ($statusColumn !== null) {
    $where[] = "s.`{$statusColumn}` = 'active'";
}

$meaningSelect = $meaningColumn !== null
    ? "s.`{$meaningColumn}` AS vietnamese_meaning"
    : "'' AS vietnamese_meaning";

$sql =
    "SELECT
        s.id,
        s.`{$textColumn}` AS sentence_text,
        {$meaningSelect},
        {$imageSelect},
        COALESCE(s.topic_id, 0) AS topic_id,
        COALESCE(t.name, '') AS topic_name
     FROM sentences s
     LEFT JOIN topics t ON t.id = s.topic_id";

if ($where !== []) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= ' ORDER BY s.id DESC';

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

$sentenceMap = [];
foreach ($sentences as $sentence) {
    $sentenceMap[(int)$sentence['id']] = $sentence;
}

/*
 * Ensure selected sentences remain visible even when using search.
 */
$missingSelected = array_diff(
    array_values($selectedIds),
    array_keys($sentenceMap)
);

if ($missingSelected !== []) {
    $placeholders = implode(',', array_fill(0, count($missingSelected), '?'));

    $missingSql =
        "SELECT
            s.id,
            s.`{$textColumn}` AS sentence_text,
            {$meaningSelect},
            {$imageSelect},
            COALESCE(s.topic_id, 0) AS topic_id,
            COALESCE(t.name, '') AS topic_name
         FROM sentences s
         LEFT JOIN topics t ON t.id = s.topic_id
         WHERE s.id IN ({$placeholders})";

    $missingStmt = $pdo->prepare($missingSql);
    $missingStmt->execute(array_values($missingSelected));

    foreach ($missingStmt->fetchAll(PDO::FETCH_ASSOC) as $sentence) {
        $sentenceMap[(int)$sentence['id']] = $sentence;
    }
}

/*
 * Sentence Set does not resolve images by itself.
 * It calls the shared resolver used by Sentence Library.
 */
foreach ($sentenceMap as &$sentence) {
    $resolvedImage = esResolveSentenceImage(
        $pdo,
        (string)$sentence['sentence_text'],
        (string)($sentence['image_path'] ?? '')
    );

    $sentence['sentence_image'] = (string)($resolvedImage['url'] ?? '');
    $sentence['image_source'] = (string)($resolvedImage['source'] ?? 'none');
}
unset($sentence);

$selectedSentences = [];
foreach ($selectedIds as $sentenceId) {
    if (isset($sentenceMap[$sentenceId])) {
        $selectedSentences[] = $sentenceMap[$sentenceId];
    }
}

$availableSentences = [];
foreach ($sentenceMap as $sentenceId => $sentence) {
    if (!isset($selectedIds[$sentenceId])) {
        $availableSentences[] = $sentence;
    }
}

ob_start();
?>
<style>
.ssc-editor{display:grid;gap:14px;max-width:1440px;margin:0 auto;padding-bottom:24px}
.ssc-top-actions{display:flex;justify-content:flex-end;gap:10px}
.ssc-btn{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:38px;padding:8px 15px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#334155;font:inherit;font-size:13px;font-weight:850;text-decoration:none;cursor:pointer;transition:.16s ease}
.ssc-btn:hover{background:#f8fafc}.ssc-btn-primary{border-color:#2563eb;background:#2563eb;color:#fff;box-shadow:0 7px 16px rgba(37,99,235,.18)}.ssc-btn-primary:hover{background:#1d4ed8}
.ssc-message{padding:11px 13px;border:1px solid #fecaca;border-radius:10px;background:#fef2f2;color:#991b1b;font-weight:750}
.ssc-info{max-width:760px;display:grid;gap:8px}
.ssc-book-box{display:grid;gap:9px;padding:13px 14px;border:1px solid #dbeafe;border-radius:12px;background:#f8fbff}
.ssc-book-label{color:#0f172a;font-size:12px;font-weight:850}
.ssc-book-help{color:#64748b;font-size:11px;line-height:1.45}
.ssc-book-level-list{display:grid;gap:9px}
.ssc-book-level-row{display:grid;grid-template-columns:minmax(190px,1fr) minmax(190px,270px);gap:10px;align-items:center}
.ssc-book-option{display:inline-flex;align-items:center;gap:7px;min-height:40px;padding:8px 11px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#334155;font-size:12px;font-weight:800}
.ssc-book-option input{margin:0}
.ssc-book-select{width:100%;min-height:40px;padding:0 10px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.ssc-name,.ssc-description{width:100%;border:1px solid #dbe2ea;border-radius:11px;background:#fff;color:#0f172a;font:inherit;outline:none;transition:.16s ease}
.ssc-name{height:54px;padding:0 15px;font-size:22px;font-weight:900}.ssc-description{min-height:60px;padding:12px 14px;resize:vertical}
.ssc-name:focus,.ssc-description:focus,.ssc-search-input:focus,.ssc-filter:focus{border-color:#60a5fa;box-shadow:0 0 0 3px rgba(37,99,235,.10)}
.ssc-status-line{display:flex;align-items:center;gap:10px;color:#64748b;font-size:12px}.ssc-status-line select{border:0;background:transparent;color:#334155;font:inherit;font-weight:800;outline:none;cursor:pointer}
.ssc-stats{display:flex;flex-wrap:wrap;gap:10px}.ssc-stat{display:inline-flex;align-items:center;gap:7px;min-height:38px;padding:8px 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#334155;font-size:13px}.ssc-stat strong{color:#0f172a}
.ssc-workspace{display:grid;grid-template-columns:280px minmax(460px,1fr) 320px;height:610px;border:1px solid #dbe2ea;border-radius:16px;background:#fff;overflow:hidden}
.ssc-panel{min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}.ssc-panel+.ssc-panel{border-left:1px solid #e5e7eb}
.ssc-panel-head{display:flex;align-items:center;justify-content:space-between;gap:10px;height:44px;padding:0 14px;border-bottom:1px solid #e5e7eb;background:#fff;color:#0f172a;font-size:13px;font-weight:900}.ssc-panel-head span:last-child{font-weight:700}
.ssc-library-tools{padding:12px;border-bottom:1px solid #eef2f7}.ssc-search-input,.ssc-filter{width:100%;min-height:40px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit;font-size:13px;outline:none}.ssc-search-input{padding:8px 11px}.ssc-filter{padding:7px 9px;margin-top:8px}
.ssc-list{display:grid;align-content:start;gap:8px;min-height:0;flex:1 1 auto;overflow-x:hidden;overflow-y:auto;padding:10px;scrollbar-gutter:stable}
.ssc-row{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:9px;padding:10px;border:1px solid #e5e7eb;border-radius:11px;background:#fff;cursor:pointer;transition:.15s ease}.ssc-row:hover{border-color:#93c5fd;background:#f8fbff}.ssc-row.is-active{border-color:#2563eb;background:#eff6ff;box-shadow:0 0 0 1px #2563eb}.ssc-row[hidden]{display:none!important}
.ssc-row-main{min-width:0}.ssc-row-title{color:#0f172a;font-size:13px;font-weight:900;line-height:1.35}.ssc-row-meaning{margin-top:3px;color:#64748b;font-size:11px;line-height:1.35}.ssc-topic-badge{display:inline-flex;margin-top:5px;padding:3px 7px;border-radius:999px;background:#f1f5f9;color:#475569;font-size:10px;font-weight:800}.ssc-row-order{display:inline-grid;place-items:center;width:30px;height:30px;border-radius:9px;background:#eff6ff;color:#2563eb;font-weight:900}.ssc-selected-row{grid-template-columns:22px 32px minmax(0,1fr) auto}.ssc-drag{color:#94a3b8;font-size:18px;cursor:grab;user-select:none}.ssc-drag:active{cursor:grabbing}
.ssc-add,.ssc-remove{border:0;background:transparent;font:inherit;font-size:12px;font-weight:850;cursor:pointer}.ssc-add{color:#2563eb}.ssc-remove{display:grid;place-items:center;width:28px;height:28px;border-radius:8px;background:#fee2e2;color:#dc2626}
.ssc-empty{margin:10px;padding:28px 14px;border:1px dashed #cbd5e1;border-radius:11px;background:#f8fafc;color:#64748b;text-align:center;font-size:12px}
.ssc-preview-body{padding:12px;overflow:auto}.ssc-preview-card{border:1px solid #e5e7eb;border-radius:14px;background:#fff;overflow:hidden}.ssc-preview-hero{display:grid;place-items:center;min-height:210px;padding:22px;background:#f8fafc;text-align:center}.ssc-preview-icon{display:grid;place-items:center;width:74px;height:74px;border-radius:20px;background:#dbeafe;font-size:36px}.ssc-preview-image{display:block;max-width:100%;max-height:190px;object-fit:contain}.ssc-preview-content{padding:15px}.ssc-preview-sentence{margin:0;color:#0f172a;font-size:22px;font-weight:950;line-height:1.35;word-break:break-word}.ssc-preview-meaning{margin:8px 0 0;color:#64748b;font-size:13px;line-height:1.5}.ssc-preview-meta{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:14px}.ssc-meta-box{padding:10px;border:1px solid #e5e7eb;border-radius:10px}.ssc-meta-label{color:#94a3b8;font-size:10px;font-weight:900;text-transform:uppercase}.ssc-meta-value{margin-top:3px;color:#334155;font-size:12px;font-weight:850}.ssc-preview-placeholder{padding:36px 15px;color:#64748b;text-align:center;font-size:12px}
.ssc-bottom{display:flex;justify-content:flex-end;gap:10px}
@media(max-width:1100px){.ssc-workspace{grid-template-columns:260px minmax(360px,1fr)}.ssc-preview-panel{grid-column:1/-1;border-left:0!important;border-top:1px solid #e5e7eb}.ssc-preview-body{max-width:520px}}
@media(max-width:760px){.ssc-book-level-row{grid-template-columns:1fr}.ssc-workspace{grid-template-columns:1fr;height:auto;overflow:visible}.ssc-panel+.ssc-panel{border-left:0;border-top:1px solid #e5e7eb}.ssc-info{max-width:none}.ssc-top-actions,.ssc-bottom{justify-content:stretch}.ssc-btn{flex:1}.ssc-workspace{min-height:0}.ssc-list{max-height:430px}}
</style>

<form method="post" id="sentenceSetForm" class="ssc-editor">
    <input type="hidden" name="id" value="<?= (int)$setId ?>">

    <div class="ssc-top-actions">
        <a class="ssc-btn" href="index.php">← List</a>
        <?php if ($setId > 0): ?>
            <a class="ssc-btn" href="preview.php?id=<?= (int)$setId ?>">Student View</a>
        <?php endif; ?>
        <button class="ssc-btn ssc-btn-primary" type="submit"><?= $setId > 0 ? 'Save Changes' : 'Create Set' ?></button>
    </div>

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

    <div class="ssc-info">
        <input class="ssc-name" id="setTitle" type="text" name="title" required placeholder="Ví dụ: Unit 1. Lesson 1" value="<?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?>">
        <textarea class="ssc-description" name="description" placeholder="Description"><?= htmlspecialchars((string)$set['description'], ENT_QUOTES, 'UTF-8') ?></textarea>

        <div class="ssc-book-box">
            <span class="ssc-book-label">Sách sử dụng Set này + Lớp / Level *</span>
            <div class="ssc-book-help">Mỗi sách được chọn bắt buộc phải có Level riêng thuộc chính sách đó.</div>

            <div class="ssc-book-level-list">
                <?php foreach ($books as $book): ?>
                    <?php
                        $bookId = (int)$book['id'];
                        $isLinkedBook = in_array($bookId, $linkedBookIds, true);
                        $selectedLevelForBook = (int)($linkedLevelIdsByBook[$bookId] ?? 0);
                        $bookLevels = $levelsByBook[$bookId] ?? [];
                    ?>
                    <div class="ssc-book-level-row">
                        <label class="ssc-book-option">
                            <input
                                type="checkbox"
                                class="js-ss-book-toggle"
                                name="book_ids[]"
                                value="<?= $bookId ?>"
                                data-book-id="<?= $bookId ?>"
                                <?= $isLinkedBook ? 'checked' : '' ?>
                            >
                            <span>📘 <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?></span>
                        </label>

                        <select
                            class="ssc-book-select js-ss-book-level"
                            name="level_ids[<?= $bookId ?>]"
                            data-book-id="<?= $bookId ?>"
                            <?= $isLinkedBook ? 'required' : 'disabled' ?>
                        >
                            <option value="">-- Chọn Lớp / Level --</option>
                            <?php foreach ($bookLevels as $level): ?>
                                <?php $levelIdOption = (int)$level['id']; ?>
                                <option value="<?= $levelIdOption ?>" <?= $selectedLevelForBook === $levelIdOption ? 'selected' : '' ?>>
                                    <?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="ssc-book-help">Một Sentence Set có thể dùng cho nhiều sách nhưng không được có Book nào thiếu Level.</div>
        </div>

        <div class="ssc-status-line">
            <?php $saveState = trim((string)($_GET['save'] ?? '')); ?>
            <span id="savedText">
                <?= $saveState === 'created' ? 'Created' : ($saveState === 'ok' ? 'Saved' : 'Ready') ?>
            </span>
            <span>•</span>
            <label>Status
                <select name="status">
                    <option value="active" <?= (string)$set['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= (string)$set['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                </select>
            </label>
        </div>
    </div>

    <div class="ssc-stats">
        <div class="ssc-stat">Total sentences <strong id="totalStat"><?= count($selectedSentences) + count($availableSentences) ?></strong></div>
        <div class="ssc-stat">Showing <strong id="showingStat"><?= count($availableSentences) ?></strong></div>
        <div class="ssc-stat">Selected <strong id="selectedStat"><?= count($selectedSentences) ?></strong></div>
    </div>

    <section class="ssc-workspace">
        <div class="ssc-panel">
            <div class="ssc-panel-head"><span>Sentence Library</span><span id="libraryCount"><?= count($availableSentences) ?></span></div>
            <div class="ssc-library-tools">
                <input class="ssc-search-input" id="sentenceSearch" type="search" placeholder="Search sentence or meaning...">
                <select class="ssc-filter" id="topicFilter">
                    <option value="all">All Topics</option>
                    <option value="0">No Topic</option>
                    <?php foreach ($topics as $topic): ?>
                        <option value="<?= (int)$topic['id'] ?>">
                            <?= htmlspecialchars((string)$topic['topic_name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div style="margin-top:9px;color:#64748b;font-size:11px;">
                    <span id="availableNote"><?= count($availableSentences) ?></span> sentences available
                </div>
                <div style="margin-top:5px;color:#64748b;font-size:10px;line-height:1.4;">
                    Word Library examples are included automatically with their Topic and image.
                </div>
            </div>
            <div class="ssc-list" id="availableList">
                <?php foreach ($availableSentences as $sentence): ?>
                    <div class="ssc-row available-row" data-id="<?= (int)$sentence['id'] ?>" data-topic="<?= (int)($sentence['topic_id'] ?? 0) ?>" data-topic-name="<?= htmlspecialchars((string)($sentence['topic_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-image="<?= htmlspecialchars((string)($sentence['sentence_image'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-search="<?= htmlspecialchars(mb_strtolower((string)$sentence['sentence_text'].' '.(string)$sentence['vietnamese_meaning'], 'UTF-8'), ENT_QUOTES, 'UTF-8') ?>">
                        <div class="ssc-row-main">
                            <div class="ssc-row-title"><?= htmlspecialchars((string)$sentence['sentence_text'], ENT_QUOTES, 'UTF-8') ?></div>
                            <?php if ((string)$sentence['vietnamese_meaning'] !== ''): ?><div class="ssc-row-meaning"><?= htmlspecialchars((string)$sentence['vietnamese_meaning'], ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
                            <div class="ssc-topic-badge"><?= (string)($sentence['topic_name'] ?? '') !== '' ? htmlspecialchars((string)$sentence['topic_name'], ENT_QUOTES, 'UTF-8') : 'No Topic' ?></div>
                        </div>
                        <button class="ssc-add add-sentence" type="button">+ Add</button>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="ssc-empty" id="availableEmpty" <?= $availableSentences !== [] ? 'hidden' : '' ?>>No sentence available.</div>
        </div>

        <div class="ssc-panel">
            <div class="ssc-panel-head"><span>Selected Sentences</span><span id="selectedCount"><?= count($selectedSentences) ?></span></div>
            <div class="ssc-list" id="selectedList">
                <?php foreach ($selectedSentences as $index => $sentence): ?>
                    <div class="ssc-row ssc-selected-row selected-row" data-id="<?= (int)$sentence['id'] ?>" data-topic="<?= (int)($sentence['topic_id'] ?? 0) ?>" data-topic-name="<?= htmlspecialchars((string)($sentence['topic_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-image="<?= htmlspecialchars((string)($sentence['sentence_image'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" draggable="true">
                        <span class="ssc-drag" title="Drag to reorder">⋮⋮</span>
                        <span class="ssc-row-order"><?= $index + 1 ?></span>
                        <input type="hidden" name="sentence_ids[]" value="<?= (int)$sentence['id'] ?>">
                        <div class="ssc-row-main">
                            <div class="ssc-row-title"><?= htmlspecialchars((string)$sentence['sentence_text'], ENT_QUOTES, 'UTF-8') ?></div>
                            <?php if ((string)$sentence['vietnamese_meaning'] !== ''): ?><div class="ssc-row-meaning"><?= htmlspecialchars((string)$sentence['vietnamese_meaning'], ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
                            <div class="ssc-topic-badge"><?= (string)($sentence['topic_name'] ?? '') !== '' ? htmlspecialchars((string)$sentence['topic_name'], ENT_QUOTES, 'UTF-8') : 'No Topic' ?></div>
                        </div>
                        <button class="ssc-remove remove-sentence" type="button" title="Remove">×</button>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="ssc-empty" id="selectedEmpty" <?= $selectedSentences !== [] ? 'hidden' : '' ?>>Choose sentences from the Sentence Library.</div>
        </div>

        <div class="ssc-panel ssc-preview-panel">
            <div class="ssc-panel-head"><span>Preview</span><span>Sentence details</span></div>
            <div class="ssc-preview-body" id="previewBody">
                <div class="ssc-preview-placeholder" id="previewEmpty">Select a sentence to preview.</div>
                <div class="ssc-preview-card" id="previewCard" hidden>
                    <div class="ssc-preview-hero"><img class="ssc-preview-image" id="previewImage" src="" alt="" hidden><div class="ssc-preview-icon" id="previewIcon">💬</div></div>
                    <div class="ssc-preview-content">
                        <h3 class="ssc-preview-sentence" id="previewSentence"></h3>
                        <p class="ssc-preview-meaning" id="previewMeaning"></p>
                        <div class="ssc-preview-meta">
                            <div class="ssc-meta-box"><div class="ssc-meta-label">Type</div><div class="ssc-meta-value">Sentence</div></div>
                            <div class="ssc-meta-box"><div class="ssc-meta-label">Status</div><div class="ssc-meta-value">Ready</div></div><div class="ssc-meta-box"><div class="ssc-meta-label">Audio</div><div class="ssc-meta-value">From Library</div></div><div class="ssc-meta-box"><div class="ssc-meta-label">Topic</div><div class="ssc-meta-value" id="previewTopic">Uncategorized</div></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="ssc-bottom">
        <a class="ssc-btn" href="index.php">Cancel</a>
        <button class="ssc-btn ssc-btn-primary" type="submit"><?= $setId > 0 ? 'Save Changes' : 'Create Set' ?></button>
    </div>
</form>

<script>
(function(){
'use strict';
const form=document.getElementById('sentenceSetForm');
if(!form) return;
const toggles=Array.from(form.querySelectorAll('.js-ss-book-toggle'));

function syncBookLevel(toggle){
    const bookId=toggle.dataset.bookId||'';
    const select=form.querySelector('.js-ss-book-level[data-book-id="'+bookId+'"]');
    if(!select) return;
    select.disabled=!toggle.checked;
    select.required=toggle.checked;
    if(!toggle.checked) select.value='';
}

toggles.forEach(function(toggle){
    syncBookLevel(toggle);
    toggle.addEventListener('change',function(){syncBookLevel(toggle);});
});

form.addEventListener('submit',function(event){
    const selected=toggles.filter(function(toggle){return toggle.checked;});
    if(selected.length===0){
        event.preventDefault();
        alert('Hãy chọn ít nhất 1 sách.');
        return;
    }

    for(const toggle of selected){
        const bookId=toggle.dataset.bookId||'';
        const select=form.querySelector('.js-ss-book-level[data-book-id="'+bookId+'"]');
        if(!select||!select.value){
            event.preventDefault();
            if(select) select.focus();
            alert('Mỗi sách được chọn phải có Lớp / Level tương ứng.');
            return;
        }
    }
});
})();
</script>

<script>
(function(){
'use strict';
const availableList=document.getElementById('availableList');
const selectedList=document.getElementById('selectedList');
const search=document.getElementById('sentenceSearch');
const topicFilter=document.getElementById('topicFilter');
const availableEmpty=document.getElementById('availableEmpty');
const selectedEmpty=document.getElementById('selectedEmpty');
const libraryCount=document.getElementById('libraryCount');
const selectedCount=document.getElementById('selectedCount');
const showingStat=document.getElementById('showingStat');
const selectedStat=document.getElementById('selectedStat');
const availableNote=document.getElementById('availableNote');
const previewEmpty=document.getElementById('previewEmpty');
const previewCard=document.getElementById('previewCard');
const previewSentence=document.getElementById('previewSentence');
const previewMeaning=document.getElementById('previewMeaning');
const previewTopic=document.getElementById('previewTopic');
const previewImage=document.getElementById('previewImage');
const previewIcon=document.getElementById('previewIcon');
let dragged=null;

function text(row,selector){return (row.querySelector(selector)?.textContent||'').trim();}
function preview(row){
 document.querySelectorAll('.ssc-row.is-active').forEach(el=>el.classList.remove('is-active'));
 if(!row){previewCard.hidden=true;previewEmpty.hidden=false;return;}
 row.classList.add('is-active');previewSentence.textContent=text(row,'.ssc-row-title');
 const meaning=text(row,'.ssc-row-meaning');previewMeaning.textContent=meaning||'No Vietnamese meaning.';if(previewTopic)previewTopic.textContent=row.dataset.topicName||'—';
 const image=(row.dataset.image||'').trim();
 if(image){
  previewImage.src=image;previewImage.hidden=false;previewIcon.hidden=true;
 }else{
  previewImage.removeAttribute('src');previewImage.hidden=true;previewIcon.hidden=false;
 }
 previewEmpty.hidden=true;previewCard.hidden=false;
}
function renumber(){selectedList.querySelectorAll('.selected-row').forEach((row,i)=>{row.querySelector('.ssc-row-order').textContent=String(i+1);});}
function update(){
 const available=[...availableList.querySelectorAll('.available-row')];
 const visible=available.filter(r=>!r.hidden).length;
 const selected=selectedList.querySelectorAll('.selected-row').length;
 libraryCount.textContent=String(available.length);if(availableNote)availableNote.textContent=String(available.length);selectedCount.textContent=String(selected);showingStat.textContent=String(visible);selectedStat.textContent=String(selected);
 availableEmpty.hidden=visible>0;
 availableEmpty.textContent=available.length===0
  ? 'No sentence available.'
  : 'No sentences match the selected Topic.';
 selectedEmpty.hidden=selected>0;renumber();
}
function availableRow(id,title,meaning,topicId,topicName,image){
 const row=document.createElement('div');row.className='ssc-row available-row';row.dataset.id=id;row.dataset.topic=topicId||'0';row.dataset.topicName=topicName||'';row.dataset.image=image||'';row.dataset.search=(title+' '+meaning).toLocaleLowerCase();
 row.innerHTML='<div class="ssc-row-main"><div class="ssc-row-title"></div>'+(meaning?'<div class="ssc-row-meaning"></div>':'')+'<div class="ssc-topic-badge"></div></div><button class="ssc-add add-sentence" type="button">+ Add</button>';
 row.querySelector('.ssc-row-title').textContent=title;if(meaning)row.querySelector('.ssc-row-meaning').textContent=meaning;row.querySelector('.ssc-topic-badge').textContent=topicName||'No Topic';bindAvailable(row);return row;
}
function selectedRow(id,title,meaning,topicId,topicName,image){
 const row=document.createElement('div');row.className='ssc-row ssc-selected-row selected-row';row.dataset.id=id;row.dataset.topic=topicId||'0';row.dataset.topicName=topicName||'';row.dataset.image=image||'';row.draggable=true;
 row.innerHTML='<span class="ssc-drag" title="Drag to reorder">⋮⋮</span><span class="ssc-row-order"></span><input type="hidden" name="sentence_ids[]" value="'+id+'"><div class="ssc-row-main"><div class="ssc-row-title"></div>'+(meaning?'<div class="ssc-row-meaning"></div>':'')+'<div class="ssc-topic-badge"></div></div><button class="ssc-remove remove-sentence" type="button" title="Remove">×</button>';
 row.querySelector('.ssc-row-title').textContent=title;if(meaning)row.querySelector('.ssc-row-meaning').textContent=meaning;row.querySelector('.ssc-topic-badge').textContent=topicName||'No Topic';bindSelected(row);return row;
}
function bindAvailable(row){
 row.addEventListener('click',e=>{if(!e.target.closest('button'))preview(row);});
 row.querySelector('.add-sentence').addEventListener('click',()=>{const id=row.dataset.id||'';const title=text(row,'.ssc-row-title');const meaning=text(row,'.ssc-row-meaning');const added=selectedRow(id,title,meaning,row.dataset.topic||'0',row.dataset.topicName||'',row.dataset.image||'');selectedList.appendChild(added);row.remove();preview(added);applySearch();update();});
}
function bindSelected(row){
 row.addEventListener('click',e=>{if(!e.target.closest('button'))preview(row);});
 row.querySelector('.remove-sentence').addEventListener('click',()=>{const id=row.dataset.id||'';const title=text(row,'.ssc-row-title');const meaning=text(row,'.ssc-row-meaning');availableList.prepend(availableRow(id,title,meaning,row.dataset.topic||'0',row.dataset.topicName||'',row.dataset.image||''));row.remove();preview(null);applySearch();update();});
 row.addEventListener('dragstart',()=>{dragged=row;row.style.opacity='.45';});
 row.addEventListener('dragend',()=>{row.style.opacity='';dragged=null;renumber();});
 row.addEventListener('dragover',e=>{e.preventDefault();if(!dragged||dragged===row)return;const rect=row.getBoundingClientRect();selectedList.insertBefore(dragged,e.clientY<rect.top+rect.height/2?row:row.nextSibling);renumber();});
}
function applySearch(){
 const q=search.value.trim().toLocaleLowerCase();
 const selectedTopic=topicFilter.value;

 availableList.querySelectorAll('.available-row').forEach(row=>{
  const matchesText=q===''||(row.dataset.search||'').includes(q);
  const rowTopic=Number.parseInt(row.dataset.topic||'0',10);
  const matchesTopic=selectedTopic==='all'
   ? true
   : rowTopic===Number.parseInt(selectedTopic,10);

  row.hidden=!(matchesText&&matchesTopic);
 });

 update();
}
document.querySelectorAll('.available-row').forEach(bindAvailable);
document.querySelectorAll('.selected-row').forEach(bindSelected);
search.addEventListener('input',applySearch);
topicFilter.addEventListener('change',applySearch);
const first=selectedList.querySelector('.selected-row')||availableList.querySelector('.available-row');if(first)preview(first);update();
})();
</script>
<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
