<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>

<div class="container-fluid px-4 py-4">
    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="fw-bold text-dark mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-pencil-square text-crimson"></i> Edit Modul Ajar
            </h4>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="/dashboard" class="text-decoration-none text-muted">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="/guru/learning-devices" class="text-decoration-none text-muted">Perangkat Pembelajaran</a></li>
                    <li class="breadcrumb-item"><a href="/guru/learning-devices/rpm/<?= $device['id'] ?>" class="text-decoration-none text-muted">RPM</a></li>
                    <li class="breadcrumb-item active text-dark fw-medium" aria-current="page">Edit Modul</li>
                </ol>
            </nav>
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-info border-0 shadow-sm rounded-pill px-3" data-bs-toggle="modal" data-bs-target="#panduanModal">
                <i class="bi bi-question-circle me-1"></i> Panduan
            </button>
            <button type="button" class="btn btn-outline-danger border-0 shadow-sm rounded-pill px-3" id="btnClearAIFields">
                <i class="bi bi-eraser me-1"></i> Kosongkan Field AI
            </button>

            <a href="/guru/learning-devices/rpm/<?= $device['id'] ?>" class="btn btn-light border-0 shadow-sm text-muted hover-bg-light transition-all rounded-pill px-3">
                <i class="bi bi-arrow-left me-1"></i> Kembali
            </a>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alert-container"></div>

    <!-- TP Navigation Pills -->
    <div class="card shadow-sm border-0 rounded-3 mb-4">
        <div class="card-body p-3">
            <div class="d-flex align-items-center gap-2 mb-2">
                <i class="bi bi-bullseye text-primary"></i>
                <span class="fw-semibold text-dark small">Pilih Tujuan Pembelajaran (TP):</span>
            </div>
            <div class="d-flex flex-wrap gap-2 tp-pills">
                <?php $chapters = json_decode($device['chapters'] ?? '[]', true) ?: []; ?>
                <?php foreach ($chapters as $ci => $cn): ?>
                    <a href="/guru/learning-devices/rpm/<?= $device['id'] ?>/edit/<?= $ci ?>"
                       class="btn btn-sm rounded-pill px-3 <?= ($ci == $chapterIndex) ? 'btn-crimson text-white' : 'btn-outline-secondary' ?>">
                        <?= 'Bab ' . ($ci + 1) . ': ' . esc($cn) ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Main Form -->
    <form id="modulForm">
        <input type="hidden" name="chapter_index" value="<?= $chapterIndex ?>">
        <input type="hidden" name="device_id" value="<?= $device['id'] ?>">

        <!-- Progress Bar -->
        <div class="card shadow-sm border-0 rounded-3 mb-4">
            <div class="card-body p-3">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="small fw-semibold text-dark">Progress Pengisian Modul</span>
                    <span class="small text-muted" id="progress-text">0/15 field terisi</span>
                </div>
                <div class="progress" style="height: 8px; border-radius: 10px;">
                    <div class="progress-bar bg-crimson" id="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
        </div>

        <!-- ======================== ACCORDION ======================== -->
        <div class="accordion" id="accordionModul">

            <!-- ====== I. INFORMASI UMUM ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark" type="button" data-bs-toggle="collapse" data-bs-target="#collapseI">
                        <i class="bi bi-info-circle text-crimson me-2"></i> I. Informasi Umum
                    </button>
                </h2>
                <div id="collapseI" class="accordion-collapse collapse show" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">

                        <!-- 1.1 Identitas Modul (Auto) -->
                        <div class="mb-4">
                            <div class="d-flex align-items-center gap-2 mb-2">
                                <span class="badge bg-success bg-opacity-10 text-success px-3 py-1 rounded-pill"><i class="bi bi-check-circle-fill me-1"></i>Otomatis</span>
                                <span class="fw-semibold text-dark small">1. Identitas Modul</span>
                            </div>
                            <div class="bg-white border rounded p-3 small" style="border-left: 4px solid #198754;">
                                <table class="table table-sm table-borderless mb-0" style="width: auto;">
                                    <tr><td class="fw-medium text-secondary" style="width: 140px;">Nama Penyusun</td><td>: <?= esc($teacher['name'] ?? '-') ?></td></tr>
                                    <tr><td class="fw-medium text-secondary"><?= esc(teacher_id_label($teacher['status_kepegawaian'] ?? null)) ?></td><td>: <?= esc(teacher_id_display($teacher)) ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Institusi</td><td>: <?= esc($settings['school_name'] ?? '-') ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Jenjang</td><td>: <?php
            $phaseJenjang = $device['phase'] ?? '';
            if (($device['school_type'] ?? 'umum') === 'madrasah') {
                echo match($phaseJenjang) { 'A','B','C' => 'MI', 'D' => 'MTs', 'E','F' => 'MA', default => 'Madrasah' };
            } else {
                echo match($phaseJenjang) { 'A','B','C' => 'SD', 'D' => 'SMP', 'E','F' => 'SMA', default => 'Sekolah' };
            }
        ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Mata Pelajaran</td><td>: <?= esc($device['subject_name'] ?? '-') ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Fase / Kelas</td><td>: <?= 'Fase ' . esc($device['phase'] ?? '-') . ' / Kelas ' . esc($device['grade_name'] ?? '-') ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Semester</td><td>: <?= ($chapterTps[0]['semester'] ?? 1) == 1 ? 'Ganjil' : 'Genap' ?> (<?= esc($chapterTps[0]['semester'] ?? 1) ?>)</td></tr>
                                    <tr><td class="fw-medium text-secondary">Bab / Materi</td><td>: <?= esc($chapterName) ?></td></tr>
                                    <tr><td class="fw-medium text-secondary">Alokasi Waktu</td><td>: <?= $totalJp ?> JP (<?= $jumlahPertemuan ?> pertemuan)</td></tr>
                                    <tr><td class="fw-medium text-secondary">Profil Lulusan</td><td>: <?= esc($dplChapterDisplay ?? $device['dpl'] ?? '-') ?></td></tr>
                                    <?php if (($device['school_type'] ?? 'umum') === 'madrasah'): ?>
                                    <tr><td class="fw-medium text-secondary">Topik KBC</td><td>: <?= esc($kbcChapterDisplay ?? $device['panca_cinta'] ?? '-') ?></td></tr>
                                    <?php endif; ?>
                                    <tr><td class="fw-medium text-secondary">Elemen CP</td><td>: <?= esc($cpElementsDisplay ?? '-') ?></td></tr>
                                </table>
                            </div>
                        </div>

                        <!-- 1.2 Kompetensi Awal (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">2. Kompetensi Awal (Prasyarat)</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat kompetensi awal/prasyarat">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Deskripsikan pengetahuan/keterampilan prasyarat yang harus dikuasai siswa sebelum mempelajari materi ini.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="kompetensi_awal"
                                placeholder="Kemampuan yang harus dimiliki siswa sebelum pembelajaran..."><?= esc($modul['kompetensi_awal'] ?? '') ?></textarea>
                        </div>

                        <!-- 1.3 Model & Pendekatan (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">3. Model & Pendekatan Pembelajaran</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat model dan pendekatan">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Tentukan model utama, pendekatan, metode, dan strategi diferensiasi.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="model_pembelajaran"
                                placeholder="Model: ... | Pendekatan: ... | Metode: ... | Diferensiasi: ..."><?= esc($modul['model_pembelajaran'] ?? '') ?></textarea>
                        </div>
<!-- 1.4 Sarana & Prasarana (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">4. Sarana & Prasarana</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat sarana dan prasarana">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Sebutkan media pembelajaran, alat/bahan, dan lingkungan belajar yang diperlukan.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="sarana_prasarana"
                                placeholder="Media, alat, lingkungan belajar, dan materi pendukung..."><?= esc($modul['sarana_prasarana'] ?? '') ?></textarea>
                        </div>

                        <!-- 1.5 Target Peserta Didik (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">5. Target Peserta Didik</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat target peserta didik">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Uraikan kategori peserta didik (reguler, CIBI, hambatan belajar) dan strategi diferensiasinya.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="target_peserta_didik"
                                placeholder="Reguler: ... | CIBI: ... | Hambatan Belajar: ..."><?= esc($modul['target_peserta_didik'] ?? '') ?></textarea>
                        </div>

                        

                    </div>
                </div>
            </div>

            <!-- ====== II. KOMPONEN INTI ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseII">
                        <i class="bi bi-journal-text text-crimson me-2"></i> II. Komponen Inti
                    </button>
                </h2>
                <div id="collapseII" class="accordion-collapse collapse" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">

                        <!-- 2.1 CP (Auto) -->
                        <div class="mb-4">
                            <div class="d-flex align-items-center gap-2 mb-2">
                                <span class="badge bg-success bg-opacity-10 text-success px-3 py-1 rounded-pill"><i class="bi bi-check-circle-fill me-1"></i>Otomatis</span>
                                <span class="fw-semibold text-dark small">1. Capaian Pembelajaran (CP)</span>
                            </div>
                            <div class="bg-white border rounded p-3 small" style="border-left: 4px solid #198754;">
                                <p class="mb-1 text-dark"><?= nl2br(esc($device['cp_content'] ?? 'Belum diisi')) ?></p>
                            </div>
                        </div>

                        <!-- 2.2 TP & Indikator (Auto) -->
                        <div class="mb-4">
                            <div class="d-flex align-items-center gap-2 mb-2">
                                <span class="badge bg-success bg-opacity-10 text-success px-3 py-1 rounded-pill"><i class="bi bi-check-circle-fill me-1"></i>Otomatis</span>
                                <span class="fw-semibold text-dark small">2. Tujuan Pembelajaran (TP) & Indikator Ketercapaian</span>
                            </div>
                            <div class="bg-white border rounded p-3 small" style="border-left: 4px solid #198754;">
                                <?php foreach ($chapterTps as $ctp): ?>
                                <div class="mb-3 pb-2 <?= $ctp !== end($chapterTps) ? 'border-bottom' : '' ?>">
                                    <div class="fw-bold text-dark mb-1"><?= esc($ctp['code']) ?>: <?= esc($ctp['description']) ?></div>
                                    <?php
                                    $indicatorText = '';
                                    if (!empty($chapterKktp)) {
                                        foreach ($chapterKktp as $ck) {
                                            if (isset($ck['tp_id']) && $ck['tp_id'] == $ctp['id']) {
                                                $indicatorText = $ck['indicators'] ?? '';
                                                break;
                                            }
                                        }
                                    }
                                    ?>
                                    <?php if (!empty($indicatorText)): ?>
                                        <div class="text-secondary mb-1">Indikator Ketercapaian:</div>
                                        <ul class="mb-0 ps-3">
                                            <?php foreach (explode("\n", $indicatorText) as $ind): ?>
                                                <?php $ind = trim($ind); if (empty($ind)) continue; ?>
                                                <li><?= esc($ind) ?></li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- 2.3 Pemahaman Bermakna (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">3. Pemahaman Bermakna</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat pemahaman bermakna">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Jelaskan manfaat nyata materi ini bagi kehidupan siswa sehari-hari.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="pemahaman_bermakna"
                                placeholder="Koneksi materi dengan kehidupan nyata..."><?= esc($modul['pemahaman_bermakna'] ?? '') ?></textarea>
                        </div>

                        <!-- 2.4 Pertanyaan Pemantik (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">4. Pertanyaan Pemantik</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat pertanyaan pemantik">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Buat 3-4 pertanyaan yang memantik rasa ingin tahu siswa.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="pertanyaan_pemantik"
                                placeholder="1. Pertanyaan pertama..."><?= esc($modul['pertanyaan_pemantik'] ?? '') ?></textarea>
                        </div>

                        <!-- 2.5 Materi Esensial (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">5. Materi Esensial / Pokok</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat materi esensial">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Uraikan materi pokok secara terstruktur (konsep, fenomena, masalah, karakter).</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="5"
                                data-field="materi_esensial"
                                placeholder="Konsep esensial, konteks fenomena, identifikasi masalah & solusi, integrasi karakter..."><?= esc($modul['materi_esensial'] ?? '') ?></textarea>
                        </div>

                    </div>
                </div>
            </div>

            <!-- ====== III. SKENARIO PEMBELAJARAN ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseIII">
                        <i class="bi bi-calendar-event text-crimson me-2"></i> III. Kegiatan Pembelajaran
                    </button>
                </h2>
                <div id="collapseIII" class="accordion-collapse collapse" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">
                        <!-- SETUP SUB-MATERI (global) -->
                        <div class="bg-white border rounded p-3 mb-3" style="border-left:4px solid #0d6efd;">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <h6 class="fw-bold text-dark mb-0"><i class="bi bi-gear text-primary me-1"></i> Atur Pembagian Materi per Pertemuan</h6>
                                <button type="button" class="btn btn-sm btn-outline-crimson" id="btnGenerateAllSubMateri"><i class="bi bi-cpu-fill me-1"></i> Generate Sub-Materi</button>
                            </div>
                            <p class="text-muted small mb-2 ms-1">Tentukan jumlah pertemuan dengan menambah/mengurangi sub-materi. Setiap sub-materi = 1 pertemuan.</p>
                            <div id="subMateriGlobalContainer">
                                <?php foreach ($subMateriList as $smi => $sm):
                                    $iktps = $iktpList[$smi] ?? [];
                                ?>
                                <div class="sub-materi-global-item mb-2 border rounded p-2 bg-white">
                                    <div class="sub-materi-global-row d-flex align-items-center gap-2">
                                        <span class="small fw-medium text-secondary" style="min-width:95px;">Sub-Materi <?= $smi+1 ?>:</span>
                                        <input type="text" class="form-control form-control-sm sub-materi-global-input" value="<?= esc($sm) ?>" placeholder="Sub-materi <?= $smi+1 ?>" data-index="<?= $smi ?>">
                                        <button type="button" class="btn btn-sm btn-outline-danger remove-global-submateri-btn" data-index="<?= $smi ?>"><i class="bi bi-x"></i></button>
                                    </div>
                                    <div class="iktp-wrapper ms-3 mt-1" data-index="<?= $smi ?>">
                                        <div class="d-flex align-items-center gap-1 mb-1">
                                            <span class="small text-muted" style="font-size:0.75rem;">IKTP:</span>
                                            <button type="button" class="btn btn-sm btn-link text-decoration-none text-primary add-iktp-btn p-0 ms-2" style="font-size:0.75rem;" data-index="<?= $smi ?>"><i class="bi bi-plus-circle me-1"></i>Tambah</button>
                                            <div class="ms-auto">
                                                <button type="button" class="btn btn-sm btn-outline-crimson btn-gen-iktp py-0" style="font-size:0.75rem;" data-index="<?= $smi ?>"><i class="bi bi-cpu-fill me-1"></i> Generate IKTP</button>
                                            </div>
                                        </div>
                                        <?php if (!empty($iktps)): foreach ($iktps as $ik => $iktp): ?>
                                        <div class="iktp-row d-flex align-items-center gap-2 mb-1">
                                            <span class="small text-muted" style="min-width:30px;font-size:0.75rem;"><?= $ik+1 ?>.</span>
                                            <input type="text" class="form-control form-control-sm iktp-input" value="<?= esc($iktp) ?>" placeholder="IKTP <?= $ik+1 ?>" data-index="<?= $smi ?>">
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-iktp-btn py-0" style="font-size:0.7rem;" data-index="<?= $smi ?>"><i class="bi bi-x"></i></button>
                                        </div>
                                        <?php endforeach; else: ?>
                                        <div class="iktp-row d-flex align-items-center gap-2 mb-1">
                                            <span class="small text-muted" style="min-width:30px;font-size:0.75rem;">1.</span>
                                            <input type="text" class="form-control form-control-sm iktp-input" value="" placeholder="IKTP 1" data-index="<?= $smi ?>">
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-iktp-btn py-0" style="font-size:0.7rem;" data-index="<?= $smi ?>"><i class="bi bi-x"></i></button>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-1">
                                <button type="button" class="btn btn-sm btn-link text-decoration-none text-primary" id="btnTambahSubMateri"><i class="bi bi-plus-circle me-1"></i>Tambah Sub Materi</button>
                            </div>
                            <input type="hidden" id="skenarioDataJson" value="<?= esc(json_encode($skenarioData)) ?>">
                        </div>

                        <!-- SKENARIO PERTEMUAN (A/B/C) -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <p class="text-muted small mb-0">Kegiatan pembelajaran per pertemuan.</p>
                            <button type="button" class="btn btn-sm btn-outline-crimson d-none" id="btnGenerateAllSkenario"><i class="bi bi-cpu-fill me-1"></i> Generate Semua Kegiatan</button>
                        </div>
                        <div id="skenarioContainer">
                            <?php foreach ($skenarioData as $sk): $p = $sk["pertemuan"]; ?>
                            <div class="skenario-item mb-3 border rounded bg-white p-3" data-pertemuan="<?= $p ?>">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h6 class="fw-bold text-dark mb-0"><i class="bi bi-bookmark-check text-crimson me-1"></i> Pertemuan ke-<?= $p ?><?php if (!empty($sk['sub_materi'])): ?>: <?= esc($sk['sub_materi']) ?><?php endif; ?></h6>
                                    <button type="button" class="btn btn-sm btn-outline-danger remove-pertemuan-btn" data-pertemuan="<?= $p ?>"><i class="bi bi-trash"></i></button>
                                </div>
                                <div class="mb-2">
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">A</span>
                                        <label class="small fw-medium text-secondary mb-0">Pendahuluan</label>
                                        <div class="ms-auto">
                                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_pendahuluan" data-pertemuan="<?= $p ?>"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                                        </div>
                                    </div>
                                    <textarea class="form-control form-control-sm skenario-field" rows="4" data-pertemuan="<?= $p ?>" data-field="pendahuluan" placeholder="Kegiatan pendahuluan..."><?= esc($sk["pendahuluan"] ?? "") ?></textarea>
                                </div>
                                <div class="mb-2">
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">B</span>
                                        <label class="small fw-medium text-secondary mb-0">Inti</label>
                                        <div class="ms-auto">
                                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_inti" data-pertemuan="<?= $p ?>"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                                        </div>
                                    </div>
                                    <textarea class="form-control form-control-sm skenario-field" rows="6" data-pertemuan="<?= $p ?>" data-field="inti" placeholder="TAHAP 1 - Memahami/Eksplorasi&#10;TAHAP 2 - Memecahkan Masalah/Elaborasi&#10;TAHAP 3 - Mengaplikasi/Konfirmasi"><?= esc($sk["inti"] ?? "") ?></textarea>
                                </div>
                                <div>
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">C</span>
                                        <label class="small fw-medium text-secondary mb-0">Penutup</label>
                                        <div class="ms-auto">
                                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_penutup" data-pertemuan="<?= $p ?>"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                                        </div>
                                    </div>
                                    <textarea class="form-control form-control-sm skenario-field" rows="4" data-pertemuan="<?= $p ?>" data-field="penutup" placeholder="Kegiatan penutup..."><?= esc($sk["penutup"] ?? "") ?></textarea>
                                </div>

                                <!-- LKPD Per Pertemuan -->
                                <div class="mt-3 pt-2 border-top border-2">
                                    <div class="d-flex align-items-center gap-2 mb-1">
                                        <span class="badge bg-success bg-opacity-10 text-success px-2 py-1" style="font-size:0.7rem;">LKPD</span>
                                        <label class="small fw-medium text-secondary mb-0">Lembar Kerja Peserta Didik</label>
                                        <div class="ms-auto">
                                            <button type="button" class="btn btn-sm btn-outline-success btn-gen-lkpd" data-pertemuan="<?= $p ?>"><i class="bi bi-cpu-fill me-1"></i> Generate LKPD</button>
                                        </div>
                                    </div>
                                    <div class="mb-1">
                                        <label class="small text-muted" style="font-size:0.75rem;">Langkah Kegiatan</label>
                                        <textarea class="form-control form-control-sm lkpd-field" rows="3" data-pertemuan="<?= $p ?>" data-lkpd="langkah" placeholder="Langkah-langkah kegiatan siswa dalam LKPD..."><?= esc($sk["lkpd_langkah"] ?? "") ?></textarea>
                                    </div>
                                    <div class="mb-1">
                                        <label class="small text-muted" style="font-size:0.75rem;">Soal/Tugas</label>
                                        <textarea class="form-control form-control-sm lkpd-field" rows="3" data-pertemuan="<?= $p ?>" data-lkpd="soal" placeholder="Soal atau tugas yang dikerjakan siswa..."><?= esc($sk["lkpd_soal"] ?? "") ?></textarea>
                                    </div>
                                    <div>
                                        <label class="small text-muted" style="font-size:0.75rem;">Kesimpulan</label>
                                        <textarea class="form-control form-control-sm lkpd-field" rows="2" data-pertemuan="<?= $p ?>" data-lkpd="kesimpulan" placeholder="Pertanyaan refleksi/kesimpulan..."><?= esc($sk["lkpd_kesimpulan"] ?? "") ?></textarea>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-secondary mt-2" id="btnTambahPertemuan"><i class="bi bi-plus-circle me-1"></i> Tambah Pertemuan</button>

                    </div>
                </div>
            </div>

            <!-- ====== IV. ASESMEN ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseIV">
                        <i class="bi bi-clipboard-check text-crimson me-2"></i> IV. Asesmen (Penilaian)
                    </button>
                </h2>
                <div id="collapseIV" class="accordion-collapse collapse" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">1. Asesmen Awal / Diagnostik</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat asesmen diagnostik">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Buat instrumen asesmen awal untuk mengetahui kesiapan belajar siswa.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="asesmen_diagnostik"
                                placeholder="Pertanyaan-pertanyaan diagnostik untuk mengukur kesiapan siswa..."><?= esc($modul['asesmen_diagnostik'] ?? '') ?></textarea>
                        </div>

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">2. Asesmen Formatif (Proses) & Rubrik</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat asesmen formatif dan rubrik">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Uraikan asesmen proses, rubrik penilaian, dan instrumen observasi.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="asesmen_formatif"
                                placeholder="Bentuk asesmen formatif + rubrik penilaian per aspek..."><?= esc($modul['asesmen_formatif'] ?? '') ?></textarea>
                        </div>

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">3. Asesmen Sumatif (Akhir)</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat asesmen sumatif">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Buat instrumen asesmen akhir untuk mengukur pencapaian seluruh TP.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="asesmen_sumatif"
                                placeholder="Soal-soal sumatif (PG, uraian, praktik)..."><?= esc($modul['asesmen_sumatif'] ?? '') ?></textarea>
                        </div>

                    </div>
                </div>
            </div>

            <!-- ====== V. PENGAYAAN & REMEDIAL ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseV">
                        <i class="bi bi-arrow-up-circle text-crimson me-2"></i> V. Pengayaan & Remedial
                    </button>
                </h2>
                <div id="collapseV" class="accordion-collapse collapse" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">1. Program Pengayaan</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat program pengayaan">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Deskripsikan program pengayaan (proyek, tutor sebaya, riset mini).</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="pengayaan"
                                placeholder="Kegiatan pengayaan untuk siswa yang melampaui KKM..."><?= esc($modul['pengayaan'] ?? '') ?></textarea>
                        </div>

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">2. Program Remedial</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat program remedial">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Deskripsikan program remedial (bimbingan, soal ulang, batas waktu).</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="remedial"
                                placeholder="Program remedial untuk siswa di bawah KKM..."><?= esc($modul['remedial'] ?? '') ?></textarea>
                        </div>

                    </div>
                </div>
            </div>

            <!-- ====== VI. LAMPIRAN ====== -->
            <div class="accordion-item shadow-sm border-0 rounded-3 mb-3 overflow-hidden">
                <h2 class="accordion-header">
                    <button class="accordion-button fw-bold text-dark collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseVI">
                        <i class="bi bi-paperclip text-crimson me-2"></i> VI. Lampiran
                    </button>
                </h2>
                <div id="collapseVI" class="accordion-collapse collapse" data-bs-parent="#accordionModul">
                    <div class="accordion-body bg-light">

                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">1. Glosarium</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat glosarium">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Daftar istilah penting beserta definisinya.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="4"
                                data-field="glosarium"
                                placeholder="Istilah 1: Definisi"><?= esc($modul['glosarium'] ?? '') ?></textarea>
                        </div>

                        <!-- 2. Daftar Pustaka (Generate/Edit) -->
                        <div class="mb-3 field-item">
                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-1 rounded-pill"><i class="bi bi-cpu-fill me-1"></i>AI + Edit</span>
                                    <span class="fw-semibold text-dark small">2. Daftar Pustaka</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-crimson btn-generate-field" data-prompt-hint="Buat daftar pustaka">
                                    <i class="bi bi-cpu-fill me-1"></i> Generate AI
                                </button>
                            </div>
                            <p class="text-muted small mb-1 ms-1">Daftar referensi yang digunakan dalam modul ajar. Generate AI, bisa ditambah/diedit sesuai kebutuhan.</p>
                            <textarea class="form-control form-control-sm field-textarea" rows="6"
                                data-field="daftar_pustaka"
                                placeholder="Kemendikdasmen RI. (2025). Permendikdasmen No. 10 Tahun 2025..."><?= esc($modul['daftar_pustaka'] ?? '') ?></textarea>
                        </div>

                    </div>
                </div>
            </div>

        </div><!-- end accordion -->

    </form>
</div>

<!-- Panduan Modal -->
<div class="modal fade" id="panduanModal" tabindex="-1" aria-labelledby="panduanModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow rounded-3">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold text-dark" id="panduanModalLabel"><i class="bi bi-compass text-primary me-2"></i>Panduan Generate Modul Ajar</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <p class="text-muted small mb-3">Untuk hasil yang maksimal dan koheren, generate field-field dalam urutan berikut. Setiap field menggunakan field sebelumnya sebagai konteks.</p>
                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">1</span>
                            <div><strong>Model & Pendekatan</strong><br><small class="text-muted">Tentukan model utama, pendekatan, metode</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">2</span>
                            <div><strong>Sarana & Prasarana</strong><br><small class="text-muted">Sesuaikan dengan model yang dipilih</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">3</span>
                            <div><strong>Materi Esensial</strong><br><small class="text-muted">Uraian materi pokok terstruktur</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">4</span>
                            <div><strong>Kompetensi Awal</strong><br><small class="text-muted">Prasyarat berdasarkan materi esensial</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">5</span>
                            <div><strong>Pemahaman Bermakna</strong><br><small class="text-muted">Koneksi materi dengan kehidupan nyata</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">6</span>
                            <div><strong>Pertanyaan Pemantik</strong><br><small class="text-muted">Pertanyaan berdasarkan materi esensial</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-primary rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">7</span>
                            <div><strong>Target Peserta Didik</strong><br><small class="text-muted">Kategori dan strategi diferensiasi</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-success rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">8</span>
                            <div><strong>Sub Materi & IKTP</strong><br><small class="text-muted">Generate sub-materi dan IKTP per pertemuan</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-success rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">9</span>
                            <div><strong>Pendahuluan (A)</strong><br><small class="text-muted">Termasuk asesmen diagnostik</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-success rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">10</span>
                            <div><strong>Inti (B)</strong><br><small class="text-muted">Termasuk asesmen formatif berbasis IKTP</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-success rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">11</span>
                            <div><strong>Penutup (C)</strong><br><small class="text-muted">Refleksi dan tindak lanjut</small></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex align-items-center gap-3 p-3 border rounded-3 bg-light bg-opacity-50">
                            <span class="badge bg-success rounded-circle fs-6" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;">12</span>
                            <div><strong>Asesmen Sumatif</strong><br><small class="text-muted">Generate dari BAB/Materi, CP, dan TP</small></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer bg-light border-0">
                <button type="button" class="btn btn-secondary rounded-pill px-4" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>


<!-- Hidden data for JS -->
<script>
window.RPM_DATA = {
    deviceId: <?= $device['id'] ?>,
    chapterIndex: <?= $chapterIndex ?>,
    csrfToken: '<?= csrf_hash() ?>',
    csrfName: '<?= csrf_token() ?>',
    generateUrl: '/guru/learning-devices/rpm/<?= $device['id'] ?>/generate-field',
    saveUrl: '/guru/learning-devices/rpm/<?= $device['id'] ?>/save-field',
    clearUrl: '/guru/learning-devices/rpm/<?= $device['id'] ?>/clear-all-ai',
    previewUrl: '/guru/learning-devices/rpm/<?= $device['id'] ?>/preview/<?= $chapterIndex ?>',
    exportUrl: '/guru/learning-devices/rpm/<?= $device['id'] ?>/export-doc/<?= $chapterIndex ?>',
};
</script>

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

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // ─── Progress Bar ─────────────────────────────────────────
    function updateProgress() {
        const fields = [
            'kompetensi_awal', 'sarana_prasarana', 'target_peserta_didik', 'model_pembelajaran',
            'pemahaman_bermakna', 'pertanyaan_pemantik', 'materi_esensial',
            'skenario_pembelajaran',
            'asesmen_diagnostik', 'asesmen_formatif', 'asesmen_sumatif',
            'pengayaan', 'remedial', 'glosarium', 'daftar_pustaka'
        ];
        let filled = 0;
        fields.forEach(f => {
            const $el = $(`textarea[data-field="${f}"]`);
            if ($el.length && $el.val().trim().length > 0) filled++;
        });
        // Check skenario (stored as JSON)
        const $skenarioFields = $('.skenario-field');
        let hasSkenarioContent = false;
        $skenarioFields.each(function() {
            if ($(this).val().trim().length > 0) hasSkenarioContent = true;
        });
        if (hasSkenarioContent) filled++;

        const pct = Math.round((filled / fields.length) * 100);
        $('#progress-bar').css('width', pct + '%').attr('aria-valuenow', pct);
        $('#progress-text').text(filled + '/' + fields.length + ' field terisi');
    }

    // ─── Dependency Map ─────────────────────────────────────
    const FIELD_DEPENDENCIES = {
        'kompetensi_awal':     { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'sarana_prasarana':    { prerequisites: ['model_pembelajaran'],                                    label: 'Model Pembelajaran' },
        'target_peserta_didik':{ prerequisites: [],                                                        label: '' },
        'model_pembelajaran':  { prerequisites: [],                                                        label: '' },
        'pemahaman_bermakna':  { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'pertanyaan_pemantik': { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'materi_esensial':     { prerequisites: ['model_pembelajaran'],                                    label: 'Model Pembelajaran' },
        'asesmen_diagnostik':  { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'asesmen_formatif':    { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'asesmen_sumatif':     { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'pengayaan':           { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'remedial':            { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'lkpd':                { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
        'glosarium':           { prerequisites: ['materi_esensial'],                                       label: 'Materi Esensial' },
    };

    /**
     * Cek dependensi field. Jika ada yang belum terisi, kembalikan daftar nama field.
     */
    function checkFieldDependencies(fieldKey) {
        const deps = FIELD_DEPENDENCIES[fieldKey];
        if (!deps || !deps.prerequisites || deps.prerequisites.length === 0) return [];

        const missing = [];
        deps.prerequisites.forEach(function(pref) {
            const $el = $(`textarea[data-field="${pref}"]`);
            if (!$el.length || $el.val().trim().length === 0) {
                missing.push(pref);
            }
        });
        return missing;
    }

    /**
     * Cari nama label yang user-friendly dari field key
     */
    function getFieldLabel(fieldKey) {
        const labels = {
            'kompetensi_awal':      'Kompetensi Awal',
            'sarana_prasarana':     'Sarana & Prasarana',
            'target_peserta_didik': 'Target Peserta Didik',
            'model_pembelajaran':   'Model & Pendekatan Pembelajaran',
            'pemahaman_bermakna':   'Pemahaman Bermakna',
            'pertanyaan_pemantik':  'Pertanyaan Pemantik',
            'materi_esensial':      'Materi Esensial',
            'asesmen_diagnostik':   'Asesmen Diagnostik',
            'asesmen_formatif':     'Asesmen Formatif',
            'asesmen_sumatif':      'Asesmen Sumatif',
            'pengayaan':            'Program Pengayaan',
            'remedial':             'Program Remedial',
            'lkpd':                 'LKPD',
            'glosarium':            'Glosarium',
            'sub_materi':           'Sub-Materi per Pertemuan',
            'skenario_pendahuluan': 'Kegiatan Pendahuluan',
            'skenario_inti':        'Kegiatan Inti',
            'skenario_penutup':     'Kegiatan Penutup',
        };
        return labels[fieldKey] || fieldKey;
    }

    /**
     * Cek dependensi dengan konfirmasi hybrid
     * callback = function yang dijalankan jika lanjut generate
     */
    function withDependencyCheck(fieldKey, subMateriNeeded, callback) {
        const missing = checkFieldDependencies(fieldKey);

        // Jika ada dependensi sub_materi (untuk skenario pertemuan)
        if (subMateriNeeded) {
            const $subInputs = $('.sub-materi-global-input');
            let hasSubMateri = false;
            $subInputs.each(function() { if ($(this).val().trim().length > 0) hasSubMateri = true; });
            if (!hasSubMateri && missing.indexOf('sub_materi') === -1) {
                missing.push('sub_materi');
            }
        }

        if (missing.length === 0) {
            callback();
            return;
        }

        const missingLabels = missing.map(function(k) {
            const label = getFieldLabel(k);
            return '<strong>' + label + '</strong>';
        }).join(', ');

        const fieldLabel = getFieldLabel(fieldKey);
        const msg = 'Field <strong>' + fieldLabel + '</strong> membutuhkan ' + missingLabels + ' terisi dahulu agar hasil optimal.<br><br>Tetap generate?';

        Swal.fire({
            title: 'Prasyarat Belum Lengkap',
            html: msg,
            icon: 'info',
            showCancelButton: true,
            confirmButtonColor: '#e83e8c',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Tetap Generate',
            cancelButtonText: 'Isi Dulu',
        }).then(function(result) {
            if (result.isConfirmed) {
                callback();
            } else {
                // Cari field prasyarat pertama dan scroll ke sana
                const firstMissing = missing[0];
                const $target = $(`textarea[data-field="${firstMissing}"]`);
                if ($target.length) {
                    $('html, body').animate({
                        scrollTop: $target.closest('.field-item, .accordion-item').offset().top - 100
                    }, 500);
                    $target.focus();
                }
            }
        });
    }

    // ─── Generate Per Field ───────────────────────────────────
    $(document).on('click', '.btn-generate-field', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const $field = $btn.closest('.field-item');
        const $textarea = $field.find('textarea');
        const fieldKey = $textarea.data('field');
        const promptHint = $btn.data('prompt-hint');

        // Hybrid dependency check
        withDependencyCheck(fieldKey, false, function() {
            const originalHtml = $btn.html();
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Generating...');

            $.ajax({
                url: window.RPM_DATA.generateUrl,
                method: 'POST',
                data: {
                    chapter_index: window.RPM_DATA.chapterIndex,
                    field: fieldKey,
                    prompt_hint: promptHint,
                    [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
                },
                dataType: 'json',
                success: function(res) {
                    if (res.status === 'success') {
                        $textarea.val(res.data.content);
                        $textarea.trigger('input');
                        autoSaveField(fieldKey, res.data.content);

                        if (fieldKey === 'materi_esensial' || fieldKey === 'asesmen_sumatif' || fieldKey === 'glosarium') {
                            let verTitle = 'Periksa Kembali Materi!';
                            let verMsg = 'AI dapat menghasilkan informasi yang tidak akurat.<br><strong>Wajib verifikasi kebenaran</strong> fakta, angka, definisi, dan istilah sebelum digunakan dalam pembelajaran.<br><br>Pastikan sudah sesuai dengan sumber referensi yang valid.';
                            if (fieldKey === 'asesmen_sumatif') {
                                verTitle = 'Verifikasi Soal & Kunci Jawaban!';
                                verMsg = 'Periksa kembali <strong>setiap soal dan kunci jawaban</strong> yang dihasilkan AI.<br>Pastikan:<br>- Soal sesuai dengan BAB/Materi Pokok<br>- Kunci jawaban benar dan tepat<br>- Opsi PG tidak ambigu<br>- Tingkat kesulitan sesuai';
                            } else if (fieldKey === 'glosarium') {
                                verTitle = 'Verifikasi Istilah & Definisi!';
                                verMsg = 'Periksa kembali <strong>setiap istilah dan definisi</strong> yang dihasilkan AI.<br>Pastikan:<br>- Istilah relevan dengan materi bab ini<br>- Definisi akurat dan sesuai kurikulum<br>- Tidak ada istilah yang salah tafsir';
                            }
                            Swal.fire({
                                icon: 'warning',
                                title: verTitle,
                                html: verMsg,
                                confirmButtonColor: '#e83e8c',
                                confirmButtonText: 'Saya akan memverifikasi',
                                timer: 0,
                                allowOutsideClick: false,
                            });
                        } else {
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil',
                                text: res.data.content.substring(0, 100) + '...',
                                timer: 2000,
                                showConfirmButton: false,
                                toast: true,
                                position: 'top-end',
                            });
                        }
                    } else {
                        Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal generate' });
                    }
                },
                error: function() {
                    Swal.fire({ icon: 'error', title: 'Error', text: 'Gagal terhubung ke server.' });
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        });
    });

    // ─── Auto-Save on Change (Debounce 1.5s) ─────────────────
    let saveTimer = null;
    $(document).on('input', '.field-textarea, .skenario-field, .lkpd-field', function() {
        const $textarea = $(this);
        const fieldKey = $textarea.data('field') || 'skenario_pembelajaran';
        const value = $textarea.val();

        clearTimeout(saveTimer);
        $('#save-status').html('<i class="bi bi-arrow-repeat spin-icon text-warning me-1"></i> Menyimpan...');

        saveTimer = setTimeout(function() {
            saveSkenario();
        }, 1500);
    });

    function autoSaveField(field, content) {
        $.ajax({
            url: window.RPM_DATA.saveUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: field,
                content: content,
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    $('#save-status').html('<i class="bi bi-check-circle text-success me-1"></i> Tersimpan');
                    updateProgress();
                } else {
                    $('#save-status').html('<i class="bi bi-exclamation-circle text-danger me-1"></i> Gagal simpan');
                }
            },
            error: function() {
                $('#save-status').html('<i class="bi bi-exclamation-circle text-danger me-1"></i> Gagal simpan');
            }
        });
    }

    function getIktpForPertemuan(idx) {
        const $item = $('.sub-materi-global-item').eq(idx - 1);
        const iktp = [];
        $item.find('.iktp-input').each(function() {
            const v = $(this).val().trim();
            if (v.length > 0) iktp.push(v);
        });
        return iktp;
    }

    function saveSkenario() {
        const pertemuans = [];

        $('.sub-materi-global-item').each(function(i) {
            const p = i + 1;
            const subMateriVal = $(this).find('.sub-materi-global-input').val().trim();

            // Baca IKTP
            const iktp = [];
            $(this).find('.iktp-input').each(function() {
                const v = $(this).val().trim();
                if (v.length > 0) iktp.push(v);
            });

            // Baca A/B/C dari skenario-item yang sesuai
            const $skItem = $('.skenario-item').eq(i);
            const pendahuluan = $skItem.length ? $skItem.find('textarea[data-field="pendahuluan"]').val() : '';
            const inti = $skItem.length ? $skItem.find('textarea[data-field="inti"]').val() : '';
            const penutup = $skItem.length ? $skItem.find('textarea[data-field="penutup"]').val() : '';

            const lkpdLangkah = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="langkah"]').val() || '';
            const lkpdSoal = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="soal"]').val() || '';
            const lkpdKesimpulan = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="kesimpulan"]').val() || '';
            pertemuans.push({
                pertemuan: p,
                judul: subMateriVal || 'Pertemuan ' + p,
                sub_materi: subMateriVal,
                iktp: iktp,
                pendahuluan: pendahuluan,
                inti: inti,
                penutup: penutup,
                lkpd_langkah: lkpdLangkah,
                lkpd_soal: lkpdSoal,
                lkpd_kesimpulan: lkpdKesimpulan,
            });
        });

        $.ajax({
            url: window.RPM_DATA.saveUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: 'skenario_pembelajaran',
                content: JSON.stringify(pertemuans),
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    $('#save-status').html('<i class="bi bi-check-circle text-success me-1"></i> Tersimpan');
                    updateProgress();
                }
            }
        });
    }


    // ─── Save LKPD Terpisah (agar tidak tertimpa auto-save skenario) ──
    function saveLkpd() {
        const pertemuans = [];

        $('.sub-materi-global-item').each(function(i) {
            const p = i + 1;
            const subMateriVal = $(this).find('.sub-materi-global-input').val().trim();
            const lkpdLangkah = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="langkah"]').val() || '';
            const lkpdSoal = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="soal"]').val() || '';
            const lkpdKesimpulan = $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="kesimpulan"]').val() || '';

            pertemuans.push({
                pertemuan: p,
                sub_materi: subMateriVal,
                lkpd_langkah: lkpdLangkah,
                lkpd_soal: lkpdSoal,
                lkpd_kesimpulan: lkpdKesimpulan,
            });
        });

        $.ajax({
            url: window.RPM_DATA.saveUrl + '?type=lkpd',
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: 'skenario_pembelajaran_lkpd',
                content: JSON.stringify(pertemuans),
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    $('#save-status').html('<i class="bi bi-check-circle text-success me-1"></i> Tersimpan');
                }
            }
        });
    }

    // ─── Generate All Skenario ────────────────────────────────
    $('#btnGenerateAllSkenario').on('click', function() {
        const $btn = $(this);
        const pertemuanCount = $('.skenario-item').length;

        // Cek apakah semua sub-materi sudah terisi
        let hasEmptySub = false;
        $('.sub-materi-global-input').each(function() {
            if (!$(this).val().trim()) hasEmptySub = true;
        });

        if (hasEmptySub) {
            Swal.fire({
                title: 'Sub-Materi Belum Lengkap',
                html: 'Beberapa pertemuan belum memiliki sub-materi. Generate sub-materi terlebih dahulu agar hasil optimal.<br><br>Tetap generate?',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#e83e8c',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Tetap Generate',
                cancelButtonText: 'Generate Sub-Materi Dulu',
            }).then(function(result) {
                if (result.isConfirmed) {
                    doGenerateAllSkenario($btn, pertemuanCount);
                } else {
                    $('#btnGenerateAllSubMateri').trigger('click');
                }
            });
            return;
        }

        doGenerateAllSkenario($btn, pertemuanCount);
    });

    function doGenerateAllSkenario($btn, pertemuanCount) {
        let completed = 0;

        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Generating...');

        function generateNext(idx) {
            if (idx > pertemuanCount) {
                $btn.html('<i class="bi bi-cpu-fill me-1"></i> Generate Semua Kegiatan').prop('disabled', false);
                Swal.fire({ icon: 'success', title: 'Selesai!', text: 'Semua skenario tergenerate.', timer: 1500, showConfirmButton: false });
                $('#save-status').html('<i class="bi bi-check-circle text-success me-1"></i> Tersimpan');
                return;
            }

            const $skItem = $('.skenario-item[data-pertemuan="' + idx + '"]');
            const fields = ['pendahuluan', 'inti', 'penutup'];
            let done = 0;

            fields.forEach(function(f) {
                const $ta = $skItem.find('textarea[data-field="' + f + '"]');
                if ($ta.val().trim().length > 0) {
                    done++;
                    if (done === fields.length) generateNext(idx + 1);
                    return;
                }
                    const iktpListSM = getIktpForPertemuan(idx);
                    $.ajax({
                        url: window.RPM_DATA.generateUrl,
                        method: 'POST',
                        data: {
                            chapter_index: window.RPM_DATA.chapterIndex,
                            field: 'skenario_' + f,
                            pertemuan: idx,
                            sub_materi: $('.sub-materi-global-input').eq(idx - 1).val() || '',
                            iktp_list: JSON.stringify(iktpListSM),
                            iktp_count: iktpListSM.length || 3,
                            [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
                        },
                    dataType: 'json',
                    success: function(res) {
                        if (res.status === 'success') {
                            $ta.val(res.data.content);
                        }
                    },
                    complete: function() {
                        done++;
                        if (done === fields.length) generateNext(idx + 1);
                    }
                });
            });
        }

        generateNext(1);
    }

    // ─── Generate Per Bagian Skenario ─────────────────────────
    $(document).on('click', '.generate-field-btn', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const field = $btn.data('field');
        const p = $btn.data('pertemuan');
        const $item = $('.skenario-item[data-pertemuan="' + p + '"]');
        const fieldMap = {'skenario_pendahuluan': 'pendahuluan', 'skenario_inti': 'inti', 'skenario_penutup': 'penutup'};
        const dataField = fieldMap[field] || field;
        const $ta = $item.find('textarea[data-field="' + dataField + '"]');

        // Konversi field ke key dependensi
        const depKey = field === 'skenario_pendahuluan' ? 'pendahuluan' : (field === 'skenario_inti' ? 'inti' : 'penutup');
        const $depField = $('.sub-materi-global-input').eq(p - 1);
        if (!$depField.length || !$depField.val().trim()) {
            Swal.fire({
                title: 'Sub-Materi Belum Diisi',
                html: 'Pertemuan ke-' + p + ' belum memiliki sub-materi. Isi sub-materi terlebih dahulu agar hasil optimal.<br><br>Tetap generate?',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#e83e8c',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Tetap Generate',
                cancelButtonText: 'Isi Dulu',
            }).then(function(result) {
                if (result.isConfirmed) {
                    doSkenarioGenerate($btn, field, p, $ta);
                } else {
                    $('.sub-materi-global-input').eq(p - 1).focus();
                }
            });
            return;
        }

        doSkenarioGenerate($btn, field, p, $ta);
    });

    function doSkenarioGenerate($btn, field, p, $ta) {
        const originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>');

        $.ajax({
            url: window.RPM_DATA.generateUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: field,
                pertemuan: p,
                sub_materi: $('.sub-materi-global-input').eq(p - 1).val() || '',
                iktp_list: JSON.stringify(getIktpForPertemuan(p)),
                iktp_count: ($('.iktp-input', $('.sub-materi-global-item').eq(p - 1)).length) || 3,
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    $ta.val(res.data.content);
                    $ta.trigger('input');
                    saveSkenario();
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal generate' });
                }
            },
            error: function() {
                Swal.fire({ icon: 'error', title: 'Gagal', text: 'Gagal terhubung ke server.' });
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalHtml);
            }
        });
    }

    // ─── Generate LKPD Per Pertemuan ────────────────────────────
    $(document).on('click', '.btn-gen-lkpd', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const p = $btn.data('pertemuan');
        const $subMateri = $('.sub-materi-global-input').eq(p - 1);
        if (!$subMateri.length || !$subMateri.val().trim()) {
            Swal.fire({ icon: 'warning', title: 'Sub-Materi Belum Diisi', text: 'Isi sub-materi pertemuan ' + p + ' terlebih dahulu.' });
            return;
        }
        const originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Generating LKPD...');
        $.ajax({
            url: window.RPM_DATA.generateUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: 'lkpd',
                pertemuan: p,
                sub_materi: $subMateri.val() || '',
                iktp_list: JSON.stringify(getIktpForPertemuan(p)),
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                console.log('LKPD generate response:', res);
                if (res.status === 'success') {
                    const data = res.data;
                    if (data.lkpd_langkah) $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="langkah"]').val(data.lkpd_langkah);
                    if (data.lkpd_soal) $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="soal"]').val(data.lkpd_soal);
                    if (data.lkpd_kesimpulan) $('.lkpd-field[data-pertemuan="' + p + '"][data-lkpd="kesimpulan"]').val(data.lkpd_kesimpulan);
                    console.log('Calling saveLkpd after LKPD generate');
                    saveLkpd();
                    Swal.fire({ icon: 'success', title: 'LKPD Pertemuan ' + p + ' Berhasil', timer: 1500, showConfirmButton: false, toast: true, position: 'top-end' });
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal generate LKPD' });
                }
            },
            error: function(jqXHR, textStatus) {
                console.error('LKPD generate AJAX error:', textStatus, jqXHR.responseText);
                Swal.fire({ icon: 'error', title: 'Gagal', text: 'Gagal terhubung ke server.' });
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalHtml);
            }
        });
    });

    // ─── Generate All Sub Materi (Global) ────────────────────
    $('#btnGenerateAllSubMateri').on('click', function() {
        const $btn = $(this);
        const $inputs = $('.sub-materi-global-input');
        const count = $inputs.length;

        if (count === 0) {
            Swal.fire({ icon: 'warning', title: 'Tidak ada sub-materi', text: 'Tambah dulu beberapa sub-materi.' });
            return;
        }

        // Cek dependensi model_pembelajaran
        withDependencyCheck('sub_materi', false, function() {
            const originalHtml = $btn.html();
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Generating...');

            $.ajax({
                url: window.RPM_DATA.generateUrl,
                method: 'POST',
                data: {
                    chapter_index: window.RPM_DATA.chapterIndex,
                    field: 'sub_materi',
                    sub_materi_count: count,
                    [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
                },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    const lines = res.data.content.split('\n').filter(l => l.trim().length > 0);
                    $inputs.each(function(i) {
                        if (i < lines.length) {
                            $(this).val(lines[i].trim());
                        }
                    });
                    $('#save-status').html('<i class="bi bi-arrow-repeat spin-icon text-warning me-1"></i> Menyimpan...');
                    saveSkenario();
                    Swal.fire({
                        icon: 'success', title: 'Berhasil',
                        text: 'Sub-materi tergenerate (' + lines.length + ' item).',
                        timer: 1500, showConfirmButton: false, toast: true, position: 'top-end',
                    });
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal generate sub-materi.' });
                }
            },
            error: function() {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Gagal terhubung ke server.' });
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalHtml);
            }
        });
        });
    });

    // ─── Tambah Sub Materi → Auto Tambah Pertemuan ABC ─────
    $('#btnTambahSubMateri').on('click', function() {
        const next = $('.sub-materi-global-item').length + 1;

        // Tambah field sub-materi global dengan IKTP
        const $item = $(`
            <div class="sub-materi-global-item mb-2 border rounded p-2 bg-white">
                <div class="sub-materi-global-row d-flex align-items-center gap-2">
                    <span class="small fw-medium text-secondary" style="min-width:95px;">Sub-Materi ${next}:</span>
                    <input type="text" class="form-control form-control-sm sub-materi-global-input" value="" placeholder="Sub-materi ${next}" data-index="${next - 1}">
                    <button type="button" class="btn btn-sm btn-outline-danger remove-global-submateri-btn" data-index="${next - 1}"><i class="bi bi-x"></i></button>
                </div>
                <div class="iktp-wrapper ms-3 mt-1" data-index="${next - 1}">
                    <div class="d-flex align-items-center gap-1 mb-1">
                        <span class="small text-muted" style="font-size:0.75rem;">IKTP:</span>
                        <button type="button" class="btn btn-sm btn-link text-decoration-none text-primary add-iktp-btn p-0 ms-2" style="font-size:0.75rem;" data-index="${next - 1}"><i class="bi bi-plus-circle me-1"></i>Tambah</button>
                        <div class="ms-auto">
                            <button type="button" class="btn btn-sm btn-outline-crimson btn-gen-iktp py-0" style="font-size:0.75rem;" data-index="${next - 1}"><i class="bi bi-cpu-fill me-1"></i> Generate IKTP</button>
                        </div>
                    </div>
                    <div class="iktp-row d-flex align-items-center gap-2 mb-1">
                        <span class="small text-muted" style="min-width:30px;font-size:0.75rem;">1.</span>
                        <input type="text" class="form-control form-control-sm iktp-input" value="" placeholder="IKTP 1" data-index="${next - 1}">
                        <button type="button" class="btn btn-sm btn-outline-danger remove-iktp-btn py-0" style="font-size:0.7rem;" data-index="${next - 1}"><i class="bi bi-x"></i></button>
                    </div>
                </div>
            </div>
        `);
        $('#subMateriGlobalContainer').append($item);

        // Auto tambah pertemuan ABC baru
        appendPertemuanItem(next);

        saveSkenario();
    });

    // ─── Hapus Sub Materi → Auto Hapus Pertemuan ABC ──────
    $(document).on('click', '.remove-global-submateri-btn', function() {
        const $item = $(this).closest('.sub-materi-global-item');
        const idx = $item.index();

        // Hapus item sub-materi (termasuk IKTP)
        $item.remove();

        // Hapus pertemuan ABC yang sesuai (index sama)
        $('.skenario-item').eq(idx).remove();

        // Re-number semua
        renumberAll();

        saveSkenario();
    });

    // ─── Auto-save sub-materi & iktp input ─────────────────
    $(document).on('input', '.sub-materi-global-input, .iktp-input', function() {
        clearTimeout(saveTimer);
        $('#save-status').html('<i class="bi bi-arrow-repeat spin-icon text-warning me-1"></i> Menyimpan...');
        saveTimer = setTimeout(function() {
            saveSkenario();
        }, 1500);
    });

    // ─── Generate IKTP per Sub-Materi ────────────────────────
    $(document).on('click', '.btn-gen-iktp', function() {
        const $btn = $(this);
        const idx = $btn.data('index');
        const $item = $('.sub-materi-global-item').eq(idx);
        const subMateri = $item.find('.sub-materi-global-input').val().trim();
        const $inputs = $item.find('.iktp-input');
        const count = $inputs.length;

        if (!subMateri) {
            Swal.fire({ icon: 'warning', title: 'Sub-materi kosong', text: 'Isi sub-materi terlebih dahulu.' });
            return;
        }

        const originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>');

        $.ajax({
            url: window.RPM_DATA.generateUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: 'iktp',
                sub_materi: subMateri,
                iktp_count: count,
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    const lines = res.data.content.split('\n').filter(l => l.trim().length > 0);
                    $inputs.each(function(i) {
                        if (i < lines.length) {
                            $(this).val(lines[i].trim());
                        }
                    });
                    $('#save-status').html('<i class="bi bi-arrow-repeat spin-icon text-warning me-1"></i> Menyimpan...');
                    saveSkenario();
                    Swal.fire({
                        icon: 'success', title: 'Berhasil',
                        text: 'IKTP tergenerate (' + lines.length + ' indikator).',
                        timer: 1500, showConfirmButton: false, toast: true, position: 'top-end',
                    });
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal generate IKTP.' });
                }
            },
            error: function() {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Gagal terhubung ke server.' });
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalHtml);
            }
        });
    });

    // ─── Tambah IKTP ─────────────────────────────────────────
    $(document).on('click', '.add-iktp-btn', function() {
        const idx = $(this).data('index');
        const $wrapper = $('.iktp-wrapper[data-index="' + idx + '"]');
        const next = $wrapper.find('.iktp-row').length + 1;
        const $row = $(`
            <div class="iktp-row d-flex align-items-center gap-2 mb-1">
                <span class="small text-muted" style="min-width:30px;font-size:0.75rem;">${next}.</span>
                <input type="text" class="form-control form-control-sm iktp-input" value="" placeholder="IKTP ${next}" data-index="${idx}">
                <button type="button" class="btn btn-sm btn-outline-danger remove-iktp-btn py-0" style="font-size:0.7rem;" data-index="${idx}"><i class="bi bi-x"></i></button>
            </div>
        `);
        $wrapper.append($row);
        saveSkenario();
    });

    // ─── Hapus IKTP ──────────────────────────────────────────
    $(document).on('click', '.remove-iktp-btn', function() {
        const $row = $(this).closest('.iktp-row');
        const $wrapper = $row.closest('.iktp-wrapper');
        $row.remove();
        // Re-number
        $wrapper.find('.iktp-row').each(function(i) {
            $(this).find('.text-muted').first().text((i + 1) + '.');
            $(this).find('.iktp-input').attr('placeholder', 'IKTP ' + (i + 1));
        });
        saveSkenario();
    });

    // ─── Helper: Append Skenario Pertemuan Baru ─────────────
    function appendPertemuanItem(num) {
        const html = `
            <div class="skenario-item mb-3 border rounded bg-white p-3" data-pertemuan="${num}">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="fw-bold text-dark mb-0"><i class="bi bi-bookmark-check text-crimson me-1"></i> Pertemuan ke-${num}</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-pertemuan-btn" data-pertemuan="${num}"><i class="bi bi-trash"></i></button>
                </div>
                <div class="mb-2">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">A</span>
                        <label class="small fw-medium text-secondary mb-0">Pendahuluan</label>
                        <div class="ms-auto">
                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_pendahuluan" data-pertemuan="${num}"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                        </div>
                    </div>
                    <textarea class="form-control form-control-sm skenario-field" rows="4"
                        data-pertemuan="${num}" data-field="pendahuluan"
                        placeholder="Kegiatan pendahuluan..."></textarea>
                </div>
                <div class="mb-2">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">B</span>
                        <label class="small fw-medium text-secondary mb-0">Inti</label>
                        <div class="ms-auto">
                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_inti" data-pertemuan="${num}"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                        </div>
                    </div>
                    <textarea class="form-control form-control-sm skenario-field" rows="6"
                        data-pertemuan="${num}" data-field="inti"
                        placeholder="TAHAP 1 - Memahami/Eksplorasi&#10;TAHAP 2 - Memecahkan Masalah/Elaborasi&#10;TAHAP 3 - Mengaplikasi/Konfirmasi"></textarea>
                </div>
                <div>
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <span class="badge bg-primary bg-opacity-10 text-primary px-2 py-1" style="font-size:0.7rem;">C</span>
                        <label class="small fw-medium text-secondary mb-0">Penutup</label>
                        <div class="ms-auto">
                            <button type="button" class="btn btn-sm btn-outline-crimson generate-field-btn" data-field="skenario_penutup" data-pertemuan="${num}"><i class="bi bi-cpu-fill me-1"></i> Generate</button>
                        </div>
                    </div>
                    <textarea class="form-control form-control-sm skenario-field" rows="4"
                        data-pertemuan="${num}" data-field="penutup"
                        placeholder="Kegiatan penutup..."></textarea>
                </div>
            </div>
        `;
        $('#skenarioContainer').append(html);
    }

    // ─── Helper: Renumber All ───────────────────────────────
    function renumberAll() {
        // Renumber global sub-materi items (+ IKTP)
        $('#subMateriGlobalContainer .sub-materi-global-item').each(function(i) {
            $(this).find('.sub-materi-global-row .text-secondary').text('Sub-Materi ' + (i + 1) + ':');
            $(this).find('.sub-materi-global-input')
                .attr('placeholder', 'Sub-materi ' + (i + 1))
                .attr('data-index', i);
            $(this).find('.remove-global-submateri-btn').attr('data-index', i);
            // Update IKTP indices
            $(this).find('.iktp-wrapper').attr('data-index', i);
            $(this).find('.btn-gen-iktp').attr('data-index', i);
            $(this).find('.add-iktp-btn').attr('data-index', i);
            $(this).find('.iktp-input, .remove-iktp-btn').attr('data-index', i);
        });

        // Renumber skenario items
        $('.skenario-item').each(function(i) {
            const num = i + 1;
            $(this).data('pertemuan', num).attr('data-pertemuan', num);
            const $h6 = $(this).find('h6');
            const subMateriText = $('.sub-materi-global-input').eq(i).val().trim();
            if (subMateriText) {
                $h6.html('<i class="bi bi-bookmark-check text-crimson me-1"></i> Pertemuan ke-' + num + ': ' + $('<span>').text(subMateriText).html());
            } else {
                $h6.html('<i class="bi bi-bookmark-check text-crimson me-1"></i> Pertemuan ke-' + num);
            }
            $(this).find('.generate-field-btn, .remove-pertemuan-btn').data('pertemuan', num);
            $(this).find('.skenario-field').data('pertemuan', num);
        });
    }

    // Override Tambah Pertemuan — just add sub-materi instead
    $('#btnTambahPertemuan').on('click', function() {
        $('#btnTambahSubMateri').trigger('click');
    });

    // Override Hapus Pertemuan — sync with sub-materi
    $(document).on('click', '.remove-pertemuan-btn', function() {
        const $item = $(this).closest('.skenario-item');
        const idx = $item.index();

        // Hapus sub-materi + IKTP yang sesuai
        $('#subMateriGlobalContainer .sub-materi-global-item').eq(idx).remove();

        $item.remove();
        renumberAll();
        saveSkenario();
    });
    // ─── Clear All AI Fields ──────────────────────────────────
    $('#btnClearAIFields').on('click', function() {
        Swal.fire({
            title: 'Kosongkan Semua Field AI?',
            html: 'Semua field yang dihasilkan AI akan dikembalikan ke kondisi awal.<br>Data yang diisi manual <strong>tidak akan terpengaruh</strong>.<br><br>Tindakan ini <strong>tidak dapat dibatalkan</strong>.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, kosongkan',
            cancelButtonText: 'Batal',
        }).then(function(result) {
            if (!result.isConfirmed) return;

            $.ajax({
                url: window.RPM_DATA.clearUrl,
                method: 'POST',
                data: {
                    chapter_index: window.RPM_DATA.chapterIndex,
                    [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
                },
                dataType: 'json',
                beforeSend: function() {
                    $('#btnClearAIFields').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Mengosongkan...');
                },
                success: function(res) {
                    if (res.status === 'success') {
                        // Kosongkan semua field-textarea AI
                        $('.field-textarea').val('');

                        // Reset skenario: reload halaman agar controller menginisialisasi ulang
                        location.reload();
                    } else {
                        Swal.fire({ icon: 'error', title: 'Gagal', text: res.message || 'Gagal mengosongkan field.' });
                    }
                },
                error: function() {
                    Swal.fire({ icon: 'error', title: 'Error', text: 'Gagal terhubung ke server.' });
                },
                complete: function() {
                    $('#btnClearAIFields').prop('disabled', false).html('<i class="bi bi-eraser me-1"></i> Kosongkan Field AI');
                }
            });
        });
    });

    // ─── Preview ──────────────────────────────────────────────
    $('#btnPreviewModul').on('click', function() {
        // Save first, then preview
        saveAllFields(function() {
            window.open(window.RPM_DATA.previewUrl, '_blank');
        });
    });

    // ─── Export DOC ────────────────────────────────────────────
    $('#btnExportDoc').on('click', function() {
        saveAllFields(function() {
            window.open(window.RPM_DATA.exportUrl, '_blank');
        });
    });

    function saveAllFields(callback) {
        // Save all regular fields
        const promises = [];
        $('.field-textarea').each(function() {
            const field = $(this).data('field');
            const value = $(this).val();
            if (field) {
                promises.push($.ajax({
                    url: window.RPM_DATA.saveUrl,
                    method: 'POST',
                    data: {
                        chapter_index: window.RPM_DATA.chapterIndex,
                        field: field,
                        content: value,
                        [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
                    },
                    dataType: 'json',
                }));
            }
        });
        // Save skenario
        promises.push($.ajax({
            url: window.RPM_DATA.saveUrl,
            method: 'POST',
            data: {
                chapter_index: window.RPM_DATA.chapterIndex,
                field: 'skenario_pembelajaran',
                content: JSON.stringify(getSkenarioData()),
                [window.RPM_DATA.csrfName]: window.RPM_DATA.csrfToken,
            },
            dataType: 'json',
        }));

        $.when.apply($, promises).done(function() {
            $('#save-status').html('<i class="bi bi-check-circle text-success me-1"></i> Tersimpan');
            if (callback) callback();
        }).fail(function() {
            Swal.fire({ icon: 'error', title: 'Gagal', text: 'Gagal menyimpan data.' });
        });
    }

    function getSkenarioData() {
        const data = [];
        $('.sub-materi-global-item').each(function(i) {
            const subMateriVal = $(this).find('.sub-materi-global-input').val().trim();
            const iktp = [];
            $(this).find('.iktp-input').each(function() {
                const v = $(this).val().trim();
                if (v.length > 0) iktp.push(v);
            });
            const $skItem = $('.skenario-item').eq(i);
            data.push({
                pertemuan: i + 1,
                judul: subMateriVal || 'Pertemuan ' + (i + 1),
                sub_materi: subMateriVal,
                iktp: iktp,
                pendahuluan: $skItem.length ? $skItem.find('textarea[data-field="pendahuluan"]').val() : '',
                inti: $skItem.length ? $skItem.find('textarea[data-field="inti"]').val() : '',
                penutup: $skItem.length ? $skItem.find('textarea[data-field="penutup"]').val() : '',
            });
        });
        return data;
    }

    // ─── Initial Progress ──────────────────────────────────────
    updateProgress();
});
</script>
<style>
.btn-crimson {
    background-color: #e83e8c;
    border-color: #e83e8c;
    color: #fff;
}
.btn-crimson:hover, .btn-crimson:focus {
    background-color: #ca2570;
    border-color: #ca2570;
    color: #fff;
}
.btn-outline-crimson {
    color: #e83e8c;
    border-color: #e83e8c;
}
.btn-outline-crimson:hover {
    background-color: #e83e8c;
    border-color: #e83e8c;
    color: #fff;
}
.bg-crimson {
    background-color: #e83e8c;
}
.text-crimson {
    color: #e83e8c;
}
.accordion-button:not(.collapsed) {
    background-color: #fef0f6;
    color: #e83e8c;
}
.accordion-button:focus {
    box-shadow: none;
    border-color: #e83e8c;
}
.field-item textarea {
    min-height: 80px;
    resize: vertical;
}
.field-item textarea:read-only {
    background-color: #f8f9fa;
    cursor: default;
}
.spin-icon {
    animation: spin 1s linear infinite;
    display: inline-block;
}
@keyframes spin { 100% { transform: rotate(360deg); } }
.tp-pills .btn {
    font-size: 0.85rem;
}
.progress-bar {
    transition: width 0.5s ease;
}
</style>
<?= $this->endSection() ?>
