<?php ob_start();
$isEdit   = !empty($post);
$action   = $isEdit
    ? '/admin/blog/update/' . (int) $post['id']
    : '/admin/blog/store';

// Build comma-separated tag string for the input field
$tagsString = '';
if (!empty($postTags)) {
    $tagsString = implode(', ', array_column($postTags, 'name'));
}
?>
<link rel="stylesheet" href="/admin/assets/editor/jodit.min.css">

<div class="content-header">
    <h2><?= $isEdit ? __('admin.blog.edit') : __('admin.blog.create') ?></h2>
    <div style="display:flex;gap:0.5rem;align-items:center;">
        <?php if ($isEdit): ?>
        <a href="/admin/preview/blog/<?= (int) $post['id'] ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.common.preview') ?></a>
        <?php endif; ?>
        <?php if ($isEdit && ($post['status'] ?? '') === 'published' && !empty($post['slug'])): ?>
        <a href="/blog/<?= e($post['slug']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.blog.view_post') ?></a>
        <?php endif; ?>
        <a href="/admin/blog" class="btn btn-secondary"><?= __('admin.blog.back') ?></a>
    </div>
</div>

<form method="POST" action="<?= $action ?>" enctype="multipart/form-data" class="admin-form" id="blogForm">
    <?= $csrf->field() ?>

    <div class="form-grid">

        <!-- Main column -->
        <div class="form-main">

            <div class="form-group">
                <label for="title"><?= __('admin.blog.post_title') ?> <span class="required">*</span></label>
                <input type="text" id="title" name="title"
                       value="<?= e($post['title'] ?? '') ?>"
                       required
                       placeholder="<?= __('admin.blog.post_title_placeholder') ?>">
            </div>

            <div class="form-group">
                <label for="slug"><?= __('admin.common.slug') ?></label>
                <div class="slug-preview-wrap">
                    <span class="slug-prefix"><?= __('admin.blog.slug_prefix') ?></span>
                    <input type="text" id="slug" name="slug"
                           value="<?= e($post['slug'] ?? '') ?>"
                           placeholder="<?= __('admin.blog.slug_placeholder') ?>">
                </div>
                <small class="form-hint"><?= __('admin.blog.slug_help') ?></small>
            </div>

            <div class="form-group">
                <label for="excerpt"><?= __('admin.blog.excerpt') ?></label>
                <textarea id="excerpt" name="excerpt" rows="3"
                          placeholder="<?= __('admin.blog.excerpt_placeholder') ?>"><?= e($post['excerpt'] ?? '') ?></textarea>
                <small class="form-hint"><?= __('admin.blog.excerpt_help') ?></small>
            </div>

            <div class="form-group">
                <label for="content"><?= __('admin.blog.content') ?></label>
                <textarea id="content" name="content" rows="18"
                          placeholder="<?= __('admin.blog.content_placeholder') ?>"><?= e($post['content'] ?? '') ?></textarea>
                <div class="editor-footer-row">
                    <small class="form-hint editor-hint"><?= __('admin.blog.content_help') ?></small>
                    <button type="button" class="btn btn-secondary btn-sm media-picker-btn" id="mediaPickerBtn" data-media-picker data-editor-target="content"><?= __('admin.blog.insert_from_library') ?></button>
                </div>
            </div>

        </div><!-- /form-main -->

        <!-- Sidebar -->
        <div class="form-sidebar">

            <!-- Publishing -->
            <div class="form-card">
                <h4><?= __('admin.blog.publishing') ?></h4>

                <div class="form-group">
                    <label for="status"><?= __('admin.common.status') ?></label>
                    <select id="status" name="status">
                        <option value="draft"     <?= ($post['status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>><?= __('admin.common.draft') ?></option>
                        <option value="published" <?= ($post['status'] ?? '')      === 'published' ? 'selected' : '' ?>><?= __('admin.common.published') ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="category_id"><?= __('admin.blog.category') ?></label>
                    <select id="category_id" name="category_id">
                        <option value=""><?= __('admin.blog.no_category') ?></option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= (int) $cat['id'] ?>"
                                <?= (int) ($post['category_id'] ?? 0) === (int) $cat['id'] ? 'selected' : '' ?>>
                            <?= e($cat['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="form-hint">
                        <a href="/admin/blog/categories" target="_blank"><?= __('admin.blog.manage_categories') ?></a>
                    </small>
                </div>

                <div class="form-group">
                    <label for="tags"><?= __('admin.blog.tags') ?></label>
                    <input type="text" id="tags" name="tags"
                           value="<?= e($tagsString) ?>"
                           placeholder="<?= __('admin.blog.tags_placeholder') ?>">
                    <small class="form-hint">
                        <?= __('admin.blog.tags_help') ?>
                        <a href="/admin/blog/tags" target="_blank"><?= __('admin.blog.manage_tags') ?></a>
                    </small>
                </div>

                <button type="submit" class="btn btn-primary btn-full" style="margin-top:0.25rem;">
                    <?= $isEdit ? __('admin.blog.update_post') : __('admin.blog.create_post') ?>
                </button>
            </div>

            <!-- Featured Image -->
            <div class="form-card">
                <h4><?= __('admin.blog.featured_image') ?></h4>

                <!-- Preview (DB image or library-picked image) -->
                <div id="featuredImgPreview" style="margin-bottom:0.75rem;<?= empty($post['featured_image']) ? 'display:none;' : '' ?>">
                    <img id="featuredImgPreviewImg"
                         src="<?= !empty($post['featured_image']) ? e(thumb_url($post['featured_image'])) : '' ?>"
                         alt="<?= __('admin.blog.featured_image_preview') ?>"
                         style="max-width:100%;border-radius:4px;">
                </div>

                <?php if ($isEdit && !empty($post['featured_image'])): ?>
                <!-- Remove checkbox for persisted DB image -->
                <div id="removeImageRow" style="margin-bottom:0.5rem;">
                    <label class="checkbox-label" style="font-size:0.85rem;color:#c0392b;">
                        <input type="checkbox" name="remove_image" value="1" id="removeImage"
                               onchange="onRemoveImageChange(this.checked)">
                        <?= __('admin.blog.remove_image') ?>
                    </label>
                </div>
                <?php endif; ?>

                <!-- Hidden field: carries relative path of library-selected image -->
                <input type="hidden" id="featured_image_path" name="featured_image_path" value="">

                <!-- Library picker button row -->
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:0.6rem;">
                    <button type="button" class="btn btn-secondary btn-sm" id="blogPickerBtn">
                        📷 <?= empty($post['featured_image']) ? __('admin.blog.select_from_library') : __('admin.blog.change_image') ?>
                    </button>
                    <button type="button" class="btn btn-sm" id="blogPickerClearBtn"
                            style="color:#c0392b;display:none;">
                        <?= __('admin.blog.clear_selection') ?>
                    </button>
                </div>

                <!-- Direct upload divider -->
                <div style="border-top:1px solid #e9ecef;padding-top:0.6rem;margin-bottom:0.4rem;">
                    <small style="display:block;color:#888;margin-bottom:0.4rem;"><?= __('admin.blog.upload_new') ?></small>
                    <input type="file" id="featured_image" name="featured_image"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                </div>

                <small class="form-hint"><?= __('admin.blog.upload_hint') ?></small>
            </div>

            <!-- SEO -->
            <div class="form-card">
                <h4><?= __('admin.blog.seo') ?></h4>

                <div class="form-group">
                    <label for="seo_title"><?= __('admin.blog.seo_title') ?></label>
                    <input type="text" id="seo_title" name="seo_title"
                           value="<?= e($post['seo_title'] ?? '') ?>"
                           placeholder="<?= __('admin.blog.seo_title_default') ?>"
                           maxlength="120">
                    <div class="seo-counter">
                        <span id="seo_title_len">0</span>/60 <?= __('admin.common.search') ?>
                    </div>
                </div>

                <div class="form-group">
                    <label for="seo_description"><?= __('admin.blog.seo_description') ?></label>
                    <textarea id="seo_description" name="seo_description" rows="3"
                              placeholder="<?= __('admin.blog.seo_description_default') ?>"
                              maxlength="320"><?= e($post['seo_description'] ?? '') ?></textarea>
                    <div class="seo-counter">
                        <span id="seo_desc_len">0</span>/160 <?= __('admin.common.search') ?>
                    </div>
                </div>
            </div>

        </div><!-- /form-sidebar -->

    </div><!-- /form-grid -->
</form>

<!-- ── Featured Image Picker Modal ────────────────────────────────────── -->
<div id="blogFeaturedPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="Select Featured Image">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.blog.select_featured_title') ?></h3>
            <button type="button" class="media-picker-close" id="blogFeaturedPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="blogFeaturedPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.blog.select_featured_help') ?></small>
        </div>
    </div>
</div>

<!-- ── Media Picker Modal (for content editor) ────────────────────────── -->
<div id="mediaPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="Image Library">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.blog.insert_from_library') ?></h3>
            <button type="button" class="media-picker-close" id="mediaPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="mediaPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.pages.insert_image_help') ?></small>
        </div>
    </div>
</div>

<script src="/admin/assets/editor/jodit.min.js"></script>
<script>
(function () {
    // ── Jodit WYSIWYG Editor ──────────────────────────────────────────────
    var contentTextarea = document.getElementById('content');
    var joditEditor     = null;
    if (contentTextarea && typeof Jodit !== 'undefined') {
        joditEditor = Jodit.make(contentTextarea, {
            height: 480,
            language: 'en',
            toolbarSticky: true,
            toolbarStickyOffset: 56,
            buttons: [
                'bold', 'italic', 'underline', 'strikethrough', 'eraser',
                '|',
                'paragraph', 'fontsize',
                '|',
                'ul', 'ol', 'indent', 'outdent',
                '|',
                'superscript', 'subscript',
                '|',
                'link', 'image',
                '|',
                'table', 'hr',
                '|',
                'align',
                '|',
                'undo', 'redo',
                '\n',
                'find',
                '|',
                'source',
                '|',
                'fullsize'
            ],
            // HTML Preservation – do not strip or modify existing HTML
            cleanHTML: {
                fillEmptyParagraph: false,
                replaceNBSP: false,
                removeEmptyElements: false,
                allowTags: false,
                denyTags: false
            },
            enter: 'P',
            allowResizeX: false,
            allowResizeY: true,
            minHeight: 300,
            // Keep HTML intact when pasting
            processPasteHTML: false,
            askBeforePasteHTML: false,
            askBeforePasteFromWord: false,
            defaultActionOnPaste: 'insert_as_html'
        });
        // Store instance on the element so admin.js can reach it via
        // [data-editor-target] without relying on a global variable.
        contentTextarea._joditEditor = joditEditor;
    }

    // ── Slug Auto-Generation ─────────────────────────────────────────────
    var titleInput = document.getElementById('title');
    var slugInput  = document.getElementById('slug');

    <?php if (!$isEdit): ?>
    if (titleInput && slugInput) {
        titleInput.addEventListener('input', function () {
            if (!slugInput._userEdited) {
                slugInput.value = slugifyTitle(this.value);
            }
        });
        slugInput.addEventListener('input', function () {
            this._userEdited = (this.value.trim() !== '');
        });
    }
    <?php endif; ?>

    function slugifyTitle(str) {
        var map = {
            'ä':'ae','ö':'oe','ü':'ue','Ä':'ae','Ö':'oe','Ü':'ue','ß':'ss',
            'à':'a','á':'a','â':'a','ã':'a','å':'a','æ':'ae',
            'ç':'c','è':'e','é':'e','ê':'e','ë':'e',
            'ì':'i','í':'i','î':'i','ï':'i',
            'ñ':'n','ò':'o','ó':'o','ô':'o','õ':'o','ø':'o',
            'ù':'u','ú':'u','û':'u',
            'ý':'y','þ':'th','ÿ':'y'
        };
        return str
            .replace(/[äöüÄÖÜßàáâãåæçèéêëìíîïñòóôõøùúûýþÿ]/g, function (c) { return map[c] || c; })
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    // ── SEO Character Counters ───────────────────────────────────────────
    function updateCounter(inputId, lenId, limit) {
        var el  = document.getElementById(inputId);
        var len = document.getElementById(lenId);
        if (!el || !len) return;
        function update() {
            var n = el.value.length;
            len.textContent = n;
            len.className = n > limit ? 'seo-over' : (n > limit * 0.9 ? 'seo-warn' : '');
        }
        el.addEventListener('input', update);
        update();
    }

    updateCounter('seo_title',       'seo_title_len', 60);
    updateCounter('seo_description', 'seo_desc_len',  160);

    // ── Tag Input normalisation ──────────────────────────────────────────
    var tagsInput = document.getElementById('tags');
    if (tagsInput) {
        tagsInput.addEventListener('blur', function () {
            var tags = this.value.split(',').map(function (t) { return t.trim(); }).filter(Boolean);
            this.value = tags.join(', ');
        });
    }

    // Media Picker (for jodit content editor) is wired up by admin.js
    // via the [data-media-picker] / [data-editor-target] attributes on the button.

    // ── Featured Image – remove checkbox helper ──────────────────────────
    window.onRemoveImageChange = function(checked) {
        var preview = document.getElementById('featuredImgPreview');
        var pathInput = document.getElementById('featured_image_path');
        if (preview) preview.style.opacity = checked ? '0.4' : '1';
        if (checked && pathInput) pathInput.value = '';
    };

    // ── Featured Image Picker ────────────────────────────────────────────
    (function () {
        var pickerBtn    = document.getElementById('blogPickerBtn');
        var clearBtn     = document.getElementById('blogPickerClearBtn');
        var overlay      = document.getElementById('blogFeaturedPickerOverlay');
        var closeBtn     = document.getElementById('blogFeaturedPickerClose');
        var pathInput    = document.getElementById('featured_image_path');
        var previewBox   = document.getElementById('featuredImgPreview');
        var previewImg   = document.getElementById('featuredImgPreviewImg');
        var pickerBody   = document.getElementById('blogFeaturedPickerBody');
        var pickerLoaded = false;

        if (!overlay) return;

        function openPicker() {
            overlay.style.display = 'flex';
            if (!pickerLoaded) {
                renderPickerShell();
                loadPickerImages('', '');
                pickerLoaded = true;
            }
        }

        function closePicker() { overlay.style.display = 'none'; }

        if (pickerBtn) pickerBtn.addEventListener('click', openPicker);
        if (closeBtn)  closeBtn.addEventListener('click', closePicker);
        overlay.addEventListener('click', function (e) { if (e.target === overlay) closePicker(); });
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && overlay.style.display !== 'none') closePicker();
        });

        // Clear library selection
        if (clearBtn) {
            clearBtn.addEventListener('click', function () {
                pathInput.value = '';
                clearBtn.style.display = 'none';
                // Only hide preview if there is no persisted DB image
                var removeRow = document.getElementById('removeImageRow');
                if (!removeRow) {
                    previewBox.style.display = 'none';
                    previewImg.src = '';
                }
                pickerBtn.textContent = '📷 Select from Library';
            });
        }

        function selectImage(id, url, thumbUrl, name) {
            // Strip /uploads/ prefix to get the relative path stored in the DB
            var relPath = url.replace(/^\/uploads\//, '');
            pathInput.value = relPath;

            // Show preview
            previewImg.src = thumbUrl || url;
            previewBox.style.display = '';
            previewBox.style.opacity = '1';

            // Uncheck remove-image checkbox if present
            var removeCheckbox = document.getElementById('removeImage');
            if (removeCheckbox) removeCheckbox.checked = false;

            // Update buttons
            pickerBtn.textContent = '📷 Change Image';
            if (clearBtn) clearBtn.style.display = '';

            closePicker();
        }

        function renderPickerShell() {
            pickerBody.innerHTML =
                '<div class="media-picker-toolbar">' +
                    '<input type="text" class="media-picker-search" id="bfpSearch" placeholder="Search images…" autocomplete="off">' +
                    '<span class="media-picker-toolbar-label">Folder:</span>' +
                    '<select class="media-picker-folder" id="bfpFolder">' +
                        '<option value="">All media</option>' +
                        '<option value="0">Unassigned</option>' +
                    '</select>' +
                '</div>' +
                '<div class="media-picker-body" id="bfpGrid">' +
                    '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">Loading…</p>' +
                '</div>';

            var searchInput  = pickerBody.querySelector('#bfpSearch');
            var folderSelect = pickerBody.querySelector('#bfpFolder');
            var searchTimer;

            searchInput.addEventListener('input', function () {
                clearTimeout(searchTimer);
                var q = searchInput.value, folder = folderSelect.value;
                searchTimer = setTimeout(function () { loadPickerImages(q, folder); }, 350);
            });
            folderSelect.addEventListener('change', function () {
                loadPickerImages(searchInput.value, folderSelect.value);
            });
        }

        function loadPickerImages(q, folder) {
            var grid = document.getElementById('bfpGrid');
            if (!grid) return;
            grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:2rem;">Loading…</p>';

            var url = '/admin/media/picker-images?q=' + encodeURIComponent(q) +
                      '&folder=' + encodeURIComponent(folder);

            fetch(url, { credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    // Populate folder options once
                    var fs = document.getElementById('bfpFolder');
                    if (fs && fs.options.length <= 2 && data.folders && data.folders.length) {
                        data.folders.forEach(function (f) {
                            var opt = document.createElement('option');
                            opt.value = f.id; opt.textContent = f.name;
                            fs.appendChild(opt);
                        });
                    }

                    if (!data.images || data.images.length === 0) {
                        grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">No images found.</p>';
                        return;
                    }

                    var html = '<div class="media-picker-grid">';
                    data.images.forEach(function (img) {
                        html += '<div class="media-picker-item bfp-item"' +
                                ' data-id="'    + escH(img.id)        + '"' +
                                ' data-url="'   + escH(img.url)       + '"' +
                                ' data-thumb="' + escH(img.thumb_url || img.url) + '"' +
                                ' title="'      + escH(img.name)      + '">' +
                                '<img src="' + escH(img.thumb_url || img.url) + '" alt="' + escH(img.name) + '" loading="lazy">' +
                                '<div class="media-picker-item-name">' + escH(img.name) + '</div>' +
                                '</div>';
                    });
                    html += '</div>';
                    grid.innerHTML = html;

                    grid.querySelectorAll('.bfp-item').forEach(function (item) {
                        item.addEventListener('click', function () {
                            selectImage(item.dataset.id, item.dataset.url, item.dataset.thumb, item.title);
                        });
                    });
                })
                .catch(function () {
                    var g = document.getElementById('bfpGrid');
                    if (g) g.innerHTML = '<p style="text-align:center;color:var(--admin-danger,#c0392b);padding-top:3rem;">Failed to load images.</p>';
                });
        }

        function escH(str) {
            return String(str)
                .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
        }
    }());
})();
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
