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

<?= $this->section('css') ?>
<style type="text/css">
  /* ===== PERPUSTAKAAN ===== */
  .buku-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 14px; display: flex; gap: 12px; transition: box-shadow 0.15s, border-color 0.15s; }
  .buku-card:hover { box-shadow: 0 4px 16px rgba(45,125,70,0.10); border-color: #86efac; }
  .buku-cover { width: 52px; min-width: 52px; height: 68px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 22px; flex-shrink: 0; }
  .buku-type { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #15803d; margin-bottom: 3px; }
  .buku-title { font-size: 12px; font-weight: 700; color: #1e293b; line-height: 1.4; margin-bottom: 4px; }
  .buku-author { font-size: 10px; color: #94a3b8; margin-bottom: 6px; }
  .buku-tags { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 6px; }
  .buku-tag { font-size: 9px; padding: 2px 7px; border-radius: 10px; background: #f1f5f9; border: 1px solid #e2e8f0; color: #64748b; font-weight: 600; }
  .buku-dl { font-size: 11px; color: #15803d; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
  .buku-dl:hover { color: #166534; }
</style>
<?= $this->endSection(); ?>

<?= $this->section('conten');?>
<main class="max-w-7xl mx-auto px-4 py-8">
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">

        <!-- ===== KONTEN UTAMA ===== -->
        <div class="lg:col-span-3 space-y-4">

            <!-- BAR DETAIL -->
            <div class="bg-gradient-to-r from-green-50 to-emerald-100/50 border border-emerald-100 rounded-xl px-4 py-3 flex flex-wrap items-center justify-between gap-3 shadow-sm">
                <div class="flex items-center gap-3">
                    <a href="<?= base_url()?>" class="bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-[11px] font-bold py-1 px-3 rounded-lg shadow-sm transition">⬅ Kembali</a>
                    <div class="h-4 w-px bg-slate-300"></div>
                    <h2 class="text-xs font-bold text-slate-800 flex items-center gap-1.5 uppercase tracking-wide">
                        Perpustakaan Digital <span>📚</span>
                    </h2>
                </div>
                <span class="bg-[#0099b8] text-white text-[9px] font-bold px-2 py-0.5 rounded-full tracking-wider uppercase">Pena Ilmu Hub</span>
            </div>

            <!-- AREA KONTEN -->
            <div id="mainContent"></div>
        </div>

        <!-- ===== SIDEBAR ===== -->
        <aside class="space-y-4">
            <div class="bg-white border border-slate-200/70 rounded-xl p-4 shadow-sm">
                <h4 class="text-xs font-bold text-slate-800 uppercase tracking-wide border-b border-slate-100 pb-2 mb-3">📋 Dokumen & Template</h4>
                <ul class="space-y-2 text-[11px] font-semibold text-slate-600">
                 <li class="flex items-center justify-between hover:text-[#0099b8] cursor-pointer transition">
                    <span class="flex items-center gap-2"><i class="fa-regular fa-file-word text-blue-600 text-sm w-4 text-center"></i> <a href="<?= base_url('dokumenfile/?type=word')?>">WORD</a></span>
                    <span class="bg-blue-50 text-blue-600 text-[9px] font-bold px-1.5 py-0.5 rounded"><?= $total_word ?></span>
                </li>
                <li class="flex items-center justify-between hover:text-[#0099b8] cursor-pointer transition">
                    <span class="flex items-center gap-2"><i class="fa-regular fa-file-excel text-emerald-600 text-sm w-4 text-center"></i> <a href="<?= base_url('dokumenfile/?type=excel')?>">EXCEL</a></span>
                    <span class="bg-emerald-50 text-emerald-600 text-[9px] font-bold px-1.5 py-0.5 rounded"><?= $total_xls ?></span>
                </li>
                <li class="flex items-center justify-between hover:text-[#0099b8] cursor-pointer transition">
                    <span class="flex items-center gap-2"><i class="fa-regular fa-file-powerpoint text-orange-600 text-sm w-4 text-center"></i> <a href="<?= base_url('dokumenfile/?type=ppt')?>">PPT</a></span>
                    <span class="bg-orange-50 text-orange-600 text-[9px] font-bold px-1.5 py-0.5 rounded"><?= $total_ppt ?></span>
                </li>
                <li class="flex items-center justify-between hover:text-[#0099b8] cursor-pointer transition">
                    <span class="flex items-center gap-2"><i class="fa-regular fa-file-pdf text-red-600 text-sm w-4 text-center"></i><a href="<?= base_url('dokumenfile/?type=pdf')?>"> PDF</a></span>
                    <span class="bg-red-50 text-red-600 text-[9px] font-bold px-1.5 py-0.5 rounded"><?= $total_pdf ?></span>
                </li>
                <li class="flex items-center justify-between hover:text-[#0099b8] cursor-pointer transition">
                    <span class="flex items-center gap-2"><i class="fa-regular fa-file-zipper text-purple-600 text-sm w-4 text-center"></i> <a href="<?= base_url('dokumenfile/?type=zip')?>">ZIP</a></span>
                    <span class="bg-purple-50 text-purple-600 text-[9px] font-bold px-1.5 py-0.5 rounded"><?= $total_zip ?></span>
                </li>
            </ul>
        </div>

        <div class="bg-white border border-slate-200/70 rounded-xl p-4 shadow-sm">
            <h4 class="text-xs font-bold text-slate-800 uppercase tracking-wide border-b border-slate-100 pb-2 mb-3">📚 Jenis Koleksi</h4>
            <ul class="space-y-2.5 text-[11px] font-semibold text-slate-600" id="sidebarTipe"></ul>
        </div>

        <div class="bg-white border border-slate-200/70 rounded-xl p-4 shadow-sm">
            <h4 class="text-xs font-bold text-slate-800 uppercase tracking-wide border-b border-slate-100 pb-2 mb-3">🔥 Koleksi Terbaru</h4>
            <ul class="space-y-2.5 text-[11px] font-semibold text-slate-600" id="sidebarTerbaru"></ul>
        </div>

       <!-- ===== tutorial ===== -->
         <div class="sb-card">
            <div class="sb-head">
                <span class="sb-head-icon"><i class="fa-solid fa-fire text-blue-600"></i></span>
                <span class="sb-head-label">Tutorial Terbaru</span>
                <span class="sb-badge badge-hot">Populer</span>
            </div>

            <!-- tutorial -->
            <?php foreach ($tutorial_terbaru as $doc) : ?>
            <a href="<?= base_url('baca_tutorial/' . $doc['id']); ?>" class="artikel-item flex items-center gap-3 p-3 hover:bg-slate-50 transition border-b border-slate-100 last:border-0">
                <div class="art-thumb flex items-center justify-center w-9 h-9 rounded-lg bg-blue-50 shrink-0">
                    <i class="fa-solid fa-book-open text-blue-600 text-sm"></i>
                </div>
                <div class="flex-1 flex flex-col min-w-0">
                    <span class="art-title text-xs font-semibold text-slate-700 truncate"><?= ucfirst(esc($doc['judul'])); ?><</span>
                    <span class="art-sub text-[10px] text-slate-400 mt-0.5"><i class="fa-regular fa-clock text-[9px] mr-0.5"></i> <?= ucfirst(esc($doc['kategori'])); ?> </span>
                </div>
            </a>
             <?php endforeach; ?>
        </div>
    </aside>
</div>
</main>
<?= $this->endSection(); ?>

<?= $this->section('myscript') ?>
<script>
/* ===================================================================
   DATABASE PERPUSTAKAAN
   Tambah item baru cukup di sini.
=================================================================== */
    const database = <?= $json_database ?? '[]'; ?>;

    let activeFilter = 'Semua';
    let searchQuery   = '';
    let currentPage   = 1;
    const PER_PAGE    = 4;

/* ------- filter ------- */
    function getFiltered() {
        return database.filter(d => {
            const matchKat = activeFilter === 'Semua' || d.kategori === activeFilter;
            const matchSearch = !searchQuery || d.judul.toLowerCase().includes(searchQuery.toLowerCase()) || d.kategori.toLowerCase().includes(searchQuery.toLowerCase());
            return matchKat && matchSearch;
        });
    }

/* ------- card HTML ------- */
    function cardHTML(d) {
        const urlBaca = `<?= base_url('lihat_perpus/'); ?>` + d.id;
        const tagsArray = Array.isArray(d.tags) ? d.tags : ["UMUM","SD","SMP","SMA", "MADRASAH"];
        const tagsHTML = tagsArray.map(t => `<span class="buku-tag">${t}</span>`).join('');
        return `
        <div class="buku-card">
        <div class="buku-cover" style="background:${d.warnaKat}">
        <span style="font-size:24px">${d.icon}</span>
        </div>
        <div style="flex:1;min-width:0">
        <div class="buku-type">${d.kategori}</div>
        <div class="buku-title">${d.judul}</div>
        <div class="buku-author">Pena Ilmu</div>
        <div class="buku-tags">${tagsHTML}</div>
        <div class="buku-dl"><a href="${urlBaca}"><i class="fa-solid fa-download fa-xs"></i> Lihat Dan Unduh</a></div>
        </div>
        </div>
        `;
    }

/* ------- render utama ------- */
    function render() {
        const filtered   = getFiltered();
        const totalPages = Math.ceil(filtered.length / PER_PAGE) || 1;
        if (currentPage > totalPages) currentPage = 1;

        const start    = (currentPage - 1) * PER_PAGE;
        const end      = Math.min(start + PER_PAGE, filtered.length);
        const pageData = filtered.slice(start, end);

        const tipeList = ['Semua', ...new Set(database.map(d => d.kategori))];

    /* chips */
        const chips = tipeList.map(k =>
            `<button onclick="setFilter('${k}')" class="filter-chip ${k === activeFilter ? 'active-green' : ''}">${k}</button>`
            ).join('');

    /* cards */
        const cards = pageData.length > 0
        ? pageData.map(cardHTML).join('')
        : `<div class="text-center py-12 text-slate-400 text-sm font-medium">Tidak ada koleksi ditemukan.</div>`;

    /* info & tombol pagination */
        const infoText   = filtered.length > 0 ? `Menampilkan ${start + 1}–${end} dari ${filtered.length} koleksi` : 'Tidak ada data';
        const prevDisabled = currentPage <= 1;
        const nextDisabled = currentPage >= totalPages;

        const pageButtons = Array.from({length: totalPages}, (_, i) => i + 1).map(p =>
            `<button onclick="goPage(${p})" style="
            width:28px;height:28px;border-radius:6px;border:none;cursor:pointer;
            font-size:11px;font-weight:700;font-family:'Inter',sans-serif;
            background:${p === currentPage ? '#0099b8' : 'transparent'};
            color:${p === currentPage ? '#fff' : '#64748b'};
            ">${p}</button>`
            ).join('');

        document.getElementById('mainContent').innerHTML = `

        <!-- HERO MINI + STAT GABUNG -->
        <div class="page-hero text-white" style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">
        <!-- kiri: teks -->
        <div style="flex:1;min-width:160px;">
        <div style="font-size:15px;font-weight:700;margin-bottom:4px;">Perpustakaan Digital</div>
        <div style="font-size:11.5px;color:rgba(255,255,255,0.78);line-height:1.5;">
        Buku, skripsi, modul, makalah —<br>semua dalam satu tempat
        </div>
        </div>
        <!-- kanan: stat boxes -->
        <div style="display:flex;gap:8px;flex-shrink:0;">
        <div style="background:rgba(255,255,255,0.15);border-radius:10px;padding:10px 18px;text-align:center;min-width:72px;">
        <div style="font-size:20px;font-weight:700;line-height:1;">${database.length}</div>
        <div style="font-size:9px;font-weight:600;letter-spacing:0.06em;text-transform:uppercase;color:rgba(255,255,255,0.75);margin-top:3px;">KOLEKSI</div>
        </div>
        <div style="background:rgba(255,255,255,0.15);border-radius:10px;padding:10px 18px;text-align:center;min-width:72px;">
        <div style="font-size:20px;font-weight:700;line-height:1;">${new Set(database.map(d=>d.kategori)).size}</div>
        <div style="font-size:9px;font-weight:600;letter-spacing:0.06em;text-transform:uppercase;color:rgba(255,255,255,0.75);margin-top:3px;">JENIS</div>
        </div>
        <div style="background:rgba(255,255,255,0.15);border-radius:10px;padding:10px 18px;text-align:center;min-width:72px;">
        <div style="font-size:20px;font-weight:700;line-height:1;color:#86efac;">Gratis</div>
        <div style="font-size:9px;font-weight:600;letter-spacing:0.06em;text-transform:uppercase;color:rgba(255,255,255,0.75);margin-top:3px;">SEMUA</div>
        </div>
        </div>
        </div>

        <!-- SEARCH -->
        <div class="search-wrap">
        <input type="text" id="mainSearch" placeholder="Cari judul, penulis, atau topik..."
        value="${searchQuery}" oninput="onSearch(this.value)">
        <button class="search-btn-green">
        <i class="fa-solid fa-magnifying-glass fa-xs mr-1"></i> Cari
        </button>
        </div>

        <!-- CHIPS FILTER -->
        <div class="chips-scroll">${chips}</div>

        <!-- LIST CARDS -->
        <div style="display:flex;flex-direction:column;gap:10px;">${cards}</div>

        <!-- PAGINATION -->
        <div style="
        display:flex;align-items:center;justify-content:space-between;
        margin-top:18px;padding:10px 14px;
        background:#fff;border:1px solid #e2e8f0;border-radius:10px;
        flex-wrap:wrap;gap:8px;
        ">
        <span style="font-size:11px;color:#374151;font-weight:600;">${infoText}</span>
        <div style="display:flex;align-items:center;gap:4px;">
        <button onclick="goPage(${currentPage - 1})" ${prevDisabled ? 'disabled' : ''} style="
        padding:5px 12px;border-radius:6px;border:1px solid #e2e8f0;
        font-size:11px;font-weight:600;font-family:'Inter',sans-serif;
        cursor:${prevDisabled ? 'not-allowed' : 'pointer'};
        background:#fff;color:${prevDisabled ? '#cbd5e1' : '#374151'};
        ">Prev</button>

        ${pageButtons}

        <button onclick="goPage(${currentPage + 1})" ${nextDisabled ? 'disabled' : ''} style="
        padding:5px 12px;border-radius:6px;border:1px solid #e2e8f0;
        font-size:11px;font-weight:600;font-family:'Inter',sans-serif;
        cursor:${nextDisabled ? 'not-allowed' : 'pointer'};
        background:#fff;color:${nextDisabled ? '#cbd5e1' : '#374151'};
        ">Next</button>
        </div>
        </div>
        `;

        renderSidebar();
    }

/* ------- sidebar ------- */
    function renderSidebar() {
        const tipeList = [...new Set(database.map(d => d.kategori))];
        document.getElementById('sidebarTipe').innerHTML = tipeList.map(t => {
            const count = database.filter(d => d.kategori === t).length;
            return `<li class="flex items-center justify-between hover:text-[#374151] cursor-pointer transition"
            onclick="setFilter('${t}')">
            <span class="flex items-center gap-2"><span class="text-slate-300">•</span> ${t}</span>
            <span class="bg-emerald-50 text-emerald-600 text-[9px] font-bold px-1.5 py-0.5 rounded">${count}</span>
            </li>`;
        }).join('');

        document.getElementById('sidebarTerbaru').innerHTML = database.slice(0, 3).map(d =>
            `<li class="flex items-start gap-1.5 hover:text-[#374151] cursor-pointer transition">
            <span class="text-slate-300 mt-0.5">•</span><span>${d.judul}</span>
            </li>`
            ).join('');
    }

/* ------- event handlers ------- */
    function setFilter(k) {
        activeFilter = k;
        currentPage  = 1;
        render();
        document.getElementById('mainContent').scrollIntoView({ behavior:'smooth', block:'start' });
    }

    function onSearch(val) {
        searchQuery = val;
        currentPage = 1;
        render();
    }

    function goPage(p) {
        const filtered   = getFiltered();
        const totalPages = Math.ceil(filtered.length / PER_PAGE) || 1;
        if (p < 1 || p > totalPages) return;
        currentPage = p;
        render();
        document.getElementById('mainContent').scrollIntoView({ behavior:'smooth', block:'start' });
    }

    function doHeroSearch() {
        const val = document.getElementById('heroSearch').value;
        searchQuery  = val;
        activeFilter = 'Semua';
        currentPage  = 1;
        render();
        const ms = document.getElementById('mainSearch');
        if (ms) ms.value = val;
        document.getElementById('mainContent').scrollIntoView({ behavior:'smooth', block:'start' });
    }

/* ------- init ------- */
    window.onload = () => render();
</script>
<?= $this->endSection(); ?>