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

<?= $this->section('css') ?>
<style type="text/css">
	/* ===== POJOK ILMU ===== */
	.pojok-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; overflow: hidden; display: flex; transition: box-shadow 0.15s, border-color 0.15s; }
	.pojok-card:hover { box-shadow: 0 4px 16px rgba(192,92,26,0.10); border-color: #0099b8; }
	.pojok-thumb { width: 88px; min-width: 88px; display: flex; align-items: center; justify-content: center; font-size: 30px; flex-shrink: 0; }
	.pojok-body { padding: 12px 14px; flex: 1; }
	.pojok-tag { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #c05c1a; margin-bottom: 3px; }
	.pojok-title { font-size: 13px; font-weight: 700; color: #1e293b; line-height: 1.4; margin-bottom: 4px; }
	.pojok-desc { font-size: 11px; color: #64748b; line-height: 1.5; margin-bottom: 8px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
	.pojok-meta { font-size: 10px; color: #94a3b8; display: flex; gap: 12px; align-items: center; }


</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-blue-to-r from-orange-50 to-blue-100/50 border border-blue-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">
						Pojok Ilmu <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">🔥 Paling Banyak Dibaca</h4>
				<ul class="space-y-2.5 text-[11px] font-semibold text-slate-600" id="sidebarPopuler"></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>
	const database = <?= $json_database ?? '[]'; ?>;

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

	function getFiltered() {
		return database.filter(d => {
			const matchTipe   = activeFilter === 'Semua' || d.tipe === activeFilter;
			const matchSearch = !searchQuery ||
			d.judul.toLowerCase().includes(searchQuery.toLowerCase()) ||
			d.desc.toLowerCase().includes(searchQuery.toLowerCase());
			return matchTipe && matchSearch;
		});
	}

	function cardHTML(d) {
		const tagsHTML = d.tags.map(t => t ? `<span class="tut-tag">${t}</span>` : '').join('');

    // Arahkan link ke route/url halaman baca bawaan CodeIgniter 4 menggunakan ID dokumen
		const urlBaca = `<?= base_url('baca_pojok/'); ?>` + d.id;

		return `
		<div class="tut-card">
		<div class="tut-cover" style="background:${d.warnaCover}">
		<span style="font-size:24px">${d.icon}</span>
		</div>
		<div style="flex:1;min-width:0">
		<div class="tut-type">${d.tipe}</div>
		<div class="tut-title">${d.judul}</div>
		<div class="tut-meta">${d.meta}</div>
		<div class="tut-tags">${tagsHTML}</div>
		<!-- Tombol dialihkan untuk membuka halaman baca penuh -->
		<a href="${urlBaca}" class="tut-link" style="display:inline-block; margin-top:8px; text-decoration:none; color:#0099b8; font-weight:600;">
		<i class="fa-solid fa-book-open fa-xs"></i> Baca tutorial
		</a>
		</div>
		</div>
		`;
	}

	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 bidangList = ['Semua', ...new Set(database.map(d => d.tipe))];

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

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

		const avgMenit = Math.round(database.reduce((a,d) => a + d.menit, 0) / database.length);

		const infoText   = filtered.length > 0 ? `Menampilkan ${start + 1}–${end} dari ${filtered.length} artikel` : '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;">
		<div style="flex:1;min-width:160px;">
		<div style="font-size:15px;font-weight:700;margin-bottom:4px;">Pojok Ilmu</div>
		<div style="font-size:11.5px;color:rgba(255,255,255,0.78);line-height:1.5;">
		Kenali ilmu baru lewat artikel ringan yang mudah dipahami semua kalangan
		</div>
		</div>
		<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;">TOTAL ARTIKEL</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.tipe)).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;">BIDANG ILMU</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:#fdba74;">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 topik atau bidang ilmu..." value="${searchQuery}" oninput="onSearch(this.value)">
		<button class="search-btn-blue"><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:#0099b8;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();
	}

	function renderSidebar() {
		

		const top3 = [...database].sort((a,b) => parseInt(b.lihat) - parseInt(a.lihat)).slice(0,3);
		document.getElementById('sidebarPopuler').innerHTML = top3.map(d =>
			`<li class="flex items-start gap-1.5 hover:text-[#c05c1a] cursor-pointer transition"><span class="text-slate-300">•</span><span>${d.judul}</span></li>`
			).join('');
	}

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

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