<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: ../login.php");
    exit;
}
include '../../includes/db.php';

// Edit mode: load existing post
$editPost = null;
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$postType = isset($_GET['type']) ? $_GET['type'] : 'blog';

if ($editId > 0) {
    if ($postType === 'services') {
        $stmt = $conn->prepare("SELECT id, title, description AS content, image_url FROM services WHERE id = ?");
    } else {
        $stmt = $conn->prepare("SELECT * FROM blogs WHERE id = ?");
    }
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $editPost = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}
$pageTitle = $editPost ? 'Edit Post' : 'Add New Post';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - Block Editor</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="wp-style.css">

    <!-- Editor.js Core -->
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>
    <!-- Editor.js Block Tools -->
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/header@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/nested-list@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/image@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/quote@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/code@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/table@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/delimiter@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/raw@latest"></script>
    <!-- Editor.js Inline Tools -->
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/inline-code@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/marker@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@editorjs/underline@latest"></script>
    <!-- Editor.js DragDrop + Undo — REQUIRED for drag-to-reorder and Ctrl+Z -->
    <script src="https://cdn.jsdelivr.net/npm/editorjs-drag-drop@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/editorjs-undo@latest"></script>
    <!-- Custom Block Definitions -->
    <script src="custom-blocks.js"></script>

    <style>
        body { background-color: #f0f2f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; }
        .edit-post-header {
            background: #fff;
            border-bottom: 1px solid #e0e0e0;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .editor-wrapper {
            background: white;
            padding: 40px;
            border: 1px solid #e0e0e0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            min-height: 500px;
        }
        /* Tab content panels */
        .tab-panel { display: none; }
        .tab-panel.active { display: block; }

        /* Patterns panel */
        .patterns-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 10px;
            padding: 12px 16px;
        }
        .pattern-item {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            cursor: pointer;
            background: #f9f9f9;
            font-size: 13px;
            transition: background 0.15s, border-color 0.15s;
        }
        .pattern-item:hover { background: #e8f0fe; border-color: #007cba; }
        .pattern-item strong { display: block; margin-bottom: 4px; color: #1e1e1e; }
        .pattern-item small { color: #757575; }

        /* Media panel */
        .media-panel-content {
            padding: 16px;
            text-align: center;
        }
        .media-upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 32px 16px;
            cursor: pointer;
            transition: border-color 0.15s;
            margin-bottom: 12px;
        }
        .media-upload-area:hover { border-color: #007cba; }
        .media-upload-area i { font-size: 36px; color: #aaa; margin-bottom: 8px; display: block; }
        .media-upload-area p { font-size: 13px; color: #757575; margin: 0; }
        #media-file-input { display: none; }
        #media-preview-list { text-align: left; }
        .media-preview-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 8px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.1s;
        }
        .media-preview-item:hover { background: #f0f0f0; }
        .media-preview-item img { width: 48px; height: 48px; object-fit: cover; border-radius: 3px; }

        /* Post settings sidebar */
        .post-settings-panel {
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            height: calc(100vh - 80px);
            overflow-y: auto;
            font-size: 13px;
        }
        .settings-section { border-bottom: 1px solid #eee; padding: 16px; }
        .settings-section h6 { font-size: 11px; text-transform: uppercase; color: #757575; font-weight: 600; margin-bottom: 12px; }
        .status-badge { display: inline-block; padding: 3px 8px; border-radius: 10px; font-size: 11px; font-weight: 500; }
        .status-draft { background: #f0f0f0; color: #555; }

        /* Toast notification */
        #toast-container {
            position: fixed;
            bottom: 24px;
            right: 24px;
            z-index: 9999;
        }
        .toast-msg {
            background: #1e1e1e;
            color: #fff;
            padding: 12px 20px;
            border-radius: 6px;
            margin-top: 8px;
            font-size: 13px;
            animation: slideIn 0.2s ease;
        }
        .toast-msg.success { background: #00a32a; }
        .toast-msg.error { background: #d63638; }
        @keyframes slideIn { from { opacity:0; transform: translateY(10px); } to { opacity:1; transform: translateY(0); } }

        /* ====== EDITORJS TOOLBAR & DRAG HANDLE ====== */
        .ce-toolbar__content, .ce-block__content {
            max-width: 800px;
        }

        /* Show toolbar actions reliably when block is focused */
        .ce-toolbar--opened {
            display: block !important;
        }
        .ce-toolbar--opened .ce-toolbar__actions {
            opacity: 1 !important;
            visibility: visible !important;
            display: flex !important;
        }

        /* ==== DRAG HANDLE – The real fix ==== */
        /* The DragDrop plugin injects a .cdx-drag-icon inside .ce-toolbar__settings-btn */
        /* We ensure it is visible and shows the grab cursor */
        .ce-toolbar__settings-btn {
            display: inline-flex !important;
            align-items: center;
            justify-content: center;
            opacity: 1 !important;
            visibility: visible !important;
            cursor: grab !important;
            width: 26px;
            height: 26px;
        }
        .ce-toolbar__settings-btn:active {
            cursor: grabbing !important;
        }
        /* Sortable ghost while dragging */
        .ce-block--dragging {
            opacity: 0.5;
            background: #f0f7ff;
            border: 2px dashed #007cba;
            border-radius: 4px;
        }
        /* Drop zone highlight */
        .codex-editor__redactor .ce-block--drop-target {
            border-top: 3px solid #007cba !important;
        }

        /* Plus button visibility */
        .ce-toolbar--opened .ce-toolbar__plus {
            display: inline-flex !important;
            opacity: 1 !important;
        }

        /* Block hover: subtle left border to show it's selectable */
        .ce-block:hover {
            background: rgba(0,124,186,0.03);
            border-radius: 4px;
        }
        .ce-block--focused {
            background: rgba(0,124,186,0.06) !important;
            border-radius: 4px;
        }

        /* ====== ALIGNMENT TUNE CSS ====== */
        .custom-align-wrapper { transition: all 0.2s ease; width: 100%; }
        .custom-align-wrapper::after { content: ""; display: table; clear: both; }
        .custom-align-wrapper.align-left { float: left; width: 50%; margin-right: 20px; margin-bottom: 20px; }
        .custom-align-wrapper.align-right { float: right; width: 50%; margin-left: 20px; margin-bottom: 20px; }
        .custom-align-wrapper.align-center { display: flex; justify-content: center; margin: 0 auto; }
        .custom-align-wrapper.align-wide { width: 130%; margin-left: -15%; max-width: none; }
        .custom-align-wrapper.align-full { width: 100vw; position: relative; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; max-width: 100vw; }

        /* ====== MEDIA LIBRARY MODAL ====== */
        .ml-overlay {
            display: none; position: fixed; inset: 0;
            background: rgba(0,0,0,0.5); z-index: 99999;
            align-items: center; justify-content: center;
        }
        .ml-overlay.open { display: flex; }
        .ml-modal {
            background: #fff; border-radius: 12px;
            width: 92vw; max-width: 900px; height: 85vh;
            display: flex; flex-direction: column;
            overflow: hidden;
            box-shadow: 0 24px 60px rgba(0,0,0,0.25);
            animation: mlPop 0.18s ease;
        }
        @keyframes mlPop { from { transform: scale(0.95); opacity:0; } to { transform: scale(1); opacity:1; } }
        .ml-header {
            padding: 16px 20px; border-bottom: 1px solid #e0e0e0;
            display: flex; align-items: center; justify-content: space-between;
        }
        .ml-header h5 { margin: 0; font-size: 16px; font-weight: 700; }
        .ml-close {
            width: 32px; height: 32px; border: none; background: #f0f0f0;
            border-radius: 50%; cursor: pointer; font-size: 16px; line-height: 1;
            display: flex; align-items: center; justify-content: center;
        }
        .ml-toolbar {
            padding: 12px 20px; border-bottom: 1px solid #eee;
            display: flex; gap: 10px; align-items: center;
        }
        .ml-upload-btn {
            padding: 7px 16px; border: 1.5px dashed #0d6efd; border-radius: 8px;
            background: #f0f6ff; color: #0d6efd; font-size: 13px; font-weight: 500;
            cursor: pointer; display: inline-flex; align-items: center; gap: 6px;
            transition: background 0.15s;
        }
        .ml-upload-btn:hover { background: #dbeafe; }
        .ml-search {
            flex: 1; padding: 7px 12px; border: 1.5px solid #ddd; border-radius: 8px;
            font-size: 13px; max-width: 260px;
        }
        .ml-search:focus { outline: none; border-color: #0d6efd; }
        .ml-body { flex: 1; overflow-y: auto; padding: 16px 20px; }
        .ml-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
            gap: 10px;
        }
        .ml-item {
            position: relative; border-radius: 8px; overflow: hidden;
            border: 2.5px solid transparent; cursor: pointer;
            aspect-ratio: 1; background: #f5f5f5;
            transition: border-color 0.15s, transform 0.12s;
        }
        .ml-item:hover { border-color: #93c5fd; transform: scale(1.02); }
        .ml-item.selected { border-color: #0d6efd; }
        .ml-item.selected::after {
            content: '\2713'; position: absolute; top: 6px; right: 6px;
            width: 22px; height: 22px; background: #0d6efd; color: white;
            border-radius: 50%; font-size: 13px; font-weight: 700;
            display: flex; align-items: center; justify-content: center;
        }
        .ml-item img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .ml-item-name {
            position: absolute; bottom: 0; left: 0; right: 0;
            background: rgba(0,0,0,0.55); color: white;
            font-size: 10px; padding: 3px 5px;
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
        .ml-footer {
            padding: 12px 20px; border-top: 1px solid #eee;
            display: flex; align-items: center; justify-content: space-between;
        }
        .ml-selected-info { font-size: 13px; color: #555; }
        .ml-footer-btns { display: flex; gap: 8px; }
        .ml-empty { text-align: center; padding: 60px 20px; color: #aaa; font-size: 14px; }
        .ml-empty i { font-size: 40px; display: block; margin-bottom: 12px; }
    </style>
</head>
<body>

<div class="edit-post-header">
    <div class="d-flex align-items-center">
        <a href="../dashboard.php" class="btn btn-icon me-3" style="color: #1e1e1e;" title="Back to Dashboard">
            <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>
        </a>
        <h5 class="mb-0 fw-bold"><?= htmlspecialchars($pageTitle) ?></h5>
        <span id="autosave-status" class="ms-3" style="font-size:12px;color:#757575;"></span>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <label for="post-type" class="mb-0 small fw-bold text-muted d-none d-lg-inline">Target:</label>
        <select id="post-type" class="form-select form-select-sm" style="width: auto; font-weight: 700; color: #01508c; border: 2px solid #01508c; border-radius: 6px; padding: 5px 14px; background-color: #f0f7ff;" onchange="syncPostType(this.value)" <?= $editPost ? 'disabled' : '' ?>>
            <option value="blog" <?= ($postType === 'blog') ? 'selected' : '' ?>>📝 Blog Post (to /blog.php)</option>
            <option value="services" <?= ($postType === 'services') ? 'selected' : '' ?>>⚙️ Services Post (to /services)</option>
        </select>
        <span class="status-badge status-draft" id="post-status-badge">Draft</span>
        <a href="insert_demo_blog.php" class="btn btn-sm" style="background:#7c3aed;color:#fff;font-weight:600;" title="Insert a demo blog post with ALL blocks to test the editor">
            🧪 Demo Blog
        </a>
        <button id="save-draft-btn" class="btn btn-outline-secondary btn-sm">Save Draft</button>
        <button id="save-button" class="btn btn-primary btn-sm px-4">Publish</button>
    </div>
</div>

<div class="container-fluid mt-4">
    <div class="row g-3">
        <!-- Inserter Sidebar (Left) -->
        <div class="col-md-3 col-lg-2 d-none d-md-block">
            <div class="wp-sidebar">
                <?php include 'sidebar.php'; ?>
            </div>
        </div>

        <!-- Editor Area (Center) -->
        <div class="col-md-6 col-lg-8">
            <div class="editor-wrapper">
                <input type="text" id="post-title" class="form-control mb-4"
                    placeholder="Add title"
                    value="<?= $editPost ? htmlspecialchars($editPost['title']) : '' ?>"
                    style="font-size: 2.5rem; font-weight: bold; border: none; box-shadow: none; padding: 0;">
                <div id="editorjs"></div>
            </div>
        </div>

        <!-- Post Settings Sidebar (Right) -->
        <div class="col-md-3 col-lg-2 d-none d-md-block">
            <div class="post-settings-panel">
                <div class="settings-section" style="background: #f8fafc; border-bottom: 2px solid #e2e8f0;">
                    <h6>Publish Destination</h6>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="sidebar_post_type" id="type_blog" value="blog" <?= ($postType === 'blog') ? 'checked' : '' ?> onchange="syncPostType('blog')" <?= $editPost ? 'disabled' : '' ?>>
                        <label class="form-check-label fw-bold" for="type_blog" style="color: #01508c; cursor: pointer;">
                            <i class="fas fa-newspaper me-1"></i> Blog Post
                            <div class="text-muted" style="font-size: 11px; font-weight: normal;">Appears on <a href="/bm/blog.php" target="_blank" style="color:#01508c;text-decoration:underline;">/blog.php</a></div>
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="sidebar_post_type" id="type_services" value="services" <?= ($postType === 'services') ? 'checked' : '' ?> onchange="syncPostType('services')" <?= $editPost ? 'disabled' : '' ?>>
                        <label class="form-check-label fw-bold" for="type_services" style="color: #059669; cursor: pointer;">
                            <i class="fas fa-cogs me-1"></i> Services Post
                            <div class="text-muted" style="font-size: 11px; font-weight: normal;">Appears on <a href="/bm/services" target="_blank" style="color:#059669;text-decoration:underline;">/services</a></div>
                        </label>
                    </div>
                </div>

                <div class="settings-section">
                    <h6>Summary</h6>
                    <div class="mb-2"><strong>Visibility:</strong> Public</div>
                    <div class="mb-2"><strong>Publish:</strong> Immediately</div>
                    <div><strong>Status:</strong> <span id="status-text">Draft</span></div>
                </div>
                <div class="settings-section">
                    <h6>Featured Image</h6>
                    <div id="featured-image-preview" class="mb-2" style="display:none;">
                        <img id="featured-img-tag" src="" alt="Featured Image" style="width:100%;border-radius:4px;">
                        <button class="btn btn-sm btn-link text-danger p-0 mt-1" id="remove-featured-img">Remove image</button>
                    </div>
                    <button class="btn btn-outline-primary btn-sm w-100 mb-2" type="button" onclick="openMediaLibrary('featured')">
                        <i class="fas fa-images me-1"></i> Select an Image
                    </button>
                    <label class="btn btn-outline-secondary btn-sm w-100" style="cursor:pointer;">
                        <input type="file" id="featured-image-input" accept="image/*" style="display:none;">
                        <i class="fas fa-upload me-1"></i> Upload Image
                    </label>
                </div>
                <div class="settings-section">
                    <h6>Excerpt</h6>
                    <textarea id="post-excerpt" class="form-control" rows="3" placeholder="Write an excerpt (optional)" style="font-size:13px;"></textarea>
                </div>
                <div class="settings-section">
                    <h6>Categories</h6>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="News" id="cat-news">
                        <label class="form-check-label" for="cat-news">News</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="Blog" id="cat-blog" checked>
                        <label class="form-check-label" for="cat-blog">Blog</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="Tutorial" id="cat-tutorial">
                        <label class="form-check-label" for="cat-tutorial">Tutorial</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="Announcement" id="cat-announcement">
                        <label class="form-check-label" for="cat-announcement">Announcement</label>
                    </div>
                </div>
                <div class="settings-section">
                    <h6>Tags</h6>
                    <input type="text" id="post-tags" class="form-control form-control-sm" placeholder="Add tags, separated by commas">
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast container -->
<div id="toast-container"></div>

<script>
// ========== GLOBAL HELPERS ==========
function showToast(message, type) {
    var container = document.getElementById('toast-container');
    var toast = document.createElement('div');
    toast.className = 'toast-msg ' + (type || '');
    toast.textContent = message;
    container.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 3000);
}

let autosaveTimer;
function showAutosaveStatus(text) {
    const el = document.getElementById('autosave-status');
    if (el) el.textContent = text;
    clearTimeout(autosaveTimer);
    autosaveTimer = setTimeout(function() { if (el) el.textContent = ''; }, 4000);
}

// ====================== SIDEBAR TABS ======================
(function initTabs() {
    const tabs = document.querySelectorAll('.inserter-tab');
    const panelIds = ['blocks-panel', 'patterns-panel', 'media-panel'];
    tabs.forEach(function(tab, index) {
        tab.addEventListener('click', function() {
            tabs.forEach(function(t) { t.classList.remove('active'); });
            tab.classList.add('active');
            panelIds.forEach(function(id) {
                const el = document.getElementById(id);
                if (el) el.classList.remove('active');
            });
            const target = document.getElementById(panelIds[index]);
            if (target) target.classList.add('active');
            fixSidebarHeight();
        });
    });
})();

// ====================== SIDEBAR HEIGHT FIX ======================
function fixSidebarHeight() {
    const sidebar = document.querySelector('.wp-sidebar');
    if (!sidebar) return;
    const header = sidebar.querySelector('.block-editor-inserter__header');
    const activePanel = sidebar.querySelector('.tab-panel.active');
    if (!activePanel) return;
    const searchBox = activePanel.querySelector('.block-editor-inserter__search');
    const results = activePanel.querySelector('.block-editor-inserter__results');
    if (!results) return;

    const headerH = header ? header.offsetHeight : 52;
    const searchH = searchBox ? searchBox.offsetHeight : 44;
    const viewportH = window.innerHeight;
    const topOffset = 68; // height of the top nav bar
    const availableH = viewportH - topOffset - headerH - searchH - 16;

    results.style.height = Math.max(availableH, 200) + 'px';
    results.style.overflowY = 'auto';
    results.style.overflowX = 'hidden';
}

// Run on load and resize
document.addEventListener('DOMContentLoaded', fixSidebarHeight);
window.addEventListener('resize', fixSidebarHeight);
// Also run after a short delay to ensure layout is settled
setTimeout(fixSidebarHeight, 300);

// ====================== EDITOR.JS INIT ======================
let editor;

class AlignmentBlockTune {
    static get isTune() { return true; }
    constructor({ api, data, config, block }) {
        this.api = api;
        this.block = block;
        this.data = data || { alignment: 'none' };
        this.alignments = [
            { name: 'none', icon: '<i class="fas fa-minus"></i>', label: 'None' },
            { name: 'wide', icon: '<i class="fas fa-arrows-alt-h"></i>', label: 'Wide width' },
            { name: 'full', icon: '<i class="fas fa-expand-arrows-alt"></i>', label: 'Full width' },
            { name: 'left', icon: '<i class="fas fa-align-left"></i>', label: 'Align left' },
            { name: 'center', icon: '<i class="fas fa-align-center"></i>', label: 'Align center' },
            { name: 'right', icon: '<i class="fas fa-align-right"></i>', label: 'Align right' }
        ];
    }
    render() {
        return this.alignments.map(tune => ({
            icon: tune.icon,
            label: tune.label,
            isActive: this.data.alignment === tune.name,
            closeOnActivate: true,
            onActivate: () => {
                this.data.alignment = tune.name;
                this.applyAlignment();
                this.block.dispatchChange();
            }
        }));
    }
    wrap(blockContent) {
        this.wrapper = document.createElement('div');
        this.wrapper.classList.add('custom-align-wrapper');
        this.wrapper.appendChild(blockContent);
        this.applyAlignment();
        return this.wrapper;
    }
    applyAlignment() {
        this.wrapper.className = 'custom-align-wrapper align-' + this.data.alignment;
        // Fix for EditorJS popover placement changing due to floats
        if (this.data.alignment === 'left' || this.data.alignment === 'right') {
            document.querySelector('.ce-toolbar').style.display = 'none';
        }
    }
    save() {
        return this.data;
    }
}

class SimpleGallery {
    static get toolbox() { return { title: 'Gallery', icon: '<i class="fas fa-images"></i>' }; }
    constructor({data}) { this.data = (data && data.urls) ? data : { urls: [] }; }
    render() {
        this.wrapper = document.createElement('div');
        this.wrapper.style.display = 'grid';
        this.wrapper.style.gridTemplateColumns = 'repeat(3, 1fr)';
        this.wrapper.style.gap = '10px';
        this.wrapper.style.padding = '10px';
        this.wrapper.style.background = '#f9f9f9';
        this.wrapper.style.border = '1px dashed #ccc';
        
        this.addBtn = document.createElement('button');
        this.addBtn.type = 'button';
        this.addBtn.innerHTML = '<i class="fas fa-plus"></i> Add Image URL';
        this.addBtn.className = 'btn btn-sm btn-outline-secondary';
        this.addBtn.style.gridColumn = '1 / -1';
        this.addBtn.onclick = () => {
            let url = prompt('Image URL:');
            if (url) {
                this.data.urls.push(url);
                this.renderImages();
            }
        };
        this.wrapper.appendChild(this.addBtn);
        this.imagesContainer = document.createElement('div');
        this.imagesContainer.style.display = 'contents';
        this.wrapper.appendChild(this.imagesContainer);
        this.renderImages();
        return this.wrapper;
    }
    renderImages() {
        this.imagesContainer.innerHTML = '';
        this.data.urls.forEach((url, i) => {
            let img = document.createElement('img');
            img.src = url;
            img.style.width = '100%';
            img.style.height = '120px';
            img.style.objectFit = 'cover';
            img.style.borderRadius = '4px';
            img.title = 'Double click to remove';
            img.ondblclick = () => {
                if (confirm('Remove image?')) {
                    this.data.urls.splice(i, 1);
                    this.renderImages();
                }
            };
            this.imagesContainer.appendChild(img);
        });
    }
    save() { return { urls: this.data.urls }; }
}

class SimpleVideo {
    static get toolbox() { return { title: 'Video', icon: '<i class="fas fa-video"></i>' }; }
    constructor({data}) { this.data = (data && data.url) ? data : { url: '' }; }
    render() {
        this.wrapper = document.createElement('div');
        this.input = document.createElement('input');
        this.input.placeholder = 'Paste Video URL (MP4) or Embed...';
        this.input.className = 'form-control mb-2';
        this.input.value = this.data.url;
        
        this.player = document.createElement('video');
        this.player.controls = true;
        this.player.style.width = '100%';
        this.player.style.display = this.data.url ? 'block' : 'none';
        if (this.data.url) this.player.src = this.data.url;

        this.input.addEventListener('change', (e) => {
            this.player.src = e.target.value;
            this.player.style.display = e.target.value ? 'block' : 'none';
        });
        this.wrapper.appendChild(this.input);
        this.wrapper.appendChild(this.player);
        return this.wrapper;
    }
    save() { return { url: this.input.value }; }
}

class SimpleAudio {
    static get toolbox() { return { title: 'Audio', icon: '<i class="fas fa-music"></i>' }; }
    constructor({data}) { this.data = (data && data.url) ? data : { url: '' }; }
    render() {
        this.wrapper = document.createElement('div');
        this.input = document.createElement('input');
        this.input.placeholder = 'Paste Audio URL...';
        this.input.className = 'form-control mb-2';
        this.input.value = this.data.url;
        
        this.player = document.createElement('audio');
        this.player.controls = true;
        this.player.style.width = '100%';
        this.player.style.display = this.data.url ? 'block' : 'none';
        if (this.data.url) this.player.src = this.data.url;

        this.input.addEventListener('change', (e) => {
            this.player.src = e.target.value;
            this.player.style.display = e.target.value ? 'block' : 'none';
        });
        this.wrapper.appendChild(this.input);
        this.wrapper.appendChild(this.player);
        return this.wrapper;
    }
    save() { return { url: this.input.value }; }
}

class SimpleCover {
    static get toolbox() { return { title: 'Cover', icon: '<i class="fas fa-bookmark"></i>' }; }
    constructor({data}) { this.data = (data && data.text) ? data : { imageUrl: '', text: 'Cover Title' }; }
    render() {
        this.wrapper = document.createElement('div');
        this.wrapper.style.position = 'relative';
        this.wrapper.style.minHeight = '250px';
        this.wrapper.style.background = '#ccc';
        this.wrapper.style.display = 'flex';
        this.wrapper.style.alignItems = 'center';
        this.wrapper.style.justifyContent = 'center';
        this.wrapper.style.borderRadius = '8px';
        this.wrapper.style.overflow = 'hidden';
        if (this.data.imageUrl) {
            this.wrapper.style.backgroundImage = `url(${this.data.imageUrl})`;
            this.wrapper.style.backgroundSize = 'cover';
            this.wrapper.style.backgroundPosition = 'center';
        }

        this.bgInput = document.createElement('input');
        this.bgInput.placeholder = 'Cover Image URL...';
        this.bgInput.className = 'form-control form-control-sm';
        this.bgInput.style.position = 'absolute';
        this.bgInput.style.top = '10px';
        this.bgInput.style.left = '10px';
        this.bgInput.style.width = 'calc(100% - 20px)';
        this.bgInput.style.zIndex = '10';
        this.bgInput.value = this.data.imageUrl;
        this.bgInput.onchange = (e) => {
            this.wrapper.style.backgroundImage = `url(${e.target.value})`;
        };

        this.textInput = document.createElement('h2');
        this.textInput.contentEditable = true;
        this.textInput.innerHTML = this.data.text;
        this.textInput.style.color = '#fff';
        this.textInput.style.textShadow = '0 2px 4px rgba(0,0,0,0.8)';
        this.textInput.style.zIndex = '5';
        this.textInput.style.textAlign = 'center';
        this.textInput.style.margin = '0';
        this.textInput.style.padding = '20px';

        this.wrapper.appendChild(this.bgInput);
        this.wrapper.appendChild(this.textInput);
        return this.wrapper;
    }
    save() { return { imageUrl: this.bgInput.value, text: this.textInput.innerHTML }; }
}

class SimpleMediaText {
    static get toolbox() { return { title: 'Media & Text', icon: '<i class="fas fa-columns"></i>' }; }
    constructor({data}) { this.data = (data && data.text) ? data : { imageUrl: '', text: 'Add text content here...' }; }
    render() {
        this.wrapper = document.createElement('div');
        this.wrapper.style.display = 'flex';
        this.wrapper.style.gap = '20px';
        this.wrapper.style.alignItems = 'center';
        this.wrapper.style.background = '#fcfcfc';
        this.wrapper.style.padding = '15px';
        this.wrapper.style.border = '1px solid #eee';
        this.wrapper.style.borderRadius = '8px';

        this.mediaCol = document.createElement('div');
        this.mediaCol.style.flex = '1';
        this.mediaCol.style.display = 'flex';
        this.mediaCol.style.flexDirection = 'column';
        this.mediaCol.style.gap = '10px';

        this.imgInput = document.createElement('input');
        this.imgInput.placeholder = 'Media Image URL...';
        this.imgInput.className = 'form-control form-control-sm';
        this.imgInput.value = this.data.imageUrl;
        
        this.img = document.createElement('img');
        this.img.style.width = '100%';
        this.img.style.objectFit = 'cover';
        this.img.style.borderRadius = '4px';
        if (this.data.imageUrl) { this.img.src = this.data.imageUrl; } else { this.img.style.display = 'none'; }
        
        this.imgInput.onchange = (e) => {
            this.img.src = e.target.value;
            this.img.style.display = e.target.value ? 'block' : 'none';
        };

        this.mediaCol.appendChild(this.imgInput);
        this.mediaCol.appendChild(this.img);

        this.textCol = document.createElement('div');
        this.textCol.style.flex = '1';
        this.textCol.contentEditable = true;
        this.textCol.innerHTML = this.data.text;
        this.textCol.style.outline = 'none';

        this.wrapper.appendChild(this.mediaCol);
        this.wrapper.appendChild(this.textCol);
        return this.wrapper;
    }
    save() { return { imageUrl: this.imgInput.value, text: this.textCol.innerHTML }; }
}

class SimpleFile {
    static get toolbox() { return { title: 'File', icon: '<i class="fas fa-file"></i>' }; }
    constructor({data}) { this.data = (data && data.text) ? data : { url: '', text: 'Download File' }; }
    render() {
        this.wrapper = document.createElement('div');
        this.wrapper.className = 'p-3 border rounded bg-light';
        
        this.urlInput = document.createElement('input');
        this.urlInput.placeholder = 'File URL...';
        this.urlInput.className = 'form-control form-control-sm mb-2';
        this.urlInput.value = this.data.url;

        this.textInput = document.createElement('input');
        this.textInput.placeholder = 'Link Text...';
        this.textInput.className = 'form-control form-control-sm mb-2';
        this.textInput.value = this.data.text;

        this.preview = document.createElement('a');
        this.preview.href = this.data.url || '#';
        this.preview.innerText = this.data.text;
        this.preview.className = 'btn btn-primary btn-sm mt-1';
        this.preview.target = '_blank';

        this.urlInput.onchange = (e) => { this.preview.href = e.target.value; };
        this.textInput.onchange = (e) => { this.preview.innerText = e.target.value; };

        this.wrapper.appendChild(this.urlInput);
        this.wrapper.appendChild(this.textInput);
        this.wrapper.appendChild(this.preview);
        return this.wrapper;
    }
    save() { return { url: this.urlInput.value, text: this.textInput.value }; }
}

(function initEditor() {
    // Safely detect built-in & CDN classes
    const HeaderClass     = window.Header || null;
    const ListClass       = window.NestedList || window.EditorJSNestedList || window.List || null;
    const ImageClass      = window.ImageTool || window.Image || null;
    const QuoteClass      = window.Quote || null;
    const CodeClass       = window.CodeTool || window.Code || null;
    const TableClass      = window.Table || null;
    const DelimiterClass  = window.Delimiter || null;
    const RawClass        = window.RawTool || window.Raw || null;
    const InlineCodeClass = window.InlineCode || null;
    const MarkerClass     = window.Marker || null;
    const UnderlineClass  = window.Underline || null;

    const editorTools = {};

    if (typeof AlignmentBlockTune !== 'undefined') {
        editorTools.alignment = AlignmentBlockTune;
    }

    if (HeaderClass) {
        editorTools.header = {
            class: HeaderClass,
            inlineToolbar: true,
            config: { levels: [2, 3, 4], defaultLevel: 2 }
        };
    }

    if (ImageClass) {
        editorTools.image = {
            class: ImageClass,
            tunes: editorTools.alignment ? ['alignment'] : [],
            config: {
                endpoints: {
                    byFile: '../upload_image.php',
                    byUrl:  '../upload_by_url.php'
                }
            }
        };
    }

    if (ListClass) {
        editorTools.list = { class: ListClass, inlineToolbar: true };
    }

    if (QuoteClass) {
        editorTools.quote = { class: QuoteClass, inlineToolbar: true };
    }

    if (CodeClass) {
        editorTools.code = { class: CodeClass };
    }

    if (TableClass) {
        editorTools.table = { class: TableClass, inlineToolbar: true };
    }

    if (DelimiterClass) {
        editorTools.delimiter = { class: DelimiterClass };
    }

    if (RawClass) {
        editorTools.raw = { class: RawClass };
    }

    // Custom Blocks (Media)
    if (typeof SimpleGallery !== 'undefined') editorTools.gallery = SimpleGallery;
    if (typeof SimpleAudio !== 'undefined') editorTools.audio = SimpleAudio;
    if (typeof SimpleCover !== 'undefined') editorTools.cover = SimpleCover;
    if (typeof SimpleFile !== 'undefined') editorTools.file = SimpleFile;
    if (typeof SimpleMediaText !== 'undefined') editorTools['media-text'] = SimpleMediaText;
    if (typeof SimpleVideo !== 'undefined') editorTools.video = SimpleVideo;

    // Custom Blocks (Text)
    if (typeof PreformattedBlock !== 'undefined') editorTools.preformatted = PreformattedBlock;
    if (typeof PullquoteBlock !== 'undefined') editorTools.pullquote = PullquoteBlock;
    if (typeof VerseBlock !== 'undefined') editorTools.verse = VerseBlock;
    if (typeof DetailsBlock !== 'undefined') editorTools.details = DetailsBlock;
    if (typeof ClassicBlock !== 'undefined') editorTools.classic = ClassicBlock;

    // Custom Blocks (Design)
    if (typeof ButtonBlock !== 'undefined') editorTools.button = ButtonBlock;
    if (typeof SeparatorBlock !== 'undefined') editorTools.separator = SeparatorBlock;
    if (typeof SpacerBlock !== 'undefined') editorTools.spacer = SpacerBlock;
    if (typeof ColumnsBlock !== 'undefined') editorTools.columns = ColumnsBlock;
    if (typeof GroupBlock !== 'undefined') editorTools.group = GroupBlock;
    if (typeof RowBlock !== 'undefined') editorTools.row = RowBlock;
    if (typeof StackBlock !== 'undefined') editorTools.stack = StackBlock;
    if (typeof GridBlock !== 'undefined') editorTools.grid = GridBlock;
    if (typeof MoreBlock !== 'undefined') editorTools.more = MoreBlock;

    // Custom Blocks (Widgets)
    if (typeof ShortcodeBlock !== 'undefined') editorTools.shortcode = ShortcodeBlock;
    if (typeof SearchBlock !== 'undefined') editorTools.search = SearchBlock;
    if (typeof ArchivesBlock !== 'undefined') editorTools.archives = ArchivesBlock;
    if (typeof CalendarBlock !== 'undefined') editorTools.calendar = CalendarBlock;
    if (typeof CategoriesListBlock !== 'undefined') editorTools.categories = CategoriesListBlock;
    if (typeof LatestPostsBlock !== 'undefined') editorTools['latest-posts'] = LatestPostsBlock;
    if (typeof SocialIconsBlock !== 'undefined') editorTools.social = SocialIconsBlock;
    if (typeof TermsListBlock !== 'undefined') editorTools['terms-list'] = TermsListBlock;
    if (typeof LatestCommentsBlock !== 'undefined') editorTools['latest-comments'] = LatestCommentsBlock;
    if (typeof PageListBlock !== 'undefined') editorTools['page-list'] = PageListBlock;
    if (typeof RssBlock !== 'undefined') editorTools.rss = RssBlock;
    if (typeof TagCloudBlock !== 'undefined') editorTools['tag-cloud'] = TagCloudBlock;

    // Custom Blocks (Theme)
    if (typeof NavigationBlock !== 'undefined') editorTools.navigation = NavigationBlock;
    if (typeof SiteLogoBlock !== 'undefined') editorTools['site-logo'] = SiteLogoBlock;
    if (typeof SiteTitleBlock !== 'undefined') editorTools['site-title'] = SiteTitleBlock;
    if (typeof AuthorBlock !== 'undefined') editorTools.author = AuthorBlock;
    if (typeof AvatarBlock !== 'undefined') editorTools.avatar = AvatarBlock;
    if (typeof SiteTaglineBlock !== 'undefined') editorTools['site-tagline'] = SiteTaglineBlock;
    if (typeof QueryLoopBlock !== 'undefined') editorTools['query-loop'] = QueryLoopBlock;
    if (typeof PostTitleBlock !== 'undefined') editorTools['post-title'] = PostTitleBlock;
    if (typeof PostExcerptBlock !== 'undefined') editorTools['post-excerpt'] = PostExcerptBlock;
    if (typeof FeaturedImageBlock !== 'undefined') editorTools['featured-image'] = FeaturedImageBlock;
    if (typeof AuthorNameBlock !== 'undefined') editorTools['author-name'] = AuthorNameBlock;
    if (typeof PostDateBlock !== 'undefined') editorTools['post-date'] = PostDateBlock;
    if (typeof ModifiedDateBlock !== 'undefined') editorTools['modified-date'] = ModifiedDateBlock;
    if (typeof PostCategoriesBlock !== 'undefined') editorTools['post-categories'] = PostCategoriesBlock;
    if (typeof PostTagsBlock !== 'undefined') editorTools['post-tags'] = PostTagsBlock;

    // Embeds
    if (typeof EmbedBlock !== 'undefined') {
        editorTools['embed-youtube'] = { class: EmbedBlock, config: { platform: 'YouTube', icon: '<i class="fab fa-youtube" style="color:#FF0000"></i>' } };
        editorTools['embed-twitter'] = { class: EmbedBlock, config: { platform: 'Twitter', icon: '<i class="fab fa-twitter" style="color:#1DA1F2"></i>' } };
        editorTools['embed-wordpress'] = { class: EmbedBlock, config: { platform: 'WordPress', icon: '<i class="fab fa-wordpress" style="color:#21759B"></i>' } };
        editorTools['embed-spotify'] = { class: EmbedBlock, config: { platform: 'Spotify', icon: '<i class="fab fa-spotify" style="color:#1DB954"></i>' } };
        editorTools['embed-soundcloud'] = { class: EmbedBlock, config: { platform: 'SoundCloud', icon: '<i class="fab fa-soundcloud" style="color:#FF5500"></i>' } };
        editorTools['embed-flickr'] = { class: EmbedBlock, config: { platform: 'Flickr', icon: '<i class="fab fa-flickr"></i>' } };
        editorTools['embed-vimeo'] = { class: EmbedBlock, config: { platform: 'Vimeo', icon: '<i class="fab fa-vimeo-v" style="color:#1AB7EA"></i>' } };
        editorTools['embed-reddit'] = { class: EmbedBlock, config: { platform: 'Reddit', icon: '<i class="fab fa-reddit" style="color:#FF4500"></i>' } };
        editorTools['embed-tiktok'] = { class: EmbedBlock, config: { platform: 'TikTok', icon: '<i class="fab fa-tiktok"></i>' } };
        editorTools['embed-instagram'] = { class: EmbedBlock, config: { platform: 'Instagram', icon: '<i class="fab fa-instagram" style="color:#E4405F"></i>' } };
        editorTools['embed-facebook'] = { class: EmbedBlock, config: { platform: 'Facebook', icon: '<i class="fab fa-facebook" style="color:#1877F2"></i>' } };
        editorTools['embed-pinterest'] = { class: EmbedBlock, config: { platform: 'Pinterest', icon: '<i class="fab fa-pinterest" style="color:#BD081C"></i>' } };
    }

    // Inline tools
    if (InlineCodeClass) editorTools.inlineCode = { class: InlineCodeClass, shortcut: 'CMD+SHIFT+M' };
    if (MarkerClass)     editorTools.marker     = { class: MarkerClass,     shortcut: 'CMD+SHIFT+H' };
    if (UnderlineClass)  editorTools.underline  = { class: UnderlineClass,  shortcut: 'CMD+U' };

    var existingData = <?= ($editPost && !empty($editPost['content'])) ? $editPost['content'] : 'null' ?>;
    if (typeof existingData === 'string') {
        try { existingData = JSON.parse(existingData); } catch(e) { existingData = null; }
    }

    try {
        window.editor = new EditorJS({
            holder: 'editorjs',
            placeholder: 'Start writing or click any block from the left panel to insert…',
            tools: editorTools,
            data: (existingData && existingData.blocks) ? existingData : {},
            onChange: function() {
                showAutosaveStatus('Unsaved changes');
            },
            onReady: function() {
                if (window.DragDrop) {
                    try { new DragDrop(window.editor); } catch(e) { console.warn('DragDrop init:', e); }
                }
                if (window.Undo) {
                    try { new Undo({ editor: window.editor }); } catch(e) { console.warn('Undo init:', e); }
                }
                injectLibraryButtons();
                setupStickyToolbar();
            }
        });
        editor = window.editor;
    } catch(err) {
        console.error('EditorJS init error:', err);
    }
})(); // End initEditor

// ---- Toolbar & Drag Setup ----
function setupStickyToolbar() {
    var editorEl = document.getElementById('editorjs');
    if (!editorEl) return;

    // Ensure the drag handle button never has its pointer events disabled
    // The DragDrop plugin attaches its own handlers to .ce-toolbar__settings-btn
    editorEl.addEventListener('mouseover', function(e) {
        var block = e.target.closest('.ce-block');
        if (!block) return;
        var settingsBtn = block.querySelector('.ce-toolbar__settings-btn');
        if (settingsBtn) {
            settingsBtn.style.cursor = 'grab';
            settingsBtn.style.display = 'inline-flex';
            settingsBtn.style.opacity = '1';
        }
    }, false);
}

// ---- Inject "Select from Library" button into EditorJS Image blocks ----
function injectLibraryButtons() {
    // Watch for new nodes added to the editor
    var editorEl = document.getElementById('editorjs');
    if (!editorEl) return;
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(m) {
            m.addedNodes.forEach(function(node) {
                if (node.nodeType !== 1) return;
                // Find image tool stubs (the empty state with file input)
                var stubs = node.querySelectorAll ? node.querySelectorAll('.image-tool__image-preloader, .image-tool__caption') : [];
                // Better: look for image-tool wrappers
                tryInjectBtn(node);
                node.querySelectorAll && node.querySelectorAll('.image-tool').forEach(tryInjectBtn);
            });
        });
    });
    observer.observe(editorEl, { childList: true, subtree: true });
    // Also inject into any existing image blocks
    editorEl.querySelectorAll('.image-tool').forEach(tryInjectBtn);
}

function tryInjectBtn(el) {
    // Find the file-input area inside the image tool block
    var wrapper = el.classList && el.classList.contains('image-tool') ? el : el.querySelector && el.querySelector('.image-tool');
    if (!wrapper) return;
    if (wrapper.dataset.mlInjected) return; // already injected
    wrapper.dataset.mlInjected = '1';

    // Wait for the input area to exist (it may not be rendered yet)
    setTimeout(function() {
        var inputWrapper = wrapper.querySelector('.cdx-button, [data-placeholder]');
        var container = wrapper.querySelector('.image-tool__image') || wrapper;
        // Build the button
        var btn = document.createElement('button');
        btn.type    = 'button';
        btn.className = 'ml-inject-btn';
        btn.innerHTML = '<i class="fas fa-images" style="margin-right:5px;"></i>Select from Library';
        btn.style.cssText = [
            'display:block', 'margin:8px auto 0', 'padding:6px 14px',
            'background:#f0f6ff', 'border:1.5px solid #0d6efd', 'border-radius:7px',
            'color:#0d6efd', 'font-size:12px', 'font-weight:600',
            'cursor:pointer', 'width:calc(100% - 16px)'
        ].join(';');
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            // Use byUrl to inject via the hidden URL input in the image tool
            openMediaLibrary('editorjs-block', function(url) {
                // Trigger EditorJS ImageTool.byUrl input
                var urlInput = wrapper.querySelector('input[placeholder*="URL"], input[placeholder*="url"], .image-tool__url-input input, input[type="url"]');
                if (urlInput) {
                    urlInput.value = url;
                    urlInput.dispatchEvent(new Event('input', { bubbles: true }));
                    // Hit Enter
                    urlInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true }));
                } else {
                    // Fallback: use fetch to call byUrl and render
                    var fd = new FormData();
                    fd.append('url', url);
                    fetch('../upload_by_url.php', { method:'POST', body:fd })
                        .then(function(r){ return r.json(); })
                        .then(function(data) {
                            if (data.success) {
                                // Find the img tag inside and set it directly
                                var imgEl = wrapper.querySelector('.image-tool__image img');
                                if (!imgEl) {
                                    imgEl = document.createElement('img');
                                    wrapper.querySelector('.image-tool__image') && wrapper.querySelector('.image-tool__image').appendChild(imgEl);
                                }
                                if (imgEl) imgEl.src = url;
                                // Also store url for EditorJS to read on save
                                wrapper.dataset.imageUrl = url;
                                wrapper.classList.add('image-tool--filled');
                                if (btn.parentNode) btn.parentNode.removeChild(btn);
                            }
                        });
                }
            });
        });

        // Insert button after the upload area
        var uploadArea = wrapper.querySelector('.image-tool__image-preloader');
        if (uploadArea && uploadArea.parentNode) {
            uploadArea.parentNode.insertBefore(btn, uploadArea.nextSibling);
        } else {
            wrapper.appendChild(btn);
        }
    }, 300);
}

// Edit mode globals
var _editId = <?= $editId > 0 ? $editId : 'null' ?>;

// All interactive features (search, blocks, patterns, media, save/publish)
(function initAllFeatures() {
    let featuredImageUrl = '';

    // ====================== SEARCH FILTER ======================
    const searchInput = document.querySelector('.components-text-control__input');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = searchInput.value.toLowerCase().trim();
            const items = document.querySelectorAll('#blocks-panel .block-editor-block-types-list__item');
            items.forEach(item => {
                const title = item.querySelector('.block-editor-block-types-list__item-title');
                const text = title ? title.innerText.toLowerCase() : '';
                item.style.display = (!query || text.includes(query)) ? 'flex' : 'none';
            });
            // Hide empty section headers
            document.querySelectorAll('#blocks-panel .block-editor-inserter__panel-header').forEach(header => {
                const panel = header.nextElementSibling;
                if (!panel) return;
                const visibleItems = panel.querySelectorAll('.block-editor-block-types-list__item:not([style*="display: none"])');
                header.style.display = visibleItems.length === 0 ? 'none' : '';
                panel.style.display = visibleItems.length === 0 ? 'none' : '';
            });
        });
    }

    // ====================== BLOCK INSERTION from Sidebar ======================
    // Map block type names to EditorJS tool names
    const typeMap = {
        'paragraph': 'paragraph',
        'header': 'header',
        'list': 'list',
        'image': 'image',
        'quote': 'quote',
        'code': 'code',
        'table': 'table',
        'delimiter': 'delimiter',
        'raw': 'raw',
        'gallery': 'gallery',
        'audio': 'audio',
        'cover': 'cover',
        'file': 'file',
        'media-text': 'media-text',
        'video': 'video'
    };

    // Default block data for initial insertion
    const defaultBlockData = {
        'paragraph': { text: '' },
        'header': { text: '', level: 2 },
        'list': { style: 'unordered', items: [''] },
        'quote': { text: '', caption: '' },
        'code': { code: '' },
        'table': { withHeadings: true, content: [['', ''], ['', '']] },
        'preformatted': { text: '' },
        'pullquote': { text: '', citation: '' },
        'verse': { text: '' },
        'details': { summary: 'Click to expand', content: 'Details content here...' },
        'button': { text: 'Click Here', url: '', style: 'primary' },
        'separator': {},
        'spacer': { height: 40 },
        'delimiter': {},
        'raw': { html: '' },
        'gallery': { urls: [] },
        'video': { url: '' },
        'audio': { url: '' },
        'cover': { imageUrl: '', text: 'Cover Heading' },
        'file': { url: '', text: 'Download File' },
        'media-text': { imageUrl: '', text: 'Media & text description' }
    };

    document.querySelectorAll('.block-editor-block-types-list__item').forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            const dataType = btn.getAttribute('data-type');
            const toolName = typeMap[dataType] || dataType;
            const ed = window.editor || editor;
            if (!ed) {
                showToast('Editor is initializing...', 'info');
                return;
            }
            ed.isReady.then(() => {
                const initialData = defaultBlockData[toolName] || {};
                try {
                    ed.blocks.insert(toolName, initialData);
                } catch(e) {
                    ed.blocks.insert(toolName);
                }
                ed.focus();
                const titleText = btn.querySelector('.block-editor-block-types-list__item-title')?.innerText || toolName;
                showToast('✓ Added: ' + titleText, 'success');
            }).catch(err => {
                console.error('Editor insert error:', err);
                showToast('Could not insert block', 'error');
            });
        });
    });

    // ====================== PATTERNS TAB ======================
    document.querySelectorAll('.pattern-item').forEach(item => {
        item.addEventListener('click', () => {
            const type = item.getAttribute('data-pattern');
            editor.isReady.then(() => {
                if (type === 'hero') {
                    editor.blocks.insert('header', { text: 'Your Page Title', level: 2 });
                    editor.blocks.insert('paragraph', { text: 'Add a compelling description about this section here.' });
                } else if (type === 'two-col') {
                    editor.blocks.insert('paragraph', { text: 'Left column content goes here.' });
                    editor.blocks.insert('delimiter');
                    editor.blocks.insert('paragraph', { text: 'Right column content goes here.' });
                } else if (type === 'cta') {
                    editor.blocks.insert('header', { text: 'Ready to get started?', level: 3 });
                    editor.blocks.insert('paragraph', { text: 'Take the next step. Click the button below to learn more.' });
                } else if (type === 'quote-block') {
                    editor.blocks.insert('quote', { text: 'Insert your inspiring quote here.', caption: '— Author Name', alignment: 'left' });
                } else if (type === 'numbered-list') {
                    editor.blocks.insert('list', { style: 'ordered', items: ['First item', 'Second item', 'Third item'] });
                }
                showToast('Pattern inserted!', 'success');
            });
        });
    });

    // ====================== MEDIA UPLOAD ======================
    const mediaUploadArea = document.getElementById('media-upload-area');
    const mediaFileInput = document.getElementById('media-file-input');
    const mediaPreviewList = document.getElementById('media-preview-list');

    if (mediaUploadArea) {
        mediaUploadArea.addEventListener('click', () => mediaFileInput.click());
        mediaUploadArea.addEventListener('dragover', e => { e.preventDefault(); mediaUploadArea.style.borderColor = '#007cba'; });
        mediaUploadArea.addEventListener('dragleave', () => { mediaUploadArea.style.borderColor = '#ddd'; });
        mediaUploadArea.addEventListener('drop', e => {
            e.preventDefault();
            mediaUploadArea.style.borderColor = '#ddd';
            handleMediaFiles(e.dataTransfer.files);
        });
    }

    if (mediaFileInput) {
        mediaFileInput.addEventListener('change', () => handleMediaFiles(mediaFileInput.files));
    }

    function handleMediaFiles(files) {
        Array.from(files).forEach(file => {
            if (!file.type.startsWith('image/')) return;
            const fd = new FormData();
            fd.append('image', file);
            showToast('Uploading ' + file.name + '...', 'info');
            fetch('../upload_image.php', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success && data.file && data.file.url) {
                        const imgUrl = data.file.url;
                        const item = document.createElement('div');
                        item.className = 'media-preview-item';
                        item.innerHTML = `<img src="${imgUrl}" alt="${file.name}"><span>${file.name}</span>`;
                        item.addEventListener('click', () => {
                            editor.isReady.then(() => {
                                editor.blocks.insert('image', {
                                    file: { url: imgUrl },
                                    caption: file.name,
                                    withBorder: false,
                                    stretched: false,
                                    withBackground: false
                                });
                                showToast('Image inserted into editor!', 'success');
                            });
                        });
                        if (mediaPreviewList) mediaPreviewList.appendChild(item);
                        showToast('Uploaded: ' + file.name, 'success');
                    } else {
                        showToast('Upload failed for ' + file.name, 'error');
                    }
                })
                .catch(() => showToast('Upload error', 'error'));
        });
    }

    // ====================== FEATURED IMAGE ======================
    let featuredImageUrl = <?= ($editPost && !empty($editPost['image_url'])) ? json_encode($editPost['image_url']) : "''" ?>;
    const featuredInput = document.getElementById('featured-image-input');
    const featuredPreview = document.getElementById('featured-image-preview');
    const featuredImgTag = document.getElementById('featured-img-tag');
    const removeFeaturedBtn = document.getElementById('remove-featured-img');

    if (featuredImageUrl) {
        featuredImgTag.src = featuredImageUrl;
        featuredPreview.style.display = 'block';
    }

    if (featuredInput) {
        featuredInput.addEventListener('change', () => {
            const file = featuredInput.files[0];
            if (!file) return;
            showToast('Uploading featured image...', 'info');
            const fd = new FormData();
            fd.append('image', file);
            fetch('../upload_image.php', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success && data.file && data.file.url) {
                        featuredImageUrl = data.file.url;
                        featuredImgTag.src = featuredImageUrl;
                        featuredPreview.style.display = 'block';
                        showToast('Featured image uploaded!', 'success');
                    } else {
                        showToast('Upload failed: ' + (data.message || 'Error'), 'error');
                    }
                })
                .catch(err => {
                    console.error('Featured image upload error:', err);
                    showToast('Upload error', 'error');
                });
        });
    }

    if (removeFeaturedBtn) {
        removeFeaturedBtn.addEventListener('click', () => {
            featuredImageUrl = '';
            featuredImgTag.src = '';
            featuredPreview.style.display = 'none';
            featuredInput.value = '';
        });
    }

    // ====================== SAVE DRAFT ======================
    document.getElementById('save-draft-btn').addEventListener('click', () => {
        savePost(false);
    });

    // ====================== PUBLISH ======================
    document.getElementById('save-button').addEventListener('click', () => {
        savePost(true);
    });

    function savePost(publish) {
        const title = document.getElementById('post-title').value.trim();
        if (!title) {
            showToast('Please enter a title before saving.', 'error');
            document.getElementById('post-title').focus();
            return;
        }

        const btn = document.getElementById('save-button');
        btn.disabled = true;
        btn.textContent = 'Saving...';

        editor.save().then((outputData) => {
            const postType = document.getElementById('post-type') ? document.getElementById('post-type').value : 'blog';
            
            // If no featured image chosen in sidebar, auto-extract the first image from content
            let finalImageUrl = featuredImageUrl;
            if (!finalImageUrl && outputData && outputData.blocks) {
                for (const block of outputData.blocks) {
                    if (block.type === 'image' && block.data && block.data.file && block.data.file.url) {
                        finalImageUrl = block.data.file.url;
                        break;
                    } else if (block.type === 'gallery' && block.data && block.data.urls && block.data.urls[0]) {
                        finalImageUrl = block.data.urls[0];
                        break;
                    }
                }
            }

            const payload = {
                title: title,
                content: outputData,
                image_url: finalImageUrl,
                excerpt: document.getElementById('post-excerpt').value,
                status: publish ? 'published' : 'draft',
                edit_id: typeof _editId !== 'undefined' ? _editId : null,
                post_type: postType
            };

            fetch('save_post.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
            })
            .then(response => response.json())
            .then(data => {
                btn.disabled = false;
                btn.textContent = 'Publish';
                if (data.success) {
                    const destName = (postType === 'services') ? 'Service' : 'Blog Post';
                    const targetPage = (postType === 'services') ? '/services' : '/blog.php';
                    
                    if (publish) {
                        document.getElementById('post-status-badge').textContent = 'Published';
                        document.getElementById('post-status-badge').className = 'status-badge';
                        document.getElementById('post-status-badge').style.background = '#d1fae5';
                        document.getElementById('post-status-badge').style.color = '#065f46';
                        document.getElementById('status-text').textContent = 'Published';
                        
                        showToast('✓ ' + destName + ' published to ' + targetPage + '! Redirecting...', 'success');
                        
                        const redirectUrl = data.manage_url || (postType === 'services' ? '../manage_services.php' : '../manage_blogs.php');
                        setTimeout(() => { window.location.href = redirectUrl; }, 1400);
                    } else {
                        var statusText = document.getElementById('status-text');
                        if (statusText) statusText.textContent = 'Draft';
                        var badge = document.getElementById('post-status-badge');
                        if (badge) { badge.textContent = 'Draft'; badge.style.background = '#fff3cd'; badge.style.color = '#856404'; }
                        showAutosaveStatus('Saved as Draft');
                        showToast('✓ ' + destName + ' saved as Draft!', 'success');
                    }
                } else {
                    showToast('Error: ' + (data.message || 'Save failed'), 'error');
                }
            })
            .catch((error) => {
                btn.disabled = false;
                btn.textContent = 'Publish';
                console.error('Error:', error);
                showToast('Connection error. Please try again.', 'error');
            });

        }).catch((error) => {
            btn.disabled = false;
            btn.textContent = 'Publish';
            console.error('Saving failed:', error);
            showToast('Editor error. Please try again.', 'error');
        });
    }

    // Global Post Type Synchronization
    window.syncPostType = function(val) {
        const headerSelect = document.getElementById('post-type');
        if (headerSelect) headerSelect.value = val;
        const radioBlog = document.getElementById('type_blog');
        const radioServ = document.getElementById('type_services');
        if (val === 'services') {
            if (radioServ) radioServ.checked = true;
            if (radioBlog) radioBlog.checked = false;
            showToast('Target set to: Services Post (/services)', 'info');
        } else {
            if (radioBlog) radioBlog.checked = true;
            if (radioServ) radioServ.checked = false;
            showToast('Target set to: Blog Post (/blog.php)', 'info');
        }
    };

    // Keyboard shortcut: Ctrl+S to save draft
    document.addEventListener('keydown', e => {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            savePost(false);
        }
    });
})();
</script>

<!-- ====== MEDIA LIBRARY MODAL ====== -->
<div class="ml-overlay" id="mlOverlay">
  <div class="ml-modal">
    <div class="ml-header">
      <h5><i class="fas fa-images me-2"></i>Media Library — Select an Image</h5>
      <button class="ml-close" onclick="closeMediaLibrary()">&#x2715;</button>
    </div>
    <div class="ml-toolbar">
      <label class="ml-upload-btn">
        <input type="file" id="mlUploadInput" accept="image/*" style="display:none;" onchange="mlUploadFile(this)">
        <i class="fas fa-upload"></i> Upload New
      </label>
      <span id="mlUploadStatus" style="font-size:12px;color:#555;margin-left:4px;"></span>
      <input type="text" class="ml-search" id="mlSearch" placeholder="Search images…" oninput="mlFilter(this.value)">
    </div>
    <div class="ml-body">
      <div class="ml-grid" id="mlGrid">
        <div class="ml-empty"><i class="fas fa-spinner fa-spin"></i> Loading…</div>
      </div>
    </div>
    <div class="ml-footer">
      <span class="ml-selected-info" id="mlSelectedInfo">No image selected</span>
      <div class="ml-footer-btns">
        <button class="btn btn-sm btn-outline-secondary" onclick="closeMediaLibrary()">Cancel</button>
        <button class="btn btn-sm btn-primary" id="mlSelectBtn" onclick="mlConfirmSelect()" disabled>
          <i class="fas fa-check me-1"></i>Select Image
        </button>
      </div>
    </div>
  </div>
</div>

<script>
var _mlContext  = null;
var _mlCallback = null;
var _mlSelected = null;
var _mlImages   = [];

function openMediaLibrary(context, callback) {
    _mlContext  = context;
    _mlCallback = callback || null;
    _mlSelected = null;
    document.getElementById('mlSelectedInfo').textContent = 'No image selected';
    document.getElementById('mlSelectBtn').disabled = true;
    document.getElementById('mlSearch').value = '';
    document.getElementById('mlOverlay').classList.add('open');
    mlLoadImages();
}
function closeMediaLibrary() {
    document.getElementById('mlOverlay').classList.remove('open');
}
document.getElementById('mlOverlay').addEventListener('click', function(e) {
    if (e.target === this) closeMediaLibrary();
});
function mlLoadImages() {
    var grid = document.getElementById('mlGrid');
    grid.innerHTML = '<div class="ml-empty"><i class="fas fa-spinner fa-spin"></i> Loading…</div>';
    fetch('media_library.php')
        .then(function(r){ return r.json(); })
        .then(function(data){
            _mlImages = data.images || [];
            mlRenderGrid(_mlImages);
        })
        .catch(function(){
            grid.innerHTML = '<div class="ml-empty"><i class="fas fa-exclamation-triangle"></i> Could not load images.</div>';
        });
}
function mlRenderGrid(images) {
    var grid = document.getElementById('mlGrid');
    if (!images.length) {
        grid.innerHTML = '<div class="ml-empty"><i class="fas fa-image"></i><br>No images yet. Use Upload New to add.</div>';
        return;
    }
    grid.innerHTML = '';
    images.forEach(function(img) {
        var div = document.createElement('div');
        div.className = 'ml-item' + (_mlSelected === img.url ? ' selected' : '');
        div.dataset.url = img.url;
        div.innerHTML = '<img src="'+img.url+'" alt="'+img.name+'" loading="lazy"><div class="ml-item-name">'+img.name+'</div>';
        div.addEventListener('click', function(){ mlSelectItem(this, img.url, img.name); });
        grid.appendChild(div);
    });
}
function mlSelectItem(el, url, name) {
    document.querySelectorAll('.ml-item').forEach(function(i){ i.classList.remove('selected'); });
    el.classList.add('selected');
    _mlSelected = url;
    document.getElementById('mlSelectedInfo').textContent = name;
    document.getElementById('mlSelectBtn').disabled = false;
}
function mlFilter(q) {
    var filtered = _mlImages.filter(function(img){
        return img.name.toLowerCase().includes(q.toLowerCase());
    });
    mlRenderGrid(filtered);
}
function mlConfirmSelect() {
    if (!_mlSelected) return;
    if (_mlContext === 'featured') {
        featuredImageUrl = _mlSelected;
        document.getElementById('featured-img-tag').src = featuredImageUrl;
        document.getElementById('featured-image-preview').style.display = 'block';
    } else if (typeof _mlCallback === 'function') {
        _mlCallback(_mlSelected);
    }
    closeMediaLibrary();
}
function mlUploadFile(input) {
    if (!input.files || !input.files[0]) return;
    var status = document.getElementById('mlUploadStatus');
    status.textContent = 'Uploading…';
    var fd = new FormData();
    fd.append('image', input.files[0]);
    fetch('../upload_image.php', { method:'POST', body:fd })
        .then(function(r){ return r.json(); })
        .then(function(data){
            if (data.success) {
                status.textContent = '✓ Uploaded!';
                setTimeout(function(){ status.textContent=''; }, 2500);
                mlLoadImages();
            } else {
                status.textContent = '✗ Failed.';
            }
        })
        .catch(function(){ status.textContent = '✗ Error.'; });
    input.value = '';
}
window.openMediaLibrary = openMediaLibrary;
</script>

</body>
</html>
