<?php
$chaptersJson = !empty($device['chapters']) ? $device['chapters'] : (!empty($masterTp['chapters']) ? $masterTp['chapters'] : '[]');
$chapters = json_decode($chaptersJson, true) ?: [];

$isMadrasah = ($device['school_type'] ?? 'umum') === 'madrasah';

// Global DPL/KBC — fallback jika per-chapter belum ada
$dplGlobal = json_decode($device['dpl'] ?? '[]', true) ?: [];
$pcGlobal = json_decode($device['panca_cinta'] ?? '[]', true) ?: [];

// Per-chapter DPL & KBC — format: { "0": ["DPL1","DPL2"], "1": ["DPL3"], ... }
$chapterDplRaw = $device['chapter_dpl'] ?? '{}';
$chapterDplMap = json_decode($chapterDplRaw, true) ?: [];

$chapterKbcRaw = $device['chapter_kbc'] ?? '{}';
$chapterKbcMap = json_decode($chapterKbcRaw, true) ?: [];

// Per-chapter CP Map — format: { "0": ["Elemen A","Elemen B"], "1": ["Elemen C"], ... }
$chapterCpMapRaw = $device['chapter_cp_map'] ?? '{}';
$chapterCpMapInit = json_decode($chapterCpMapRaw, true) ?: [];
// Back-compat: if old format was a string, wrap in array
foreach ($chapterCpMapInit as $k => $v) {
    if (is_string($v)) $chapterCpMapInit[$k] = [$v];
}
?>
<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <h1 class="h3 mb-1 text-gray-800 fw-bold">Tujuan Pembelajaran (TP)</h1>
            <p class="text-muted mb-0 small">Rumuskan Tujuan Pembelajaran secara terstruktur per Bab/Materi Pokok menggunakan AI Co-Pilot.</p>
        </div>
        <div class="d-flex gap-2 align-items-center flex-wrap">
            <div class="d-flex align-items-center gap-2 me-2">
                <label for="jpPerWeekSelect" class="small fw-bold text-muted text-nowrap mb-0"><i class="bi bi-clock-history"></i> JP / Minggu:</label>
                <select id="jpPerWeekSelect" class="form-select form-select-sm border-light-subtle shadow-sm" style="width: 90px; border-radius: 8px;">
                    <?php for($i=1; $i<=10; $i++): ?>
                        <option value="<?= $i ?>" <?= ($device['jp_per_week'] ?? 4) == $i ? 'selected' : '' ?>><?= $i ?> JP</option>
                    <?php endfor; ?>
                </select>
            </div>
            <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-sm btn-outline-secondary py-2 px-3" style="border-radius: 8px;">
                <i class="bi bi-arrow-left"></i> Kembali
            </a>
        </div>
    </div>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert" style="border-radius: 12px; background-color: #f8d7da; color: #842029;">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= session()->getFlashdata('error') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Main Form Column -->
        <div class="col-lg-8">
            
            <!-- CARD 1: DAFTAR BAB / MATERI POKOK -->
            <div class="card border-0 shadow-sm mb-4" style="border-radius: 14px; border-left: 4px solid #4f46e5;">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-0">
                        <i class="bi bi-journal-text text-primary fs-4"></i> 1. Tentukan Bab / Materi Pokok & Karakter
                    </h5>
                    <small class="text-muted">Satu baris per bab: tulis nama bab, pilih Elemen CP, klik tombol DPL<?= $isMadrasah ? '/KBC' : '' ?> untuk integrasi karakter per-bab.</small>
                </div>
                <div class="card-body p-4">
                    <div id="chaptersContainer">
                        <?php if (!empty($chapters)): ?>
                            <?php foreach ($chapters as $cIndex => $chapter):
                                $dplCount = count($chapterDplMap[$cIndex] ?? []);
                                $kbcCount = count($chapterKbcMap[$cIndex] ?? []);
                                $cpCountInit = count($chapterCpMapInit[$cIndex] ?? []);
                            ?>
                            <div class="chapter-row mb-2">
                                <div class="d-flex align-items-center gap-2 flex-nowrap">
                                    <span class="badge bg-secondary py-2 px-3 fw-bold chapter-label text-nowrap" style="min-width: 55px;">Bab <?= $cIndex + 1 ?></span>
                                    <textarea class="form-control form-control-sm chapter-input" placeholder="Nama bab/materi" required style="border-radius: 6px; resize: vertical; min-width: 140px;" rows="1"><?= esc($chapter) ?></textarea>
                                    <button class="btn btn-sm btn-outline-success text-nowrap chapter-cp-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#cpCollapse_<?= $cIndex ?>" aria-expanded="false">
                                        <i class="bi bi-grid-fill me-1"></i> Elemen <span class="chapter-cp-count badge bg-success rounded-pill ms-1"><?= $cpCountInit ?></span>
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary text-nowrap chapter-dpl-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#dplCollapse_<?= $cIndex ?>" aria-expanded="false">
                                        <i class="bi bi-person-badge me-1"></i> DPL <span class="chapter-dpl-count badge bg-primary rounded-pill ms-1"><?= $dplCount ?></span>
                                    </button>
                                    <?php if ($isMadrasah): ?>
                                    <button class="btn btn-sm btn-outline-danger text-nowrap chapter-kbc-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#kbcCollapse_<?= $cIndex ?>" aria-expanded="false">
                                        <i class="bi bi-heart-fill me-1"></i> KBC <span class="chapter-kbc-count badge bg-danger rounded-pill ms-1"><?= $kbcCount ?></span>
                                    </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-outline-danger btn-sm btn-delete-chapter-row text-nowrap" style="border-radius: 6px; <?= count($chapters) === 1 ? 'display: none;' : '' ?>">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                                <!-- COLLAPSE ELEMEN CP -->
                                <div class="collapse" id="cpCollapse_<?= $cIndex ?>">
                                    <div class="card card-body py-2 px-3 mt-1 mb-1 border-0" style="border-radius: 8px; background-color: #f0fdf4;">
                                        <div class="fw-bold small mb-1 text-success"><i class="bi bi-grid-fill me-1"></i>Elemen Capaian Pembelajaran</div>
                                        <div class="row g-1">
                                            <?php $ci = 0; foreach ($cpElementNames as $cpName): ?>
                                            <div class="col-md-6">
                                                <div class="form-check">
                                                    <input class="form-check-input chapter-cp-cb" type="checkbox" value="<?= esc($cpName) ?>"
                                                        data-chapter="<?= $cIndex ?>"
                                                        id="ch_cp_<?= $cIndex ?>_<?= $ci ?>"
                                                        <?= in_array($cpName, $chapterCpMapInit[$cIndex] ?? []) ? 'checked' : '' ?>>
                                                    <label class="form-check-label small" for="ch_cp_<?= $cIndex ?>_<?= $ci ?>"><?= esc($cpName) ?></label>
                                                </div>
                                            </div>
                                            <?php $ci++; endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                                <!-- COLLAPSE DPL -->
                                <div class="collapse" id="dplCollapse_<?= $cIndex ?>">
                                    <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                                        <div class="fw-bold small mb-1 text-primary">8 Dimensi Profil Lulusan</div>
                                        <div class="row g-1">
                                            <?php $i = 0; foreach ($dplList as $dpl): ?>
                                            <div class="col-md-6">
                                                <div class="form-check">
                                                    <input class="form-check-input chapter-dpl-cb" type="checkbox" value="<?= esc($dpl) ?>"
                                                        data-chapter="<?= $cIndex ?>"
                                                        id="ch_dpl_<?= $cIndex ?>_<?= $i ?>"
                                                        <?= in_array($dpl, $chapterDplMap[$cIndex] ?? []) ? 'checked' : '' ?>>
                                                    <label class="form-check-label small" for="ch_dpl_<?= $cIndex ?>_<?= $i ?>"><?= esc($dpl) ?></label>
                                                </div>
                                            </div>
                                            <?php $i++; endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php if ($isMadrasah): ?>
                                <!-- COLLAPSE KBC -->
                                <div class="collapse" id="kbcCollapse_<?= $cIndex ?>">
                                    <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                                        <div class="fw-bold small mb-1 text-danger">Panca Cinta KBC</div>
                                        <div class="row g-1">
                                            <?php $j = 0; foreach ($pancaCintaList as $pc): ?>
                                            <div class="col-md-6">
                                                <div class="form-check">
                                                    <input class="form-check-input chapter-kbc-cb" type="checkbox" value="<?= esc($pc) ?>"
                                                        data-chapter="<?= $cIndex ?>"
                                                        id="ch_kbc_<?= $cIndex ?>_<?= $j ?>"
                                                        <?= in_array($pc, $chapterKbcMap[$cIndex] ?? []) ? 'checked' : '' ?>>
                                                    <label class="form-check-label small" for="ch_kbc_<?= $cIndex ?>_<?= $j ?>"><?= esc($pc) ?></label>
                                                </div>
                                            </div>
                                            <?php $j++; endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                        <div class="chapter-row mb-2">
                            <div class="d-flex align-items-center gap-2 flex-nowrap">
                                <span class="badge bg-secondary py-2 px-3 fw-bold chapter-label text-nowrap" style="min-width: 55px;">Bab 1</span>
                                <textarea class="form-control form-control-sm chapter-input" placeholder="Nama bab/materi" required style="border-radius: 6px; resize: vertical; min-width: 140px;" rows="1"></textarea>
                                <button class="btn btn-sm btn-outline-success text-nowrap chapter-cp-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#cpCollapse_0" aria-expanded="false">
                                    <i class="bi bi-grid-fill me-1"></i> Elemen <span class="chapter-cp-count badge bg-success rounded-pill ms-1">0</span>
                                </button>
                                <button class="btn btn-sm btn-outline-primary text-nowrap chapter-dpl-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#dplCollapse_0" aria-expanded="false">
                                    <i class="bi bi-person-badge me-1"></i> DPL <span class="chapter-dpl-count badge bg-primary rounded-pill ms-1">0</span>
                                </button>
                                <?php if ($isMadrasah): ?>
                                <button class="btn btn-sm btn-outline-danger text-nowrap chapter-kbc-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#kbcCollapse_0" aria-expanded="false">
                                    <i class="bi bi-heart-fill me-1"></i> KBC <span class="chapter-kbc-count badge bg-danger rounded-pill ms-1">0</span>
                                </button>
                                <?php endif; ?>
                                <button type="button" class="btn btn-outline-danger btn-sm btn-delete-chapter-row text-nowrap" style="border-radius: 6px; display: none;">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                            <!-- Collapse Elemen CP -->
                            <div class="collapse" id="cpCollapse_0">
                                <div class="card card-body py-2 px-3 mt-1 mb-1 border-0" style="border-radius: 8px; background-color: #f0fdf4;">
                                    <div class="fw-bold small mb-1 text-success"><i class="bi bi-grid-fill me-1"></i>Elemen Capaian Pembelajaran</div>
                                    <div class="row g-1">
                                        <?php $ci = 0; foreach ($cpElementNames as $cpName): ?>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input chapter-cp-cb" type="checkbox" value="<?= esc($cpName) ?>" data-chapter="0" id="ch_cp_0_<?= $ci ?>">
                                                <label class="form-check-label small" for="ch_cp_0_<?= $ci ?>"><?= esc($cpName) ?></label>
                                            </div>
                                        </div>
                                        <?php $ci++; endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <!-- Collapse DPL -->
                            <div class="collapse" id="dplCollapse_0">
                                <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                                    <div class="fw-bold small mb-1 text-primary">8 Dimensi Profil Lulusan</div>
                                    <div class="row g-1">
                                        <?php $i = 0; foreach ($dplList as $dpl): ?>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input chapter-dpl-cb" type="checkbox" value="<?= esc($dpl) ?>" data-chapter="0" id="ch_dpl_0_<?= $i ?>">
                                                <label class="form-check-label small" for="ch_dpl_0_<?= $i ?>"><?= esc($dpl) ?></label>
                                            </div>
                                        </div>
                                        <?php $i++; endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php if ($isMadrasah): ?>
                            <!-- Collapse KBC -->
                            <div class="collapse" id="kbcCollapse_0">
                                <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                                    <div class="fw-bold small mb-1 text-danger">Panca Cinta KBC</div>
                                    <div class="row g-1">
                                        <?php $j = 0; foreach ($pancaCintaList as $pc): ?>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input chapter-kbc-cb" type="checkbox" value="<?= esc($pc) ?>" data-chapter="0" id="ch_kbc_0_<?= $j ?>">
                                                <label class="form-check-label small" for="ch_kbc_0_<?= $j ?>"><?= esc($pc) ?></label>
                                            </div>
                                        </div>
                                        <?php $j++; endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>

                    <button type="button" class="btn btn-outline-primary btn-sm mt-2 px-3" id="btnAddChapterRow" style="border-radius: 8px;">
                        <i class="bi bi-plus-circle me-1"></i> + Tambah Bab Baru
                    </button>
                </div>
            </div>

            <!-- CARD 2: RUMUSKAN DENGAN AI CO-PILOT -->
            <div class="card border-0 shadow-sm mb-4" style="border-radius: 14px; border-top: 4px solid #0dcaf0;">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-0">
                        <i class="bi bi-magic text-info fs-4"></i> 2. Rumuskan TP via AI
                    </h5>
                    <small class="text-muted">Centang bab yang ingin di-generate. DPL<?= $isMadrasah ? ' & KBC' : '' ?> akan otomatis terkirim sesuai pilihan per-bab di atas.</small>
                </div>
                <div class="card-body p-4">
                    <form id="formAiGenerate">
                        <?= csrf_field() ?>

                        <!-- Dynamic Checkbox Selection for Chapters -->
                        <div class="mb-4 bg-light p-3 rounded" style="border: 1px solid #e3e6f0; border-radius: 10px;">
                            <label class="form-label fw-bold text-dark small mb-2 d-block">
                                <i class="bi bi-check2-square text-info me-1"></i> Pilih Bab untuk Di-rumuskan:
                            </label>
                            <div id="generatorChaptersWrapper" class="d-flex flex-wrap gap-2">
                                <!-- Will be dynamically populated by Javascript -->
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-sm-6">
                                <label for="tps_per_chapter" class="form-label fw-bold text-dark small mb-1">Target TP per Bab / Materi</label>
                                <div class="input-group">
                                    <input type="number" id="tps_per_chapter" name="tps_per_chapter" class="form-control" value="1" min="1" max="8" style="border-radius: 8px 0 0 8px;">
                                    <span class="input-group-text small">Tujuan per Bab</span>
                                </div>
                                <div class="form-text small text-muted">Saran pelatihan diklat: 4 Tujuan Pembelajaran per Bab.</div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end border-top pt-3">
                            <button type="button" class="btn btn-info text-white fw-bold px-4 shadow-sm" id="btnRunAiGeneration" style="border-radius: 8px; background: linear-gradient(135deg, #0dcaf0 0%, #0d6efd 100%); border: none;">
                                <i class="bi bi-cpu-fill me-1"></i> Rumuskan TP Terpilih via AI
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- CARD 3: TABEL DAFTAR TP -->
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-0">
                        <i class="bi bi-list-stars text-success fs-4"></i> 3. Hasil Rumusan Tujuan Pembelajaran (TP)
                    </h5>
                </div>
                <div class="card-body p-4">
                    <form action="/guru/learning-devices/tp/save/<?= $device['id'] ?>" method="post" id="formSaveTps">
                        <?= csrf_field() ?>
                        <input type="hidden" name="chapters_json" id="hidden_chapters_json" value="<?= esc($chaptersJson) ?>">
                        <input type="hidden" name="chapter_dpl_json" id="hidden_chapter_dpl_json" value="<?= esc($chapterDplRaw) ?>">
                        <?php if ($isMadrasah): ?>
                        <input type="hidden" name="chapter_kbc_json" id="hidden_chapter_kbc_json" value="<?= esc($chapterKbcRaw) ?>">
                        <?php endif; ?>
                        <input type="hidden" name="chapter_cp_map" id="hidden_chapter_cp_map" value="<?= esc($chapterCpMapRaw) ?>">

                        <div class="table-responsive">
                            <table class="table table-hover align-middle table-sm border" id="tpTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="100" class="text-center">Kode TP</th>
                                        <th width="170" class="text-center">Bab/Materi</th>
                                        <th>Deskripsi Tujuan Pembelajaran (TP) <span class="text-danger">*</span></th>
                                        <th width="130" class="text-center">Alokasi JP <span class="text-danger">*</span></th>
                                        <th width="70" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="tpTableBody">
                                    <?php if (!empty($tps)): ?>
                                        <?php foreach ($tps as $index => $tp): ?>
                                            <tr class="tp-row">
                                                <td>
                                                    <input type="text" name="tps[<?= $index ?>][code]" class="form-control text-center fw-bold tp-code-input" value="<?= esc($tp['code']) ?>" placeholder="TP-<?= $index + 1 ?>" style="border-radius: 6px;">
                                                </td>
                                                <td>
                                                    <select name="tps[<?= $index ?>][chapter]" class="form-select form-select-sm tp-chapter-select" style="border-radius: 6px; font-size: 0.82rem;">
                                                        <option value="">-- Pilih Bab --</option>
                                                        <?php foreach ($chapters as $ci => $chap): ?>
                                                        <option value="<?= esc($chap) ?>" <?= ($tp['chapter'] ?? '') === $chap ? 'selected' : '' ?>>Bab <?= $ci + 1 ?>: <?= esc($chap) ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </td>
                                                <td>
                                                    <textarea name="tps[<?= $index ?>][description]" class="form-control tp-desc-input" rows="2" placeholder="Deskripsi Tujuan Pembelajaran..." required style="border-radius: 6px; font-size: 0.88rem; line-height: 1.5;"><?= esc($tp['description']) ?></textarea>
                                                </td>
                                                <td>
                                                    <div class="input-group input-group-sm">
                                                        <input type="number" name="tps[<?= $index ?>][allocated_hours]" class="form-control text-center tp-hours-input" value="<?= esc($tp['allocated_hours']) ?>" min="1" max="100" required style="border-radius: 6px 0 0 6px;">
                                                        <span class="input-group-text small">JP</span>
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-outline-danger btn-sm btn-delete-row" style="border-radius: 6px;">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr id="emptyRowPlaceholder">
                                            <td colspan="4" class="text-center py-4 text-muted small">
                                                <i class="bi bi-info-circle d-block fs-4 mb-2 text-secondary"></i>
                                                Belum ada rumusan TP. Masukkan Bab di atas, centang bab yang ingin dirumuskan pada langkah 2, lalu klik AI Generator.
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="d-flex justify-content-between align-items-center mt-3 mb-4">
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-primary btn-sm px-3" id="btnAddRow" style="border-radius: 6px;">
                                    <i class="bi bi-plus-circle me-1"></i> + Tambah TP Baru Manual
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm px-3" id="btnRecalculateChapter" style="border-radius: 6px;">
                                    <i class="bi bi-arrow-repeat me-1"></i> Recalculate Bab
                                </button>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2 pt-3 border-top">
                            <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-light px-4" style="border-radius: 8px;">
                                Batal
                            </a>
                            <button type="submit" class="btn btn-primary px-4 fw-bold shadow-sm" style="border-radius: 8px; background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%); border: none;">
                                <i class="bi bi-save me-1"></i> Simpan TP
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar Info Column -->
        <div class="col-lg-4">
            <!-- Identity Info Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4 bg-light border-start border-primary border-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-3">Informasi Perangkat</h6>
                    <table class="table table-sm table-borderless mb-0 small text-muted">
                        <tr>
                            <td class="ps-0 py-1" style="width: 100px;">Mata Pelajaran</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1"><?= esc($device['subject_name']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Tingkat Kelas</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1">Kelas <?= esc($device['grade_name']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Fase</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1">Fase <?= esc($device['phase']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Jenis Sekolah</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1"><?= ($device['school_type'] === 'madrasah') ? 'Madrasah (KMA)' : 'Sekolah Umum (Kemdikbud)' ?></td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- Quality Control (QC) Alokasi Waktu Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4 card-qc" style="border-left: 4px solid #4f46e5 !important;">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-3 d-flex align-items-center gap-2">
                        <i class="bi bi-shield-check text-primary"></i> Kontrol Kualitas Alokasi Waktu
                    </h6>
                    <div class="bg-light p-3 rounded mb-3" style="font-size: 0.85rem; border-radius: 8px; border: 1px solid #e3e6f0;">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">Pekan Efektif RPE:</span>
                            <span class="fw-bold text-dark">
                                Ganjil: <span id="qcWeeksS1"><?= $effectiveWeeksS1 ?></span> | Genap: <span id="qcWeeksS2"><?= $effectiveWeeksS2 ?></span>
                            </span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">Beban Belajar:</span>
                            <span class="fw-bold text-primary"><span id="qcJpPerWeek"><?= $device['jp_per_week'] ?? 4 ?></span> JP / Minggu</span>
                        </div>
                        <hr class="my-2 border-light-subtle">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted">Kapasitas Tahunan:</span>
                            <span class="fw-bold text-dark"><span id="qcMaxJp">0</span> JP</span>
                        </div>
                    </div>

                    <div style="font-size: 0.85rem;">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">Total JP Dialokasikan:</span>
                            <span class="fw-bold text-dark"><span id="qcAllocatedJp">0</span> JP</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span class="text-muted">Sisa Kuota JP:</span>
                            <span class="fw-bold" id="qcJpLeft">0 JP</span>
                        </div>
                        
                        <div class="progress mb-3" style="height: 10px; border-radius: 10px;">
                            <div id="qcProgressBar" class="progress-bar bg-success" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>

                        <div id="qcAlertBadge" class="alert p-2 mb-0 text-center fw-bold small" style="border-radius: 8px;">
                            Menghitung...
                        </div>
                    </div>
                </div>
            </div>

            <!-- Capaian Pembelajaran Reference Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h6 class="fw-bold text-dark mb-0">
                        <i class="bi bi-file-earmark-ruled text-success"></i> Teks CP Acuan (Step 2)
                    </h6>
                </div>
                <div class="card-body p-4 pt-2">
                    <div class="bg-light p-3 rounded text-muted small text-justify leading-relaxed" style="max-height: 250px; overflow-y: auto; border: 1px solid #e3e6f0; font-size: 0.82rem; border-radius: 8px;">
                        <?= nl2br(esc($device['cp_content'])) ?>
                    </div>
                </div>
            </div>

            <!-- Guidelines Card -->
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark d-flex align-items-center gap-2 mb-3">
                        <i class="bi bi-info-circle-fill text-primary"></i> Panduan Guru
                    </h6>
                    <p class="text-muted small text-justify leading-relaxed mb-0" style="font-size: 0.85rem;">
                        Tujuan Pembelajaran (TP) menjabarkan kompetensi yang dipelajari siswa per topik materi pokok.
                        <br><br>
                        Tentukan dulu Bab/Materi Anda di langkah 1. Kemudian di langkah 2, centang Bab mana saja yang ingin dirumuskan oleh AI, lalu pilih DPL<?= $isMadrasah ? ' dan Panca Cinta' : '' ?> yang ingin dikaitkan. AI akan merumuskan TP khusus untuk bab-bab terpilih tersebut.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    let tpRowIndex = <?= count($tps) ?>;

    const initialChapters = <?= json_encode($chapters) ?>;
    const cpElementNames = <?= json_encode($cpElementNames) ?>;
    const initialChapterCp = <?= json_encode($chapterCpMapInit) ?>;

    function buildCpCheckboxes(index, selected) {
        let html = '';
        cpElementNames.forEach(function(name, ci) {
            const checked = (selected && selected.includes(name)) ? 'checked' : '';
            html += '<div class="col-md-6"><div class="form-check">' +
                '<input class="form-check-input chapter-cp-cb" type="checkbox" value="' + name + '" data-chapter="' + index + '" id="ch_cp_' + index + '_' + ci + '" ' + checked + '>' +
                '<label class="form-check-label small" for="ch_cp_' + index + '_' + ci + '">' + name + '</label></div></div>';
        });
        return html;
    }

    // — Per-chapter DPL/KBC data dari PHP —
    const initialChapterDpl = <?= json_encode($chapterDplMap) ?>;
    const initialChapterKbc = <?= json_encode($chapterKbcMap) ?>;
    const dplNames = <?= json_encode($dplList) ?>;
    const kbcNames = <?= json_encode($pancaCintaList) ?>;
    const isMadrasah = <?= $isMadrasah ? 'true' : 'false' ?>;

    function buildDplCheckboxes(index, selected) {
        let html = '';
        dplNames.forEach(function(dpl, i) {
            const checked = (selected && selected.includes(dpl)) ? 'checked' : '';
            html += '<div class="col-md-6"><div class="form-check">' +
                '<input class="form-check-input chapter-dpl-cb" type="checkbox" value="' + dpl + '" data-chapter="' + index + '" id="ch_dpl_' + index + '_' + i + '" ' + checked + '>' +
                '<label class="form-check-label small" for="ch_dpl_' + index + '_' + i + '">' + dpl + '</label></div></div>';
        });
        return html;
    }

    function buildKbcCheckboxes(index, selected) {
        let html = '';
        kbcNames.forEach(function(pc, j) {
            const checked = (selected && selected.includes(pc)) ? 'checked' : '';
            html += '<div class="col-md-6"><div class="form-check">' +
                '<input class="form-check-input chapter-kbc-cb" type="checkbox" value="' + pc + '" data-chapter="' + index + '" id="ch_kbc_' + index + '_' + j + '" ' + checked + '>' +
                '<label class="form-check-label small" for="ch_kbc_' + index + '_' + j + '">' + pc + '</label></div></div>';
        });
        return html;
    }

    if (initialChapters.length > 0) {
        $('#chaptersContainer').empty();
        initialChapters.forEach(function(chap, index) {
            const count = index + 1;
            const safeChap = $('<div>').text(chap).html();

            const dplSelected = initialChapterDpl[index] || [];
            const kbcSelected = initialChapterKbc[index] || [];
            const cpSelected = initialChapterCp[index] || [];
            const dplCount = dplSelected.length;
            const kbcCount = kbcSelected.length;
            const cpCount = cpSelected.length;
            const dplShow = '';
            const kbcShow = '';
            const cpShow = '';
            const hideDelete = (count === 1 && initialChapters.length === 1) ? 'display: none;' : '';

            const newRow = `
                <div class="chapter-row mb-2">
                    <div class="d-flex align-items-center gap-2 flex-nowrap">
                        <span class="badge bg-secondary py-2 px-3 fw-bold chapter-label text-nowrap" style="min-width: 55px;">Bab ${count}</span>
                        <textarea class="form-control form-control-sm chapter-input" placeholder="Nama bab/materi" required style="border-radius: 6px; resize: vertical; min-width: 140px;" rows="1">${safeChap}</textarea>
                        <button class="btn btn-sm btn-outline-success text-nowrap chapter-cp-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#cpCollapse_${index}" aria-expanded="false">
                            <i class="bi bi-grid-fill me-1"></i> Elemen <span class="chapter-cp-count badge bg-success rounded-pill ms-1">${cpCount}</span>
                        </button>
                        <button class="btn btn-sm btn-outline-primary text-nowrap chapter-dpl-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#dplCollapse_${index}" aria-expanded="false">
                            <i class="bi bi-person-badge me-1"></i> DPL <span class="chapter-dpl-count badge bg-primary rounded-pill ms-1">${dplCount}</span>
                        </button>
                        ${isMadrasah ? `
                        <button class="btn btn-sm btn-outline-danger text-nowrap chapter-kbc-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#kbcCollapse_${index}" aria-expanded="false">
                            <i class="bi bi-heart-fill me-1"></i> KBC <span class="chapter-kbc-count badge bg-danger rounded-pill ms-1">${kbcCount}</span>
                        </button>` : ''}
                        <button type="button" class="btn btn-outline-danger btn-sm btn-delete-chapter-row text-nowrap" style="border-radius: 6px; ${hideDelete}">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="collapse ${cpShow}" id="cpCollapse_${index}">
                        <div class="card card-body py-2 px-3 mt-1 mb-1 border-0" style="border-radius: 8px; background-color: #f0fdf4;">
                            <div class="fw-bold small mb-1 text-success"><i class="bi bi-grid-fill me-1"></i>Elemen Capaian Pembelajaran</div>
                            <div class="row g-1">${buildCpCheckboxes(index, cpSelected)}</div>
                        </div>
                    </div>
                    <div class="collapse ${dplShow}" id="dplCollapse_${index}">
                        <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                            <div class="fw-bold small mb-1 text-primary">8 Dimensi Profil Lulusan</div>
                            <div class="row g-1">${buildDplCheckboxes(index, dplSelected)}</div>
                        </div>
                    </div>
                    ${isMadrasah ? `
                    <div class="collapse ${kbcShow}" id="kbcCollapse_${index}">
                        <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                            <div class="fw-bold small mb-1 text-danger">Panca Cinta KBC</div>
                            <div class="row g-1">${buildKbcCheckboxes(index, kbcSelected)}</div>
                        </div>
                    </div>` : ''}
                </div>
            `;

            $('#chaptersContainer').append(newRow);
        });
    }

    updateGeneratorChapterCheckboxes();

    $('#formSaveTps').on('submit', function(e) {
        // Cek apakah sudah ada TP sebelumnya → beri peringatan
        const existingTpCount = $('#tpTableBody .tp-row').length;
        const hasExistingData = <?= !empty($tps) ? 'true' : 'false' ?>;

        if (hasExistingData && existingTpCount > 0) {
            e.preventDefault();
            const form = this;
            Swal.fire({
                icon: 'warning',
                title: 'Perhatian!',
                html: `
                    <div class="text-start">
                        <p class="fw-bold mb-2 text-danger"><i class="bi bi-exclamation-triangle me-1"></i> Menyimpan ulang TP akan menghapus data berikut:</p>
                        <ul class="text-muted small">
                            <li>ATP (Alur Tujuan Pembelajaran)</li>
                            <li>KKTP (Kriteria Ketercapaian TP)</li>
                            <li>PROTA & PROMES</li>
                            <li>Modul Ajar (RPM) yang sudah digenerate</li>
                        </ul>
                        <p class="text-warning fw-semibold small mb-0"><i class="bi bi-info-circle me-1"></i> Pastikan Anda telah mengekspor data yang diperlukan sebelum menyimpan!</p>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonColor: '#e83e8c',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="bi bi-check-lg me-1"></i> Ya, Simpan TP',
                cancelButtonText: 'Batal',
                reverseButtons: true,
            }).then((result) => {
                if (result.isConfirmed) {
                    collectChapterData();
                    form.submit();
                }
            });
            return false;
        }

        // Jika tidak ada data sebelumnya, lanjut normal
        collectChapterData();
    });

    // Helper: collect per-chapter data untuk disimpan
    function collectChapterData() {
        const chaptersList = [];
        $('.chapter-row').each(function(idx) {
            const val = $(this).find('.chapter-input').val().trim();
            if (val) chaptersList.push(val);
        });
        $('#hidden_chapters_json').val(JSON.stringify(chaptersList));

        // Per-chapter DPL
        const chapterDplMap = {};
        $('.chapter-row').each(function(idx) {
            const vals = [];
            $(this).find('.chapter-dpl-cb:checked').each(function() {
                vals.push($(this).val());
            });
            if (vals.length > 0) chapterDplMap[idx] = vals;
        });
        $('#hidden_chapter_dpl_json').val(JSON.stringify(chapterDplMap));

        // Per-chapter KBC
        const chapterKbcMap = {};
        <?php if ($isMadrasah): ?>
        $('.chapter-row').each(function(idx) {
            const vals = [];
            $(this).find('.chapter-kbc-cb:checked').each(function() {
                vals.push($(this).val());
            });
            if (vals.length > 0) chapterKbcMap[idx] = vals;
        });
        $('#hidden_chapter_kbc_json').val(JSON.stringify(chapterKbcMap));
        <?php endif; ?>

        // Per-chapter CP map (multi-select array)
        const chapterCpMapObj = {};
        $('.chapter-row').each(function(idx) {
            const vals = [];
            $(this).find('.chapter-cp-cb:checked').each(function() {
                vals.push($(this).val());
            });
            if (vals.length > 0) chapterCpMapObj[idx] = vals;
        });
        $('#hidden_chapter_cp_map').val(JSON.stringify(chapterCpMapObj));
    }

    // Helper: update placeholders & show/hide empty placeholder
    function updateEmptyPlaceholder() {
        if ($('#tpTableBody .tp-row').length === 0) {
            if ($('#emptyRowPlaceholder').length === 0) {
                $('#tpTableBody').append(`
                    <tr id="emptyRowPlaceholder">
                        <td colspan="4" class="text-center py-4 text-muted small">
                            <i class="bi bi-info-circle d-block fs-4 mb-2 text-secondary"></i>
                            Belum ada rumusan TP. Masukkan Bab di atas, centang bab yang ingin dirumuskan pada langkah 2, lalu klik AI Generator.
                        </td>
                    </tr>
                `);
            }
        } else {
            $('#emptyRowPlaceholder').remove();
        }
    }

    // Helper: Re-index all rows inputs name in the TP table body so they submit properly in array
    function reindexTableInputs() {
        $('#tpTableBody .tp-row').each(function(index) {
            $(this).find('.tp-code-input').attr('name', `tps[${index}][code]`);
            $(this).find('.tp-chapter-select').attr('name', `tps[${index}][chapter]`);
            $(this).find('.tp-desc-input').attr('name', `tps[${index}][description]`);
            $(this).find('.tp-hours-input').attr('name', `tps[${index}][allocated_hours]`);
            
            // Auto update placeholders if code is default TP-X
            const currentCode = $(this).find('.tp-code-input').val();
            if (currentCode.startsWith('TP-')) {
                $(this).find('.tp-code-input').val(`TP-${index + 1}`);
            }
        });
        tpRowIndex = $('#tpTableBody .tp-row').length;
    }

    // Sync Bab Inputs to AI Section Checkboxes
    function updateGeneratorChapterCheckboxes() {
        const container = $('#generatorChaptersWrapper');
        
        // Save current selections
        const selectedChaps = [];
        container.find('.select-chapter-to-gen:checked').each(function() {
            selectedChaps.push($(this).data('row-id'));
        });

        // Check if select-all was checked
        const selectAllChecked = $('#selectAllChapters').length === 0 || $('#selectAllChapters').is(':checked');

        container.empty();

        // Add "Select All" control
        container.append(`
            <div class="form-check w-100 mb-2 border-bottom pb-2">
                <input class="form-check-input" type="checkbox" id="selectAllChapters" ${selectAllChecked ? 'checked' : ''}>
                <label class="form-check-label text-primary fw-bold" for="selectAllChapters" style="cursor: pointer;">
                    Pilih Semua Bab
                </label>
            </div>
        `);

        // Add individual chapter rows
        const rows = $('#chaptersContainer .chapter-row');
        rows.each(function(index) {
            const val = $(this).find('.chapter-input').val().trim();
            const labelText = `Bab ${index + 1}: ${val || '(Belum Diisi)'}`;
            const rowId = `chap_input_${index}`;
            $(this).attr('data-row-id', rowId); // Bind unique reference
            
            const isChecked = selectedChaps.includes(rowId) || (selectedChaps.length === 0 && selectAllChecked);

            container.append(`
                <div class="form-check me-3 mb-2 d-inline-block p-2 border rounded bg-white" style="border-radius: 6px; font-size: 0.88rem; min-width: 200px;">
                    <input class="form-check-input select-chapter-to-gen ms-1" type="checkbox" data-row-id="${rowId}" value="${val}" id="gen_chap_${index}" ${isChecked ? 'checked' : ''} ${val === '' ? 'disabled' : ''}>
                                    <label class="form-check-label ms-2 text-dark fw-bold" style="cursor: pointer;" for="gen_chap_${index}">
                        Bab ${index + 1}: <span class="text-muted fw-normal">${val || '<i class="text-danger">Ketik nama bab dulu...</i>'}</span>
                    </label>
                </div>
            `);
        });
    }

    // Watch inputs changes in Card 1 to trigger dynamic checkbox sync
    $(document).on('input', '.chapter-input', function() {
        updateGeneratorChapterCheckboxes();
    });

    // Dynamic Chapters: Add Row
    $('#btnAddChapterRow').on('click', function() {
        const count = $('#chaptersContainer .chapter-row').length + 1;
        const idx = count - 1;
        const newRow = `
            <div class="chapter-row mb-2">
                <div class="d-flex align-items-center gap-2 flex-nowrap">
                    <span class="badge bg-secondary py-2 px-3 fw-bold chapter-label text-nowrap" style="min-width: 55px;">Bab ${count}</span>
                    <textarea class="form-control form-control-sm chapter-input" placeholder="Nama bab/materi" required style="border-radius: 6px; resize: vertical; min-width: 140px;" rows="1"></textarea>
                    <button class="btn btn-sm btn-outline-success text-nowrap chapter-cp-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#cpCollapse_${idx}" aria-expanded="false">
                        <i class="bi bi-grid-fill me-1"></i> Elemen <span class="chapter-cp-count badge bg-success rounded-pill ms-1">0</span>
                    </button>
                    <button class="btn btn-sm btn-outline-primary text-nowrap chapter-dpl-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#dplCollapse_${idx}" aria-expanded="false">
                        <i class="bi bi-person-badge me-1"></i> DPL <span class="chapter-dpl-count badge bg-primary rounded-pill ms-1">0</span>
                    </button>
                    ${isMadrasah ? `
                    <button class="btn btn-sm btn-outline-danger text-nowrap chapter-kbc-collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#kbcCollapse_${idx}" aria-expanded="false">
                        <i class="bi bi-heart-fill me-1"></i> KBC <span class="chapter-kbc-count badge bg-danger rounded-pill ms-1">0</span>
                    </button>` : ''}
                    <button type="button" class="btn btn-outline-danger btn-sm btn-delete-chapter-row text-nowrap" style="border-radius: 6px;">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
                <div class="collapse" id="cpCollapse_${idx}">
                    <div class="card card-body py-2 px-3 mt-1 mb-1 border-0" style="border-radius: 8px; background-color: #f0fdf4;">
                        <div class="fw-bold small mb-1 text-success"><i class="bi bi-grid-fill me-1"></i>Elemen Capaian Pembelajaran</div>
                        <div class="row g-1">${buildCpCheckboxes(idx, [])}</div>
                    </div>
                </div>
                <div class="collapse" id="dplCollapse_${idx}">
                    <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                        <div class="fw-bold small mb-1 text-primary">8 Dimensi Profil Lulusan</div>
                        <div class="row g-1">${buildDplCheckboxes(idx, [])}</div>
                    </div>
                </div>
                ${isMadrasah ? `
                <div class="collapse" id="kbcCollapse_${idx}">
                    <div class="card card-body py-2 px-3 mt-1 mb-1 bg-light border-0" style="border-radius: 8px;">
                        <div class="fw-bold small mb-1 text-danger">Panca Cinta KBC</div>
                        <div class="row g-1">${buildKbcCheckboxes(idx, [])}</div>
                    </div>
                </div>` : ''}
            </div>
        `;
        $('#chaptersContainer').append(newRow);
        updateChapterRowControls();
        updateGeneratorChapterCheckboxes();
    });

    // Dynamic Chapters: Delete Row
    $(document).on('click', '.btn-delete-chapter-row', function() {
        $(this).closest('.chapter-row').remove();
        updateChapterRowControls();
        updateGeneratorChapterCheckboxes();
    });

    // Helper: update labels and visibility of delete buttons in chapter rows
    function updateChapterRowControls() {
        const rows = $('#chaptersContainer .chapter-row');
        rows.each(function(index) {
            $(this).find('.chapter-label').text(`Bab ${index + 1}`);
        });

        if (rows.length === 1) {
            rows.find('.btn-delete-chapter-row').hide();
        } else {
            rows.find('.btn-delete-chapter-row').show();
        }
    }

    // Select All / Deselect All chapters handler
    $(document).on('change', '#selectAllChapters', function() {
        const isChecked = $(this).is(':checked');
        $('.select-chapter-to-gen').not(':disabled').prop('checked', isChecked);
    });

    $(document).on('change', '.select-chapter-to-gen', function() {
        const allChecked = $('.select-chapter-to-gen:not(:disabled):checked').length === $('.select-chapter-to-gen:not(:disabled)').length;
        $('#selectAllChapters').prop('checked', allChecked);
    });

    // Add manual row to TP table
    $('#btnAddRow').on('click', function() {
        $('#emptyRowPlaceholder').remove();
        const code = `TP-${tpRowIndex + 1}`;
        // Build chapter options from current chapter inputs
        const chapOptions = [];
        $('#chaptersContainer .chapter-row').each(function(ci) {
            const val = $(this).find('.chapter-input').val().trim();
            if (val) chapOptions.push(`<option value="${$('<div>').text(val).html()}">Bab ${ci+1}: ${$('<div>').text(val).html()}</option>`);
        });
        const newRow = `
            <tr class="tp-row">
                <td>
                    <input type="text" name="tps[${tpRowIndex}][code]" class="form-control text-center fw-bold tp-code-input" value="${code}" placeholder="${code}" style="border-radius: 6px;">
                </td>
                <td>
                    <select name="tps[${tpRowIndex}][chapter]" class="form-select form-select-sm tp-chapter-select" style="border-radius: 6px; font-size: 0.82rem;">
                        <option value="">-- Pilih Bab --</option>
                        ${chapOptions.join('')}
                    </select>
                </td>
                <td>
                    <textarea name="tps[${tpRowIndex}][description]" class="form-control tp-desc-input" rows="2" placeholder="Deskripsi Tujuan Pembelajaran..." required style="border-radius: 6px; font-size: 0.88rem; line-height: 1.5;"></textarea>
                </td>
                <td>
                    <div class="input-group input-group-sm">
                        <input type="number" name="tps[${tpRowIndex}][allocated_hours]" class="form-control text-center tp-hours-input" value="8" min="1" max="100" required style="border-radius: 6px 0 0 6px;">
                        <span class="input-group-text small">JP</span>
                    </div>
                </td>
                <td class="text-center">
                    <button type="button" class="btn btn-outline-danger btn-sm btn-delete-row" style="border-radius: 6px;">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            </tr>
        `;
        $('#tpTableBody').append(newRow);
        tpRowIndex++;
        reindexTableInputs();
    });

    // Recalculate chapter assignment
    $('#btnRecalculateChapter').on('click', function() {
        const chapters = [];
        $('#chaptersContainer .chapter-row').each(function() {
            const val = $(this).find('.chapter-input').val().trim();
            if (val) chapters.push(val);
        });
        if (chapters.length === 0) {
            Swal.fire('Perhatian', 'Tidak ada Bab yang terisi di langkah 1.', 'warning');
            return;
        }
        const tpRows = $('#tpTableBody .tp-row');
        const totalTps = tpRows.length;
        const tpsPerChapter = Math.ceil(totalTps / chapters.length);
        tpRows.each(function(idx) {
            const chapIdx = Math.min(Math.floor(idx / tpsPerChapter), chapters.length - 1);
            $(this).find('.tp-chapter-select').val(chapters[chapIdx]);
        });
        Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: 'Bab TP telah di-recalculate!', showConfirmButton: false, timer: 2000 });
    });

    // Delete row from TP table
    $(document).on('click', '.btn-delete-row', function() {
        $(this).closest('tr').remove();
        reindexTableInputs();
        updateEmptyPlaceholder();
    });

    // Generate selected chapters via AI
    $('#btnRunAiGeneration').on('click', function() {
        // Collect checked chapter values
        const chaptersList = [];
        $('.select-chapter-to-gen:checked').each(function() {
            const val = $(this).val().trim();
            if (val !== '') {
                chaptersList.push(val);
            }
        });

        if (chaptersList.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Tidak Ada Bab Terpilih',
                text: 'Silakan ketik nama Bab terlebih dahulu di langkah 1, lalu centang Bab yang ingin di-generate di langkah 2.',
                confirmButtonColor: '#0dcaf0'
            });
            return;
        }

        // Ask for Overwrite vs Append if table has content
        const hasExistingTps = $('#tpTableBody .tp-row').length > 0;
        
        if (hasExistingTps) {
            Swal.fire({
                title: 'Rumuskan TP Terpilih',
                text: `Anda memilih untuk merumuskan TP untuk ${chaptersList.length} Bab. Apakah Anda ingin menimpa (overwrite) atau menambahkan di bawah data yang sudah ada?`,
                icon: 'question',
                showCancelButton: true,
                showDenyButton: true,
                confirmButtonColor: '#ffc107',
                denyButtonColor: '#198754',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Timpa Semua (Hapus Lama)',
                denyButtonText: 'Tambah di Bawah (Append)',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    executeGenerate(chaptersList, true);
                } else if (result.isDenied) {
                    executeGenerate(chaptersList, false);
                }
            });
        } else {
            executeGenerate(chaptersList, true);
        }
    });

    function executeGenerate(chaptersList, overwrite) {
        // Collect per-chapter DPL, KBC & CP Elements from chapter-row checkboxes
        const chapterDplMap = {};
        const chapterKbcMap = {};
        const chapterCpGenMap = {};
        // Build a mapping of chapter text → row index for matching with chaptersList
        const allRows = $('#chaptersContainer .chapter-row');
        allRows.each(function(idx) {
            const dplVals = [];
            $(this).find('.chapter-dpl-cb:checked').each(function() {
                dplVals.push($(this).val());
            });
            if (dplVals.length > 0) chapterDplMap[idx] = dplVals;
            const kbcVals = [];
            $(this).find('.chapter-kbc-cb:checked').each(function() {
                kbcVals.push($(this).val());
            });
            if (kbcVals.length > 0) chapterKbcMap[idx] = kbcVals;
            const cpVals = [];
            $(this).find('.chapter-cp-cb:checked').each(function() {
                cpVals.push($(this).val());
            });
            if (cpVals.length > 0) chapterCpGenMap[idx] = cpVals;
        });

        const tpsPerChapter = $('#tps_per_chapter').val();

        Swal.fire({
            title: 'Menyusun TP Terpilih via AI...',
            html: `<p>AI Co-pilot sedang menganalisis CP dan merumuskan TP untuk <strong>${chaptersList.length} Bab</strong> terpilih.</p><p class="text-danger small">Proses ini memakan waktu sekitar 10-20 detik.</p>`,
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        $.ajax({
            url: '/guru/learning-devices/tp/generate/<?= $device['id'] ?>',
            method: 'POST',
            data: {
                chapters: chaptersList,
                chapter_dpl_map: JSON.stringify(chapterDplMap),
                chapter_kbc_map: JSON.stringify(chapterKbcMap),
                chapter_cp_map: JSON.stringify(chapterCpGenMap),
                tps_per_chapter: tpsPerChapter,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    if (overwrite) {
                        $('#tpTableBody').empty();
                        tpRowIndex = 0;
                    }

                    $('#emptyRowPlaceholder').remove();
                    
                    const tps = res.data;
                    tps.forEach(function(tp) {
                        const code = tp.code || `TP-${tpRowIndex + 1}`;
                        const hours = tp.allocated_hours || 8;
                        const chapVal = tp.chapter || '';
                        // Build chapter options
                        const chapOptions = initialChapters.map((c, ci) => {
                            const escaped = $('<div>').text(c).html();
                            const sel = (c === chapVal) ? 'selected' : '';
                            return `<option value="${escaped}" ${sel}>Bab ${ci+1}: ${escaped}</option>`;
                        }).join('');
                        const rowHtml = `
                            <tr class="tp-row">
                                <td>
                                    <input type="text" name="tps[${tpRowIndex}][code]" class="form-control text-center fw-bold tp-code-input" value="${code}" placeholder="${code}" style="border-radius: 6px;">
                                </td>
                                <td>
                                    <select name="tps[${tpRowIndex}][chapter]" class="form-select form-select-sm tp-chapter-select" style="border-radius: 6px; font-size: 0.82rem;">
                                        <option value="">-- Pilih Bab --</option>
                                        ${chapOptions}
                                    </select>
                                </td>
                                <td>
                                    <textarea name="tps[${tpRowIndex}][description]" class="form-control tp-desc-input" rows="2" placeholder="Deskripsi Tujuan Pembelajaran..." required style="border-radius: 6px; font-size: 0.88rem; line-height: 1.5;">${tp.description}</textarea>
                                </td>
                                <td>
                                    <div class="input-group input-group-sm">
                                        <input type="number" name="tps[${tpRowIndex}][allocated_hours]" class="form-control text-center tp-hours-input" value="${hours}" min="1" max="100" required style="border-radius: 6px 0 0 6px;">
                                        <span class="input-group-text small">JP</span>
                                    </div>
                                </td>
                                <td>
                                    <button type="button" class="btn btn-outline-danger btn-sm btn-delete-row" style="border-radius: 6px;">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        `;
                        $('#tpTableBody').append(rowHtml);
                        tpRowIndex++;
                    });

                    reindexTableInputs();
                    updateEmptyPlaceholder();

                    Swal.fire({
                        icon: 'success',
                        title: 'TP Berhasil Dirumuskan!',
                        text: `Draf TP untuk ${chaptersList.length} Bab terpilih berhasil ditambahkan ke tabel.`,
                        confirmButtonColor: '#4f46e5'
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal Merumuskan',
                        text: res.message,
                        confirmButtonColor: '#6c757d'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error Sistem',
                    text: 'Gagal menghubungi server AI. Silakan coba lagi.',
                    confirmButtonColor: '#6c757d'
                });
            }
        });
    }

    // Initialize visibility of row delete buttons in chapter inputs
    updateChapterRowControls();
    updateGeneratorChapterCheckboxes();

    // Update CP badge count when checkboxes change
    $(document).on('change', '.chapter-cp-cb', function() {
        const row = $(this).closest('.chapter-row');
        const count = row.find('.chapter-cp-cb:checked').length;
        row.find('.chapter-cp-count').text(count);
    });

    // Update DPL badge count when checkboxes change
    $(document).on('change', '.chapter-dpl-cb', function() {
        const row = $(this).closest('.chapter-row');
        const count = row.find('.chapter-dpl-cb:checked').length;
        row.find('.chapter-dpl-count').text(count);
    });

    // Update KBC badge count when checkboxes change
    $(document).on('change', '.chapter-kbc-cb', function() {
        const row = $(this).closest('.chapter-row');
        const count = row.find('.chapter-kbc-cb:checked').length;
        row.find('.chapter-kbc-count').text(count);
    });

    // === QUALITY CONTROL (QC) FUNCTIONS ===
    function calculateQC() {
        const weeksS1 = parseInt($('#qcWeeksS1').text()) || 0;
        const weeksS2 = parseInt($('#qcWeeksS2').text()) || 0;
        const totalWeeks = weeksS1 + weeksS2;
        const jpPerWeek = parseInt($('#jpPerWeekSelect').val()) || 4;

        // update info boxes
        $('#qcJpPerWeek').text(jpPerWeek);
        const maxJp = totalWeeks * jpPerWeek;
        $('#qcMaxJp').text(maxJp);

        // calculate current allocated JP
        let totalAllocated = 0;
        $('.tp-hours-input').each(function() {
            totalAllocated += parseInt($(this).val()) || 0;
        });
        $('#qcAllocatedJp').text(totalAllocated);

        // calculate sisa
        const sisa = maxJp - totalAllocated;
        const jpLeftEl = $('#qcJpLeft');
        if (sisa >= 0) {
            jpLeftEl.text(sisa + ' JP').removeClass('text-danger').addClass('text-success');
        } else {
            jpLeftEl.text(sisa + ' JP (Over Limit)').removeClass('text-success').addClass('text-danger');
        }

        // calculate percentage
        const percentage = maxJp > 0 ? Math.round((totalAllocated / maxJp) * 100) : 0;
        const progressBar = $('#qcProgressBar');
        progressBar.css('width', percentage + '%').attr('aria-valuenow', percentage);

        const alertBadge = $('#qcAlertBadge');
        if (percentage <= 100) {
            progressBar.removeClass('bg-danger').addClass('bg-success');
            alertBadge.html('<i class="bi bi-check-circle-fill"></i> Status: AMAN (Terpakai ' + percentage + '%)')
                      .removeClass('alert-danger text-danger alert-warning text-warning').addClass('alert-success text-success');
        } else {
            progressBar.removeClass('bg-success').addClass('bg-danger');
            alertBadge.html('<i class="bi bi-exclamation-triangle-fill"></i> Status: OVER-CAPACITY (' + percentage + '%)')
                      .removeClass('alert-success text-success alert-warning text-warning').addClass('alert-danger text-danger');
        }
    }

    // Initialize QC on load
    calculateQC();

    // Listen to changes in TP hours inputs
    $(document).on('input change', '.tp-hours-input', calculateQC);

    // Listen to adding/deleting rows (which also changes inputs count)
    $(document).on('click', '.btn-delete-row, #btnAddTpRow, #btnAddRow, #btnRunAiGeneration, #btnSaveTps', function() {
        setTimeout(calculateQC, 300);
    });

    // Update JP per minggu via AJAX
    $('#jpPerWeekSelect').on('change', function() {
        const val = $(this).val();
        $.ajax({
            url: '/guru/learning-devices/update-jp-per-week',
            type: 'POST',
            data: {
                device_id: deviceId,
                jp_per_week: val,
                '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
            },
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        toast: true,
                        position: 'top-end',
                        icon: 'success',
                        title: res.message,
                        showConfirmButton: false,
                        timer: 2000
                    });
                    calculateQC();
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal memperbarui JP per minggu.', 'error');
            }
        });
    });
});
</script>
<style>
.leading-relaxed {
    line-height: 1.6;
}
.text-justify {
    text-align: justify;
}
</style>
<?= $this->endSection() ?>

<?= $this->endSection() ?>
