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

<?= $this->section('css') ?>
<style>
    body { font-family: 'Inter', sans-serif; }

    /* ===== CARD INFOGRAFIS ===== */
    .infografis-card {
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 16px;
        overflow: hidden;
        transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        display: flex;
        flex-direction: column;
        box-shadow: 0 1px 3px rgba(0,0,0,0.04);
    }
    .infografis-card:hover { 
        transform: translateY(-3px);
        box-shadow: 0 12px 24px -6px rgba(0, 136, 170, 0.15); 
        border-color: #38bdf8; 
    }

    /* Container Gambar */
    .infografis-thumb {
        height: 220px; /* Bikin thumbnail lebih tinggi sedikit agar infografis kelihatan jelas */
        width: 100%;
        position: relative;
        background: #f8fafc;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px; /* Memberi sedikit jarak manis agar gambar tidak menempel garis border */
    }

/* Gambar Infografis */
.drive-icon {
    width: 100%;          /* UBAH DARI 50% KE 100% agar lebar memenuhi area */
    height: 100%;
    object-fit: contain;  /* UBAH DARI cover KE contain agar SELURUH GAMBAR kelihatan tanpa terpotong */
    object-position: center;
    transition: transform 0.3s ease;
}

.infografis-card:hover .drive-icon {
    transform: scale(1.05); /* Efek zoom halus saat hover */
}

.badge-gratis {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(16, 185, 129, 0.9);
    backdrop-filter: blur(4px);
    color: #fff;
    font-size: 9px;
    font-weight: 700;
    padding: 3px 9px;
    border-radius: 20px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    z-index: 2;
}

.infografis-body { 
    padding: 14px 14px 8px; 
    flex: 1; 
    display: flex;
    flex-direction: column;
}

.info-cat {
    font-size: 9px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    margin-bottom: 4px;
}

.info-title {
    font-size: 13px;
    font-weight: 700;
    color: #0f172a;
    line-height: 1.4;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2; /* Batasi maksimal 2 baris agar tinggi card seragam */
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.info-meta-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 10px;
    color: #64748b;
    margin-top: auto;
    padding-top: 6px;
}

.info-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    margin: 8px 14px 14px;
    padding: 8px 0;
    border-radius: 10px;
    border: 1.5px solid #0099b8;
    background: transparent;
    color: #0099b8;
    font-size: 11px;
    font-weight: 700;
    cursor: pointer;
    font-family: 'Inter', sans-serif;
    transition: all 0.2s ease;
}

.info-btn:hover { 
    background: #0099b8; 
    color: #fff; 
    box-shadow: 0 4px 10px rgba(0, 153, 184, 0.25);
}

/* ===== FILTER CHIPS ===== */
.filter-chip {
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    border: 1px solid #e2e8f0;
    color: #64748b;
    cursor: pointer;
    background: #fff;
    transition: all 0.15s ease;
    font-family: 'Inter', sans-serif;
    white-space: nowrap;
}
.filter-chip:hover { background: #f1f5f9; color: #0f172a; }
.filter-chip.active-blue { background: #0099b8; color: #fff; border-color: #0099b8; }

/* ===== SEARCH BAR ===== */
.search-wrap { display: flex; gap: 8px; margin-bottom: 14px; }
.search-wrap input {
    flex: 1;
    padding: 9px 14px;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    font-size: 12px;
    font-family: 'Inter', sans-serif;
    outline: none;
    color: #1e293b;
    background: #fff;
    transition: border-color 0.15s;
}
.search-wrap input:focus { border-color: #0099b8; box-shadow: 0 0 0 3px rgba(0, 153, 184, 0.1); }

.search-btn-blue {
    padding: 9px 18px;
    border-radius: 10px;
    border: none;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    font-family: 'Inter', sans-serif;
    color: #fff;
    background: #0099b8;
    transition: opacity 0.15s;
}
.search-btn-blue:hover { opacity: 0.9; }

.page-hero {
    border-radius: 16px;
    padding: 20px 24px;
    margin-bottom: 16px;
    background: linear-gradient(135deg, #005580 0%, #0088aa 100%);
    box-shadow: 0 4px 12px rgba(0, 85, 128, 0.15);
}

/* Grid layout */
.cards-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
}
@media (max-width: 900px) {
    .cards-grid { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 600px) {
    .cards-grid { grid-template-columns: 1fr; }
}

.chips-scroll {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 16px;
}

.default-icon { font-size: 40px; color: #94a3b8; }
</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-blue-50 to-sky-100/50 border border-sky-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">
                        Infografis Edukasi <span>📊</span>
                    </h2>
                </div>
                <span class="bg-[#0099b8] text-white text-[9px] font-bold px-2.5 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">🔥 Paling Banyak Dilihat</h4>
            <ul class="space-y-2.5 text-[11px] font-semibold text-slate-600" id="sidebarPopuler"></ul>
        </div>

        <!-- ===== pojok ilmu ===== -->
          <div class="sb-card">
            <div class="sb-head">
                <span class="sb-head-icon"><i class="fa-solid fa-display text-amber-500 text-sm"></i></span>
                <span class="sb-head-label">Pojok Ilmu Terbaru</span>
                <span class="sb-badge badge-hot">Baru</span>
            </div>

            <!-- pojok ilmu -->
            <?php foreach ($pojok_terbaru as $doc) : ?>
            <a href="<?= base_url('baca_pojok/' . $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-regular fa-lightbulb text-amber-500 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>

        
           <!-- ===== BOX 4: ARTIKEL PILIHAN ===== -->
        <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>

            <!-- ARTIKEL 1: ADMINISTRASI / SEKOLAH -->
            <?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>
    const database = <?= $json_database ?? '[]'; ?>;

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

/* ------- Filter Data ------- */
    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 (Diperbaiki & Dipercantik) ------- */
    function cardHTML(d) {
        let iconContent = '';
        const urlBaca = `<?= base_url('lihat_infografis/'); ?>` + d.id;
        if (d.icon && d.icon.trim() !== '') {
            let iconUrl = d.icon;
            if (!iconUrl.startsWith('http')) {
                iconUrl = `https://lh3.googleusercontent.com/d/${iconUrl}`;
            }

            iconContent = `<img src="${iconUrl}" 
            alt="${d.judul}" 
            class="drive-icon" 
            referrerpolicy="no-referrer"
            onerror="this.onerror=null; this.outerHTML='<span class=\'default-icon\'>🖼️</span>';">`;
        } else {
            iconContent = `<span class="default-icon">🖼️</span>`;
        }

        return `
        <div class="infografis-card">
        <div class="infografis-thumb" style="background:${d.warnaBg || '#f8fafc'}">
        ${iconContent}
        <span class="badge-gratis">Gratis</span>
        </div>
        <div class="infografis-body">
        <div class="info-cat" style="color:${d.warnaKat || '#0099b8'}">${d.kategori}</div>
        <div class="info-title" title="${d.judul}">${d.judul}</div>
        <div class="info-meta-row">
        <span style="background:#f0fdf4;color:#15803d;font-size:9px;font-weight:700;padding:2px 8px;border-radius:20px">Gambar 300 DPI</span>
        </div>
        </div>
    
        <a href="${urlBaca}" class="info-btn" >
       <i class="fa-solid fa-circle-info"></i> Lihat Detail
        </a>
        </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 kategoriList = ['Semua', ...new Set(database.map(d => d.kategori))];

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

        const cards = pageData.length > 0
        ? pageData.map(cardHTML).join('')
        : `<div class="col-span-3 text-center py-12 text-slate-400 text-sm font-medium bg-white border border-dashed border-slate-200 rounded-xl">Tidak ada infografis yang ditemukan.</div>`;

        const infoText = filtered.length > 0
        ? `Menampilkan ${start + 1}–${end} dari ${filtered.length} infografis`
        : '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:30px;height:30px;border-radius:8px;border:none;cursor:pointer;font-size:11px;font-weight:700;
            background:${p === currentPage ? '#0099b8' : 'transparent'};
            color:${p === currentPage ? '#fff' : '#64748b'};
            font-family:'Inter',sans-serif;
            transition: all 0.15s ease;
            ">${p}</button>`
            ).join('');

        document.getElementById('mainContent').innerHTML = `
        <!-- HERO MINI -->
        <div class="page-hero text-white flex items-center justify-between gap-4 flex-wrap">
        <div style="flex:1;min-width:160px;">
        <div style="font-size:16px;font-weight:800;margin-bottom:4px;">Infografis Edukasi</div>
        <div style="font-size:11.5px;color:rgba(255,255,255,0.85);line-height:1.5;">
        Koleksi visual interaktif untuk belajar lebih mudah dan menyenangkan
        </div>
        </div>
        <div style="display:flex;gap:8px;flex-shrink:0;">
        <div style="background:rgba(255,255,255,0.15);backdrop-filter:blur(4px);border-radius:12px;padding:10px 16px;text-align:center;min-width:72px;">
        <div style="font-size:18px;font-weight:800;line-height:1;">${database.length}</div>
        <div style="font-size:9px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;color:rgba(255,255,255,0.8);margin-top:4px;">TOTAL</div>
        </div>
        <div style="background:rgba(255,255,255,0.15);backdrop-filter:blur(4px);border-radius:12px;padding:10px 16px;text-align:center;min-width:72px;">
        <div style="font-size:18px;font-weight:800;line-height:1;">${new Set(database.map(d=>d.kategori)).size}</div>
        <div style="font-size:9px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;color:rgba(255,255,255,0.8);margin-top:4px;">KATEGORI</div>
        </div>
        </div>
        </div>

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

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

        <!-- GRID CARDS -->
        <div class="cards-grid">${cards}</div>

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

        ${pageButtons}

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

        renderSidebar();
    }

/* ------- Render Sidebar ------- */
    function renderSidebar() {
        const parseNum = str => parseFloat(String(str).replace(/[^0-9.]/g, '')) || 0;
        const top3 = [...database].sort((a,b) => parseNum(b.dilihat) - parseNum(a.dilihat)).slice(0,3);
        
        const populerEl = document.getElementById('sidebarPopuler');
        if (populerEl) {
            populerEl.innerHTML = top3.map(d =>
                `<li class="flex items-start gap-2 hover:text-[#0099b8] cursor-pointer transition py-0.5">
                <span class="text-[#0099b8] font-bold">•</span>
                <span class="line-clamp-2">${d.judul}</span>
                </li>`
                ).join('');
        }
    }

/* ------- Event Handlers ------- */
    function setFilter(k) {
        activeFilter = k;
        currentPage = 1;
        render();
    }

    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' });
    }

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