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

<?= $this->section('css') ?>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.0/marked.min.js"></script>
<style type="text/css">
	/* ══════ PANEL ══════ */
    .panel12 { background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:24px 26px; }
    .panel12-head { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; }
    .panel12-title { font-size:14px; font-weight:700; color:#1e293b; }

	/* ══════ 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-input:focus, .form-select:focus, .form-textarea:focus {
		outline:none; border-color:#0099b8; box-shadow:0 0 0 3px rgba(0,153,184,.12);
	}

	.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; }

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

	/* ══════ JENIS KONTEN 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.tutorial { background:#e0f7fb; color:#0099b8; }
	.jenis-badge.pojok { background:#fef3e2; color:#c2760a; }

	/* ══════ EDITOR TUTORIAL (ala artifact Claude) ══════ */
	.editor-shell { border:1px solid #e2e8f0; border-radius:14px; overflow:hidden; }
	.editor-toolbar { display:flex; align-items:center; justify-content:space-between; background:#f8fafc; border-bottom:1px solid #e2e8f0; padding:8px 12px; }
	.editor-tabs { display:flex; gap:4px; background:#e2e8f0; padding:3px; border-radius:9px; }
	.editor-tab { font-size:11.5px; font-weight:700; color:#64748b; padding:6px 14px; border-radius:7px; cursor:pointer; display:flex; align-items:center; gap:6px; transition:all .12s; }
	.editor-tab.active { background:#fff; color:#0099b8; box-shadow:0 1px 3px rgba(0,0,0,.08); }
	.editor-tools { display:flex; align-items:center; gap:4px; }
	.editor-tool-btn { width:30px; height:30px; border-radius:7px; display:flex; align-items:center; justify-content:center; color:#64748b; font-size:11.5px; cursor:pointer; transition:all .12s; border:1px solid transparent; }
	.editor-tool-btn:hover { background:#fff; border-color:#e2e8f0; color:#0099b8; }
	.editor-divider { width:1px; height:18px; background:#e2e8f0; margin:0 4px; }

	.editor-body { display:grid; grid-template-columns:1fr; min-height:420px; }
	.editor-body.split { grid-template-columns:1fr 1fr; }

	.editor-pane { position:relative; background:#0f172a; }
	.editor-pane textarea {
		width:100%; height:420px; resize:vertical; background:#0f172a; color:#e2e8f0;
		font-family:'JetBrains Mono',monospace; font-size:12.5px; line-height:1.7;
		padding:16px 18px; border:none; outline:none;
	}
	.editor-pane textarea::placeholder { color:#475569; }

	.preview-pane { background:#fff; border-left:1px solid #e2e8f0; height:420px; overflow-y:auto; padding:18px 22px; }
	.preview-pane.full { border-left:none; }

	/* hasil render markdown */
	.rendered-content h1 { font-size:19px; font-weight:800; color:#1e293b; margin:0 0 12px; }
	.rendered-content h2 { font-size:16px; font-weight:700; color:#1e293b; margin:20px 0 10px; }
	.rendered-content h3 { font-size:14px; font-weight:700; color:#1e293b; margin:16px 0 8px; }
	.rendered-content p { font-size:13px; color:#334155; line-height:1.75; margin:0 0 12px; }
	.rendered-content ul, .rendered-content ol { margin:0 0 12px 20px; font-size:13px; color:#334155; line-height:1.75; }
	.rendered-content li { margin-bottom:4px; }
	.rendered-content strong { color:#1e293b; font-weight:700; }
	.rendered-content code:not(pre code) { background:#f1f5f9; color:#0099b8; padding:2px 6px; border-radius:5px; font-family:'JetBrains Mono',monospace; font-size:12px; }
	.rendered-content a { color:#0099b8; font-weight:600; text-decoration:underline; }
	.rendered-content blockquote { border-left:3px solid #0099b8; background:#f0fbfd; padding:10px 16px; border-radius:0 8px 8px 0; font-size:12.5px; color:#475569; margin:0 0 12px; }
	.rendered-content img { max-width:100%; border-radius:10px; margin:10px 0; }

	/* code block ala chat interface */
	.code-block-wrap { border-radius:12px; overflow:hidden; margin:0 0 16px; border:1px solid #1e293b; }
	.code-block-head { background:#1e293b; color:#94a3b8; font-size:11px; font-weight:700; padding:9px 14px; display:flex; align-items:center; justify-content:space-between; font-family:'JetBrains Mono',monospace; }
	.code-block-head .copy-btn { font-size:10.5px; color:#94a3b8; display:flex; align-items:center; gap:5px; cursor:pointer; padding:3px 8px; border-radius:6px; transition:all .12s; }
	.code-block-head .copy-btn:hover { background:rgba(255,255,255,.08); color:#fff; }
	.rendered-content pre { margin:0 !important; border-radius:0 !important; font-size:12px !important; }
	.rendered-content pre code.hljs { padding:16px 18px !important; }

	.empty-preview { display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%; color:#94a3b8; gap:10px; text-align:center; }
	.empty-preview i { font-size:26px; color:#cbd5e1; }
	.empty-preview span { font-size:12px; font-weight:600; }

	.snippet-bar { display:flex; flex-wrap:wrap; gap:6px; padding:10px 12px; background:#f8fafc; border-top:1px solid #e2e8f0; }
	.snippet-chip { font-size:10.5px; font-weight:700; color:#475569; background:#fff; border:1px solid #e2e8f0; padding:5px 11px; border-radius:7px; cursor:pointer; display:flex; align-items:center; gap:5px; transition:all .12s; }
	.snippet-chip:hover { border-color:#0099b8; color:#0099b8; }

	.lang-select { font-size:11px; font-weight:700; color:#64748b; background:#fff; border:1px solid #e2e8f0; border-radius:7px; padding:5px 8px; outline:none; }
</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">Konten</a> <i class="fa-solid fa-chevron-right" style="font-size:8px;"></i> <span class="text-slate-600">Tambah Konten</span>
				</div>
				<h1 class="text-lg font-bold text-slate-800">Input Konten Baru <span class="jenis-badge tutorial" id="topBadge"><i class="fa-solid fa-graduation-cap"></i> Tutorial</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 action="<?= base_url('admin/simtutor') ?>" method="post">

			<!-- JENIS KONTEN -->
			<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 Konten</div>
				</div>
				<div class="form-group mb-0">
					<div class="jenis-toggle">
						<label class="jenis-option">
							<input type="radio" name="jenis" value="tutorial" checked onchange="onJenisChange()">
							<div class="jenis-card">
								<div class="jenis-icon"><i class="fa-solid fa-graduation-cap"></i></div>
								<div>
									<div class="jenis-name">Tutorial</div>
									<div class="jenis-desc">Langkah demi langkah, biasanya berisi kode</div>
								</div>
							</div>
						</label>
						<label class="jenis-option">
							<input type="radio" name="jenis" value="pojok_ilmu" onchange="onJenisChange()">
							<div class="jenis-card">
								<div class="jenis-icon"><i class="fa-solid fa-lightbulb"></i></div>
								<div>
									<div class="jenis-name">Pojok Ilmu</div>
									<div class="jenis-desc">Artikel/wawasan singkat, tanpa langkah teknis</div>
								</div>
							</div>
						</label>
					</div>
					<div class="form-hint">Pilih jenis konten untuk menentukan halaman tampilan. Konten "Tutorial" akan muncul di halaman Tutorial, sedangkan "Pojok Ilmu" akan muncul di halaman Pojok Ilmu.</div>
				</div>
			</div>

			<!-- INFORMASI TUTORIAL -->
			<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 Konten</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-graduation-cap left-icon" id="titleIcon"></i>
						<input type="text" name="judul" class="form-input" placeholder="Contoh: Cara Membuat Looping For di JavaScript" id="tutTitle">
					</div>
				</div>

				
					<div class="form-group mb-0">
						<label class="form-label">Kategori <span class="req">*</span></label>
						<select class="form-select" id="tutCategory" name="kategori">
							<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>

			<!-- ISI KONTEN -->
			<div class="panel2 mb-5">
				<div class="panel2-head">
					<div class="panel2-title"><i class="fa-solid fa-code text-[#0099b8] mr-1.5"></i> Isi Konten</div>
					<span class="form-hint" style="margin:0;">Tulis pakai Markdown. Bungkus kode dengan <span class="mono" style="background:#f1f5f9;padding:1px 5px;border-radius:5px;">```bahasa</span> agar tampil dengan syntax highlight di preview.</span>
				</div>

				<div class="form-group mb-0">
					<div class="editor-shell">
						<!-- toolbar -->
						<div class="editor-toolbar">
							<div class="editor-tabs">
								<div class="editor-tab active" data-mode="split" onclick="setMode('split')"><i class="fa-solid fa-table-columns"></i> Split</div>
								<div class="editor-tab" data-mode="write" onclick="setMode('write')"><i class="fa-solid fa-pen"></i> Tulis</div>
								<div class="editor-tab" data-mode="preview" onclick="setMode('preview')"><i class="fa-solid fa-eye"></i> Preview</div>
							</div>
							<div class="editor-tools">
								<select class="lang-select" id="snippetLang">
									<option value="javascript">JavaScript</option>
									<option value="python">Python</option>
									<option value="php">PHP</option>
									<option value="html">HTML</option>
									<option value="css">CSS</option>
									<option value="sql">SQL</option>
									<option value="bash">Bash</option>
									<option value="java">Java</option>
								</select>
								<div class="editor-tool-btn" title="Sisipkan blok kode" onclick="insertCodeBlock()"><i class="fa-solid fa-code"></i></div>
								<div class="editor-divider"></div>
								<div class="editor-tool-btn" title="Bold" onclick="wrapSelection('**','**')"><i class="fa-solid fa-bold"></i></div>
								<div class="editor-tool-btn" title="Italic" onclick="wrapSelection('_','_')"><i class="fa-solid fa-italic"></i></div>
								<div class="editor-tool-btn" title="Heading" onclick="insertAtLineStart('## ')"><i class="fa-solid fa-heading"></i></div>
								<div class="editor-tool-btn" title="List" onclick="insertAtLineStart('- ')"><i class="fa-solid fa-list-ul"></i></div>
								<div class="editor-tool-btn" title="Link" onclick="wrapSelection('[','](https://)')"><i class="fa-solid fa-link"></i></div>
							</div>
						</div>

						<!-- body: editor + preview -->
						<div class="editor-body split" id="editorBody">
							<div class="editor-pane" id="paneWrite">
								<textarea id="tutContent" name="isi" placeholder="Tulis isi konten di sini menggunakan Markdown...

								Contoh blok kode:
								```javascript
								function sapa(nama) {
									console.log('Halo, ' + nama + '!');
								}
								sapa('Pena Ilmu');
								```"></textarea>
							</div>
							<div class="preview-pane" id="panePreview">
								<div class="rendered-content" id="renderedOutput"></div>
							</div>
						</div>

						<!-- snippet shortcuts -->
						<div class="snippet-bar">
							<span class="snippet-chip" onclick="insertAtLineStart('### ')"><i class="fa-solid fa-heading fa-xs"></i> Sub Judul</span>
							<span class="snippet-chip" onclick="insertAtCursor('\n> Catatan: ')"><i class="fa-solid fa-quote-left fa-xs"></i> Catatan</span>
							<span class="snippet-chip" onclick="insertAtLineStart('1. ')"><i class="fa-solid fa-list-ol fa-xs"></i> List Bernomor</span>
							<span class="snippet-chip" onclick="insertCodeBlock()"><i class="fa-solid fa-terminal fa-xs"></i> Blok Kode</span>
							<span class="snippet-chip" onclick="insertAtCursor('\n![alt teks](https://)\n')"><i class="fa-solid fa-image fa-xs"></i> Gambar</span>
						</div>
					</div>
					<div class="form-hint">Panel kanan menampilkan hasil konten secara langsung, persis seperti yang akan dilihat pengguna — termasuk tampilan kode dengan syntax highlight.</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="button" class="btn-secondary" onclick="setMode('preview')"><i class="fa-solid fa-eye"></i> Lihat Preview Penuh</button>
				<button type="submit" class="btn-primary" onclick="simpanKonten()"><i class="fa-solid fa-circle-check"></i> Simpan Konten</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 textarea = document.getElementById('tutContent');
        const renderedOutput = document.getElementById('renderedOutput');
        const editorBody = document.getElementById('editorBody');
        const paneWrite = document.getElementById('paneWrite');
        const panePreview = document.getElementById('panePreview');
        const topBadge = document.getElementById('topBadge');
        const titleIcon = document.getElementById('titleIcon');

        marked.setOptions({ breaks: true, gfm: true });

        function escapeHtml(str){
            return str.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
        }

        // ══════ JENIS KONTEN: mengatur tampilan & label sesuai pilihan ══════
       

        // ══════ Kumpulkan payload untuk dikirim ke backend ══════
        function simpanKonten() {
            const payload = {
                jenis: document.querySelector('input[name="jenis"]:checked').value, // "tutorial" atau "pojok_ilmu"
                judul: document.getElementById('tutTitle').value,
                kategori: document.getElementById('tutCategory').value,
                isi: textarea.value
            };
            console.log('Payload yang akan dikirim ke server:', payload);
            // TODO: kirim payload ini ke endpoint backend (mis. fetch('/api/konten', { method:'POST', body: JSON.stringify(payload) }))
            // Backend lalu menyimpan kolom "jenis" di database, dan halaman Tutorial / Pojok Ilmu
            // tinggal query berdasarkan kolom tersebut (WHERE jenis = 'tutorial' / WHERE jenis = 'pojok_ilmu').
        }

        function renderMarkdown() {
            const raw = textarea.value.trim();
            if (!raw) {
                renderedOutput.innerHTML = `<div class="empty-preview">
                    <i class="fa-solid fa-eye-slash"></i>
                    <span>Belum ada isi konten.<br>Mulai menulis di panel kiri untuk melihat preview.</span>
                </div>`;
                return;
            }

            let html = marked.parse(raw);
            renderedOutput.innerHTML = html;

            // bungkus tiap <pre><code> menjadi code-block ala chat interface + highlight
            renderedOutput.querySelectorAll('pre code').forEach((block, i) => {
                hljs.highlightElement(block);
                const lang = (block.className.match(/language-(\w+)/) || [,'plain'])[1];
                const pre = block.parentElement;
                const wrap = document.createElement('div');
                wrap.className = 'code-block-wrap';
                const head = document.createElement('div');
                head.className = 'code-block-head';
                head.innerHTML = `<span class="mono">${escapeHtml(lang)}</span>
                    <span class="copy-btn" onclick="copyCode(this)"><i class="fa-regular fa-copy"></i> Salin</span>`;
                pre.parentNode.insertBefore(wrap, pre);
                wrap.appendChild(head);
                wrap.appendChild(pre);
            });
        }

        function copyCode(el) {
            const code = el.closest('.code-block-wrap').querySelector('code').innerText;
            navigator.clipboard.writeText(code).then(() => {
                const original = el.innerHTML;
                el.innerHTML = '<i class="fa-solid fa-check"></i> Tersalin';
                setTimeout(() => el.innerHTML = original, 1500);
            });
        }

        function setMode(mode) {
            document.querySelectorAll('.editor-tab').forEach(t => t.classList.toggle('active', t.dataset.mode === mode));
            if (mode === 'split') {
                editorBody.classList.add('split');
                paneWrite.style.display = 'block';
                panePreview.style.display = 'block';
                panePreview.classList.remove('full');
            } else if (mode === 'write') {
                editorBody.classList.remove('split');
                paneWrite.style.display = 'block';
                panePreview.style.display = 'none';
            } else {
                editorBody.classList.remove('split');
                paneWrite.style.display = 'none';
                panePreview.style.display = 'block';
                panePreview.classList.add('full');
            }
        }

        function insertAtCursor(text) {
            const start = textarea.selectionStart, end = textarea.selectionEnd;
            textarea.value = textarea.value.substring(0, start) + text + textarea.value.substring(end);
            textarea.focus();
            textarea.selectionStart = textarea.selectionEnd = start + text.length;
            renderMarkdown();
        }

        function wrapSelection(before, after) {
            const start = textarea.selectionStart, end = textarea.selectionEnd;
            const selected = textarea.value.substring(start, end) || 'teks';
            const newText = before + selected + after;
            textarea.value = textarea.value.substring(0, start) + newText + textarea.value.substring(end);
            textarea.focus();
            textarea.selectionStart = start + before.length;
            textarea.selectionEnd = start + before.length + selected.length;
            renderMarkdown();
        }

        function insertAtLineStart(prefix) {
            const start = textarea.selectionStart;
            const value = textarea.value;
            const lineStart = value.lastIndexOf('\n', start - 1) + 1;
            textarea.value = value.substring(0, lineStart) + prefix + value.substring(lineStart);
            textarea.focus();
            textarea.selectionStart = textarea.selectionEnd = start + prefix.length;
            renderMarkdown();
        }

        function insertCodeBlock() {
            const lang = document.getElementById('snippetLang').value;
            const start = textarea.selectionStart, end = textarea.selectionEnd;
            const selected = textarea.value.substring(start, end);
            const snippet = '\n```' + lang + '\n' + (selected || '// tulis kode di sini') + '\n```\n';
            textarea.value = textarea.value.substring(0, start) + snippet + textarea.value.substring(end);
            textarea.focus();
            const cursorPos = start + snippet.indexOf((selected || '// tulis kode di sini')) ;
            textarea.selectionStart = cursorPos;
            textarea.selectionEnd = cursorPos + (selected || '// tulis kode di sini').length;
            renderMarkdown();
        }

        textarea.addEventListener('input', renderMarkdown);
        renderMarkdown();
    </script>
<?= $this->endSection(); ?>