<?= $this->extend('layout/tempadmin');?>

<?= $this->section('css') ?>
<style type="text/css">
  /* ══════ FORM ══════ */
  .form-group { margin-bottom:20px; }
  .form-label { display:block; font-size:12.5px; font-weight:700; color:#334155; margin-bottom:7px; }
  .form-label .req { color:#dc2626; }
  .form-hint { font-size:10.5px; color:#94a3b8; margin-top:6px; }

  .form-input, .form-select, .form-textarea {
    width:100%; border:1px solid #e2e8f0; border-radius:10px; padding:11px 14px;
    font-size:13px; font-weight:500; color:#1e293b; background:#fff; transition:all .12s;
    font-family:'Inter',sans-serif;
}
.form-textarea { resize:vertical; min-height:90px; line-height:1.6; }
.form-input:focus, .form-select:focus, .form-textarea:focus {
    outline:none; border-color:#0099b8; box-shadow:0 0 0 3px rgba(0,153,184,.12);
}
.form-input.error, .form-input.error:focus { border-color:#dc2626; box-shadow:0 0 0 3px rgba(220,38,38,.1); }

.input-icon-wrap { position:relative; }
.input-icon-wrap i.left-icon { position:absolute; left:14px; top:50%; transform:translateY(-50%); color:#94a3b8; font-size:12.5px; }
.input-icon-wrap .form-input { padding-left:38px; }
.input-suffix-wrap { position:relative; }
.input-suffix-wrap .form-input { padding-right:46px; }
.input-suffix { position:absolute; right:1px; top:1px; bottom:1px; display:flex; align-items:center; padding:0 13px; background:#f8fafc; border-left:1px solid #e2e8f0; border-radius:0 9px 9px 0; font-size:11.5px; font-weight:700; color:#64748b; }

.btn-primary { background:#0099b8; color:#fff; font-size:13px; font-weight:700; padding:12px 22px; border-radius:10px; display:flex; align-items:center; gap:8px; cursor:pointer; transition:all .15s; box-shadow:0 4px 14px rgba(0,153,184,.3); border:none; }
.btn-primary:hover { background:#007e9a; }
.btn-secondary { background:#fff; color:#475569; border:1px solid #e2e8f0; font-size:13px; font-weight:700; padding:12px 22px; border-radius:10px; display:flex; align-items:center; gap:8px; cursor:pointer; transition:all .15s; }
.btn-secondary:hover { background:#f8fafc; }
.btn-ghost-sm { font-size:11px; font-weight:700; color:#0099b8; display:flex; align-items:center; gap:5px; cursor:pointer; background:none; border:none; padding:0; }
.btn-ghost-sm:hover { color:#007e9a; }

/* ══════ JENIS TOGGLE ══════ */
.jenis-toggle { display:flex; gap:10px; }
.jenis-option { flex:1; position:relative; }
.jenis-option input { position:absolute; opacity:0; width:100%; height:100%; margin:0; cursor:pointer; top:0; left:0; }
.jenis-card { border:1.5px solid #e2e8f0; border-radius:12px; padding:14px 16px; display:flex; align-items:center; gap:12px; transition:all .12s; background:#fff; }
.jenis-icon { width:38px; height:38px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:15px; background:#f1f5f9; color:#94a3b8; flex-shrink:0; transition:all .12s; }
.jenis-name { font-size:13px; font-weight:700; color:#334155; }
.jenis-desc { font-size:10.5px; color:#94a3b8; margin-top:1px; }
.jenis-option input:checked ~ .jenis-card { border-color:#0099b8; background:#f0fbfd; box-shadow:0 0 0 3px rgba(0,153,184,.1); }
.jenis-option input:checked ~ .jenis-card .jenis-icon { background:#0099b8; color:#fff; }
.jenis-option input:checked ~ .jenis-card .jenis-name { color:#0099b8; }
.jenis-option:hover .jenis-card { border-color:#cbd5e1; }

.jenis-badge { font-size:10px; font-weight:700; padding:4px 11px; border-radius:20px; display:inline-flex; align-items:center; gap:5px; }
.jenis-badge.perpus { background:#e0f7fb; color:#0099b8; }
.jenis-badge.info { background:#fdeaf3; color:#c2266e; }

/* ══════ DRIVE PREVIEW CARD ══════ */
.drive-preview { display:flex; gap:14px; align-items:center; border:1.5px dashed #e2e8f0; border-radius:12px; padding:14px 16px; margin-top:12px; background:#f8fafc; }
.drive-preview.filled { border-style:solid; border-color:#e2e8f0; background:#fff; }
.drive-thumb { width:56px; height:56px; border-radius:10px; background:#eef2f7; display:flex; align-items:center; justify-content:center; flex-shrink:0; overflow:hidden; color:#94a3b8; font-size:20px; }
.drive-thumb img { width:100%; height:100%; object-fit:cover; }
.drive-meta { flex:1; min-width:0; }
.drive-meta .fid { font-size:11.5px; font-weight:700; color:#1e293b; font-family:'JetBrains Mono',monospace; word-break:break-all; }
.drive-meta .fstatus { font-size:10.5px; color:#94a3b8; margin-top:2px; }
.drive-meta .fstatus.ok { color:#0f9d58; }
.drive-meta .fstatus.bad { color:#dc2626; }

.empty-icon-box { width:56px; height:56px; border-radius:10px; background:#eef2f7; display:flex; align-items:center; justify-content:center; color:#94a3b8; font-size:18px; }

/* kapasitas quick pills */
.cap-pill-bar { display:flex; gap:6px; margin-top:8px; }
.cap-pill { font-size:10.5px; font-weight:700; color:#64748b; background:#f1f5f9; border:1px solid #e2e8f0; padding:4px 10px; border-radius:7px; cursor:pointer; transition:all .12s; }
.cap-pill:hover { border-color:#0099b8; color:#0099b8; background:#f0fbfd; }
</style>
<?= $this->endSection(); ?>

<?= $this->section('conten');?>
<div class="main-area">

    <!-- TOPBAR -->
    <div class="topbar">
        <div class="flex items-center gap-4">
            <button class="topbar-icon-btn"><i class="fa-solid fa-bars"></i></button>
            <div>
                <div class="text-[10.5px] text-slate-400 font-semibold flex items-center gap-1.5">
                    <a class="hover:text-[#0099b8] cursor-pointer">Perpustakaan</a> <i class="fa-solid fa-chevron-right" style="font-size:8px;"></i> <span class="text-slate-600">Tambah Item</span>
                </div>
                <h1 class="text-lg font-bold text-slate-800">Input Perpustakaan / Infografis <span class="jenis-badge perpus" id="topBadge"><i class="fa-solid fa-book-open"></i> Perpustakaan</span></h1>
            </div>
        </div>
        <div class="flex items-center gap-2">
            <button class="topbar-icon-btn">
                <i class="fa-regular fa-bell"></i>
                <span class="notif-dot">3</span>
            </button>
            <div class="h-7 w-px bg-slate-200 mx-2"></div>
            <div class="flex items-center gap-2.5 cursor-pointer">
                <div class="w-9 h-9 rounded-full bg-gradient-to-br from-[#0099b8] to-[#0066cc] flex items-center justify-center text-white text-sm font-bold">A</div>
                <div class="hidden md:block">
                    <div class="text-xs font-bold text-slate-700">Administrator</div>
                    <div class="text-[10px] text-slate-400">Super Admin</div>
                </div>
            </div>
        </div>
    </div>

    <div class="p-7 space-y-6 max-w-8xl">
        <?php if(session()->getFlashdata('success')): ?>
        <script>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: '<?= session()->getFlashdata('success'); ?>',
                timer: 2000,
                showConfirmButton: false
            });
        </script>
    <?php endif; ?>

    <?php if(session()->getFlashdata('error')): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: '<?= session()->getFlashdata('error'); ?>'
        });
    </script>
<?php endif; ?>

<form  method="post" action="<?= base_url('admin/siminfografis') ?>">

    <!-- JENIS -->
    <div class="panel2 mb-5">
        <div class="panel2-head">
            <div class="panel2-title"><i class="fa-solid fa-layer-group text-[#0099b8] mr-1.5"></i> Jenis Item</div>
        </div>
        <div class="form-group mb-0">
            <div class="jenis-toggle">
                <label class="jenis-option">
                    <input type="radio" name="jenis" value="perpustakaan" checked onchange="onJenisChange()">
                    <div class="jenis-card">
                        <div class="jenis-icon"><i class="fa-solid fa-book-open"></i></div>
                        <div>
                            <div class="jenis-name">Perpustakaan</div>
                            <div class="jenis-desc">E-book, modul, dokumen referensi</div>
                        </div>
                    </div>
                </label>
                <label class="jenis-option">
                    <input type="radio" name="jenis" value="infografis" onchange="onJenisChange()">
                    <div class="jenis-card">
                        <div class="jenis-icon"><i class="fa-solid fa-chart-simple"></i></div>
                        <div>
                            <div class="jenis-name">Infografis</div>
                            <div class="jenis-desc">Poster/gambar visual ringkasan materi</div>
                        </div>
                    </div>
                </label>
            </div>
            <div class="form-hint">Menentukan halaman tampilan: Perpustakaan atau Infografis.</div>
        </div>
    </div>

    <!-- INFORMASI -->
    <div class="panel2 mb-5">
        <div class="panel2-head">
            <div class="panel2-title"><i class="fa-solid fa-circle-info text-[#0099b8] mr-1.5"></i> Informasi Item</div>
        </div>

        <div class="form-group">
            <label class="form-label">Judul <span class="req">*</span></label>
            <div class="input-icon-wrap">
                <i class="fa-solid fa-heading left-icon"></i>
                <input type="text" name="judul" class="form-input" placeholder="Contoh: Modul Dasar Aljabar Linear" id="itemTitle">
            </div>
        </div>

        <div class="form-group">
            <label class="form-label">Keterangan</label>
            <textarea name="keterangan" class="form-textarea" placeholder="Deskripsi singkat mengenai isi/konten item ini..." id="itemDesc"></textarea>
        </div>

        <div class="grid grid-cols-2 gap-4">
            <div class="form-group mb-0">
                <label class="form-label">Kategori <span class="req">*</span></label>
                <select class="form-select" name="kategori" id="itemCategory">
                    <option>Panduan Produktivitas</option>
                    <option>Teknologi Pendidikan</option>
                    <option>Metode Pembelajaran</option>
                    <option>Materi Pelajaran</option>
                    <option>Info Pendidikan</option>
                    <option>Kabar & Kebijakan</option>
                    <option>Umum</option>
                </select>
            </div>
            <div class="form-group mb-0">
                <label class="form-label">Kapasitas File <span class="req">*</span></label>
                <div class="input-suffix-wrap">
                    <input type="number" name="kapasitas" min="0" step="1" class="form-input" placeholder="Contoh: 2450" id="itemSize">
                    <span class="input-suffix">KB</span>
                </div>
                <div class="cap-pill-bar">
                    <span class="cap-pill" onclick="setSize(500)">500 KB</span>
                    <span class="cap-pill" onclick="setSize(1024)">1 MB</span>
                    <span class="cap-pill" onclick="setSize(5120)">5 MB</span>
                    <span class="cap-pill" onclick="setSize(10240)">10 MB</span>
                </div>
            </div>
        </div>
    </div>

    <!-- SUMBER FILE (GOOGLE DRIVE) -->
    <div class="panel2 mb-5">
        <div class="panel2-head">
            <div class="panel2-title"><i class="fa-brands fa-google-drive text-[#0099b8] mr-1.5"></i> Sumber File (Google Drive)</div>
        </div>

        <div class="form-group mb-0">
            <label class="form-label">Tautan / Potongan URL Google Drive <span class="req">*</span></label>
            <div class="input-icon-wrap">
                <i class="fa-solid fa-link left-icon"></i>
                <input type="text" name="tautan" class="form-input" placeholder="Tempel link, mis: https://drive.google.com/file/d/1AbCDefGhIJklmnoPQRstuVWxyz/view atau langsung ID file" id="driveUrl" oninput="onDriveInput()">
            </div>
            <div class="form-hint">Boleh tempel link lengkap Google Drive maupun hanya ID filenya saja — sistem otomatis mendeteksi ID file dari link.</div>

            <!-- preview area -->
            <div class="drive-preview" id="drivePreview">
                <div class="empty-icon-box"><i class="fa-brands fa-google-drive"></i></div>
                <div class="drive-meta">
                    <div class="fid" style="color:#94a3b8;font-weight:600;">Belum ada link yang ditempel</div>
                    <div class="fstatus">Preview & ID file akan muncul otomatis di sini</div>
                </div>
            </div>
        </div>
    </div>

    <!-- AKSI -->
    <div class="flex items-center justify-end gap-3">
        <button type="button" class="btn-secondary"><i class="fa-solid fa-xmark"></i> Batal</button>
        <button type="submit" class="btn-primary" onclick="simpanItem()"><i class="fa-solid fa-circle-check"></i> Simpan Item</button>
    </div>
</form>

<!-- FOOTER -->
<div class="flex items-center justify-between pt-2 text-[11px] text-slate-400 font-medium">
    <span>&copy; 2026 Pena Ilmu. All rights reserved.</span>
    <span>Versi 1.0.0</span>
</div>

</div>
</div>
<?= $this->endSection(); ?>

<?= $this->section('myscript') ?>
<script>
    const topBadge = document.getElementById('topBadge');
    const driveUrlInput = document.getElementById('driveUrl');
    const drivePreview = document.getElementById('drivePreview');

        // ══════ JENIS ITEM: ubah label/badge sesuai pilihan ══════
    function onJenisChange() {
        const jenis = document.querySelector('input[name="jenis"]:checked').value;
        if (jenis === 'perpustakaan') {
            topBadge.className = 'jenis-badge perpus';
            topBadge.innerHTML = '<i class="fa-solid fa-book-open"></i> Perpustakaan';
        } else {
            topBadge.className = 'jenis-badge info';
            topBadge.innerHTML = '<i class="fa-solid fa-chart-simple"></i> Infografis';
        }
    }

    function setSize(kb) {
        document.getElementById('itemSize').value = kb;
    }

        // ══════ Ekstrak ID file Google Drive dari berbagai format link ══════
    function extractDriveId(input) {
        const val = input.trim();
        if (!val) return null;

            // format: https://drive.google.com/file/d/FILE_ID/view...
        let m = val.match(/\/d\/([a-zA-Z0-9_-]{15,})/);
        if (m) return m[1];

            // format: https://drive.google.com/open?id=FILE_ID  atau ...?id=FILE_ID
        m = val.match(/[?&]id=([a-zA-Z0-9_-]{15,})/);
        if (m) return m[1];

            // format: https://drive.google.com/uc?export=view&id=FILE_ID (sudah tercakup di atas)

            // kalau user langsung tempel ID-nya saja (tanpa url)
        if (/^[a-zA-Z0-9_-]{15,}$/.test(val)) return val;

        return null;
    }

    function onDriveInput() {
        const fileId = extractDriveId(driveUrlInput.value);

        if (!fileId) {
            drivePreview.classList.remove('filled');
            if (!driveUrlInput.value.trim()) {
                drivePreview.innerHTML = `
                <div class="empty-icon-box"><i class="fa-brands fa-google-drive"></i></div>
                <div class="drive-meta">
                <div class="fid" style="color:#94a3b8;font-weight:600;">Belum ada link yang ditempel</div>
                <div class="fstatus">Preview & ID file akan muncul otomatis di sini</div>
                </div>`;
            } else {
                drivePreview.innerHTML = `
                <div class="empty-icon-box" style="color:#dc2626;background:#fef2f2;"><i class="fa-solid fa-triangle-exclamation"></i></div>
                <div class="drive-meta">
                <div class="fid" style="color:#dc2626;">Link tidak dikenali</div>
                <div class="fstatus bad">Pastikan link berupa URL Google Drive yang valid atau ID file</div>
                </div>`;
            }
            driveUrlInput.classList.toggle('error', !!driveUrlInput.value.trim());
            return;
        }

        driveUrlInput.classList.remove('error');
        drivePreview.classList.add('filled');
        const thumbUrl = `https://drive.google.com/thumbnail?id=${fileId}&sz=w200`;
        drivePreview.innerHTML = `
        <div class="drive-thumb">
        <img src="${thumbUrl}" alt="preview" onerror="this.parentElement.innerHTML='<i class=\\'fa-brands fa-google-drive\\'></i>'">
        </div>
        <div class="drive-meta">
        <div class="fid">${fileId}</div>
        <div class="fstatus ok"><i class="fa-solid fa-circle-check"></i> ID file terdeteksi</div>
        </div>
        <a href="https://drive.google.com/file/d/${fileId}/view" target="_blank" class="btn-ghost-sm"><i class="fa-solid fa-arrow-up-right-from-square"></i> Buka</a>
        `;
    }

        // ══════ Kumpulkan payload untuk dikirim ke backend ══════
    function simpanItem() {
        const fileId = extractDriveId(driveUrlInput.value);
        const payload = {
                jenis: document.querySelector('input[name="jenisItem"]:checked').value, // "perpustakaan" atau "infografis"
                judul: document.getElementById('itemTitle').value,
                keterangan: document.getElementById('itemDesc').value,
                kategori: document.getElementById('itemCategory').value,
                kapasitas_kb: Number(document.getElementById('itemSize').value) || 0,
                drive_url: driveUrlInput.value.trim(),
                drive_file_id: fileId
            };
            console.log('Payload yang akan dikirim ke server:', payload);
            // TODO: kirim payload ini ke endpoint backend, mis:
            // fetch('/api/perpustakaan', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) })
            // Backend menyimpan kolom "jenis" (perpustakaan/infografis) sehingga masing-masing
            // halaman tinggal query WHERE jenis = 'perpustakaan' atau WHERE jenis = 'infografis'.
        }
    </script>
    <?= $this->endSection(); ?>