<?= $this->extend('App\Modules\Admin\Views\_admin_layout') ?>

<?= $this->section('styles') ?>
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">
<style>
    .blog-admin-container { max-width: 1100px; margin: 20px auto; color: #1f2937; }
    .form-card { background: #fff; border: 1px solid #d6d3cc; border-radius: 12px; padding: 20px; margin-bottom: 20px; }
    .label-mini {
        display: block;
        font-size: 11px;
        font-weight: 800;
        text-transform: uppercase;
        color: #6b7280;
        margin-bottom: 6px;
        letter-spacing: 0.5px;
    }

    .std-input {
        width: 100%;
        padding: 10px 12px;
        font-size: 14px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        box-sizing: border-box;
    }
    .title-input {
        font-size: 18px;
        font-weight: 700;
        border: 2px solid #d1d5db;
    }

    .editor-wrapper {
        border: 1px solid #d1d5db;
        border-radius: 6px;
        background: white;
        position: relative;
    }

    #editor-container {
        height: 400px;
        font-size: 16px;
    }

    .ql-container.ql-snow {
        border: none !important;
        height: 100% !important;
        min-height: 358px;
    }

    .ql-toolbar.ql-snow {
        background: #f9fafb;
        border: none !important;
        border-bottom: 1px solid #d1d5db !important;
        border-radius: 6px 6px 0 0;
    }

    .google-preview {
        background: #fff;
        border: 1px solid #dfe1e5;
        border-radius: 8px;
        padding: 15px;
        margin-top: 10px;
        font-family: arial, sans-serif;
    }
    .prev-t { color: #1a0dab; font-size: 18px; line-height: 1.2; margin-bottom: 2px; }
    .prev-u { color: #006621; font-size: 13px; line-height: 1.5; margin-bottom: 3px; }
    .prev-d {
        color: #4d5156;
        font-size: 13px;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .admin-grid {
        display: grid;
        grid-template-columns: 1fr 320px;
        gap: 24px;
    }
    @media (max-width: 1024px) {
        .admin-grid { grid-template-columns: 1fr; }
    }

    .btn-save {
        width: 100%;
        padding: 14px;
        background: #d4a373;
        color: #18181b;
        border: none;
        border-radius: 8px;
        font-weight: 800;
        text-transform: uppercase;
        cursor: pointer;
    }

    .tags-input {
        padding: 8px 10px;
        font-size: 14px;
    }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="blog-admin-container">
    <form action="<?= $post ? url_to('admin.blog.update', $post['id']) : url_to('admin.blog.store') ?>" method="post" id="blog-form">
        <?= csrf_field() ?>

        <div class="admin-grid">
            <div class="content-area">
                <div class="form-card">
                    <div style="margin-bottom: 15px;">
                        <label class="label-mini">Article Title</label>
                        <input type="text" name="title" id="blog-title" value="<?= esc($post['title'] ?? '') ?>" class="std-input title-input" required placeholder="Main Story Headline">
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label class="label-mini">Permalink Slug</label>
                        <input type="text" name="slug" id="blog-slug" value="<?= esc($post['slug'] ?? '') ?>" class="std-input" style="background:#f9fafb; font-family:monospace; color:#d4a373;" readonly>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label class="label-mini">Category</label>
                        <select name="category" class="std-input">
                            <option value="">— Select Category —</option>
                            <?php
                            $categories = ['Mount Kenya Treks', 'Wildlife Safaris', 'Travel Tips', 'Local Culture'];
                            foreach ($categories as $cat): ?>
                                <option value="<?= esc($cat) ?>" <?= (isset($post) && $post['category'] === $cat) ? 'selected' : '' ?>>
                                    <?= esc($cat) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label class="label-mini">Tags (comma-separated)</label>
                        <input type="text" name="tags" id="blog-tags" value="<?= esc($post['tags'] ?? '') ?>" class="std-input tags-input" placeholder="e.g. hiking, kenya, mountain">
                    </div>

                    <div>
                        <label class="label-mini">Article Body</label>
                        <div class="editor-wrapper">
                            <div id="editor-container" tabindex="0"></div>
                        </div>
                        <!-- FIX: do NOT escape HTML meant for Quill -->
                        <input type="hidden" name="content" id="content-storage" value="<?= $post['content'] ?? '' ?>">
                    </div>
                </div>
            </div>

            <div class="meta-area">
                <div class="form-card" style="background: #111827; color: white; border: none;">
                    <label class="label-mini" style="color: #9ca3af;">Visibility Status</label>
                    <select name="status" class="std-input" style="margin-bottom: 20px; background: #374151; color: white; border-color: #4b5563;">
                        <option value="draft" <?= (!isset($post) || $post['status'] === 'draft') ? 'selected' : '' ?>>Draft</option>
                        <option value="published" <?= (isset($post) && $post['status'] === 'published') ? 'selected' : '' ?>>Published</option>
                    </select>
                    <button type="submit" class="btn-save">Update Chronicle</button>
                </div>

                <div class="form-card">
                    <label class="label-mini">Search Engine Preview</label>
                    <div class="google-preview">
                        <div class="prev-t" id="prev-title">Article Title Example</div>
                        <div class="prev-u"><?= base_url('blog/') ?><span id="prev-slug">slug-here</span></div>
                        <div class="prev-d" id="prev-desc">Meta description will appear here as a snippet...</div>
                    </div>

                    <div style="margin-top: 20px;">
                        <label class="label-mini">SEO Meta Title</label>
                        <input type="text" name="meta_title" id="meta-title" value="<?= esc($post['meta_title'] ?? '') ?>" class="std-input" maxlength="60">
                    </div>

                    <div style="margin-top: 15px;">
                        <label class="label-mini">SEO Meta Description</label>
                        <textarea name="meta_description" id="meta-desc" rows="3" class="std-input" maxlength="160"><?= esc($post['meta_description'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const quill = new Quill('#editor-container', {
        theme: 'snow',
        placeholder: 'Begin your journey...',
        modules: {
            toolbar: [
                [{ 'header': [2, 3, false] }],
                ['bold', 'italic', 'underline'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                ['link', 'image'],
                ['clean']
            ]
        }
    });

    const storage = document.getElementById('content-storage');
    const titleIn = document.getElementById('blog-title');
    const slugIn = document.getElementById('blog-slug');
    const metaTitleIn = document.getElementById('meta-title');
    const metaDescIn = document.getElementById('meta-desc');

    const pTitle = document.getElementById('prev-title');
    const pSlug = document.getElementById('prev-slug');
    const pDesc = document.getElementById('prev-desc');

    // FIX: load HTML correctly into Quill
    if (storage.value) {
        quill.clipboard.dangerouslyPasteHTML(storage.value);
    }

    function stripHtml(html, maxLength = 155) {
        const tmp = document.createElement('div');
        tmp.innerHTML = html;
        let text = tmp.textContent || tmp.innerText || '';
        text = text.replace(/\s+/g, ' ').trim();
        return text.length > maxLength ? text.substring(0, maxLength - 3) + '...' : text;
    }

    function updateAutomation() {
        let slug = titleIn.value
            .toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')
            .trim()
            .replace(/\s+/g, '-');
        slugIn.value = slug;
        pSlug.textContent = slug || 'slug-here';

        if (!metaTitleIn.dataset.edited) {
            metaTitleIn.value = titleIn.value || '';
        }

        if (!metaDescIn.dataset.edited) {
            metaDescIn.value = stripHtml(quill.root.innerHTML, 155);
        }

        pTitle.textContent = metaTitleIn.value || titleIn.value || 'Article Title Example';
        pDesc.textContent = metaDescIn.value || stripHtml(quill.root.innerHTML, 155) || 'Meta description will appear here as a snippet...';
    }

    titleIn.addEventListener('input', updateAutomation);
    quill.on('text-change', updateAutomation);

    metaTitleIn.addEventListener('input', e => {
        e.target.dataset.edited = 'true';
        updateAutomation();
    });

    metaDescIn.addEventListener('input', e => {
        e.target.dataset.edited = 'true';
        updateAutomation();
    });

    document.getElementById('blog-form').addEventListener('submit', function() {
        storage.value = quill.root.innerHTML;
    });

    updateAutomation();
});
</script>
<?= $this->endSection() ?>
