<?php
require_once __DIR__ . '/bootstrap.php';

if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

$id = $_GET['id'] ?? null;
if (!$id) {
    die("Page ID required.");
}

$page = \Models\Page::find($id);
if (!$page) {
    die("Page not found.");
}

// Fetch media for Asset Manager
$mediaItems = \Models\Media::all();
$assetsJson = json_encode(array_map(function ($item) {
    return [
        'type' => strpos($item['mime_type'] ?? $item['mimetype'], 'image/') === 0 ? 'image' : 'file',
        'src' => '/uploads/' . $item['filename'],
        'name' => $item['filename'],
        'height' => 0,
        'width' => 0
    ];
}, $mediaItems));

// Handle Save Request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input && isset($input['html'])) {
        // We store the full HTML (+ styles) in the page content for rendering
        // And the GrapesJS state in grapes_data for future editing
        $seoTitle = $input['seo']['seo_title'] ?: $page['title'];
        $seoDescription = $input['seo']['seo_description'] ?? '';
        $ogImage = $input['seo']['og_image'] ?? '';

        $metaTags = "<title>" . htmlspecialchars($seoTitle) . "</title>\n";
        if ($seoDescription) {
            $metaTags .= "    <meta name=\"description\" content=\"" . htmlspecialchars($seoDescription) . "\">\n";
            $metaTags .= "    <meta property=\"og:description\" content=\"" . htmlspecialchars($seoDescription) . "\">\n";
        }
        $metaTags .= "    <meta property=\"og:title\" content=\"" . htmlspecialchars($seoTitle) . "\">\n";
        if ($ogImage) {
            $metaTags .= "    <meta property=\"og:image\" content=\"" . htmlspecialchars($ogImage) . "\">\n";
        }

        $full_content = "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" . $metaTags . "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css\">\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css\">\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css\">\n<style>" . ($input['css'] ?? '') . "</style>\n</head>\n<body>\n" . $input['html'] . "\n</body>\n</html>";

        $updateData = [
            'content' => $full_content,
            'grapes_data' => json_encode($input['components'] ?? [])
        ];

        // If publish flag is set, update status
        if (!empty($input['publish'])) {
            $updateData['status'] = 'published';
        }

        try {
            // Save SEO Meta Data
            if (isset($input['seo'])) {
                foreach ($input['seo'] as $key => $value) {
                    \Models\Meta::set($id, 'page', $key, $value);
                }
            }

            \Models\Page::update($id, $updateData);

            // Clear the cache for this page so frontend shows updated content
            $pageSlug = $page['slug'] ?? '';
            if ($pageSlug) {
                \Core\Cache::delete('page_' . $pageSlug);
            }

            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/debug_error.log', $e->getMessage() . "\n" . $e->getTraceAsString());
            header('Content-Type: application/json');
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Save failed: ' . $e->getMessage()]);
        }
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Visual Builder - <?= htmlspecialchars($page['title']) ?></title>
    <link rel="stylesheet" href="https://unpkg.com/grapesjs/dist/css/grapes.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
        }

        body,
        html {
            height: 100%;
            margin: 0;
            overflow: hidden;
            font-family: 'Inter', sans-serif;
            background: #0f172a;
        }

        /* Premium Dark Theme */
        .gjs-one-bg {
            background-color: #1e293b;
        }

        .gjs-two-bg {
            background-color: #334155;
        }

        .gjs-three-bg {
            background-color: #475569;
        }

        .gjs-four-color,
        .gjs-four-color-h:hover {
            color: #38bdf8;
        }

        /* Main Layout */
        .editor-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        /* Top Bar */
        .panel__top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 50px;
            padding: 0 15px;
            background: #1e293b;
            border-bottom: 1px solid #334155;
            flex-shrink: 0;
        }

        .panel__top-left,
        .panel__top-center,
        .panel__top-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .panel__top-center {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
        }

        /* Panel Containers */
        .editor-main {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .panel__left {
            width: 280px;
            background: #1e293b;
            border-right: 1px solid #334155;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .panel__left-header {
            padding: 12px 15px;
            font-weight: 600;
            color: #94a3b8;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid #334155;
        }

        #gjs {
            flex: 1;
            background: #0f172a;
            overflow: hidden;
        }

        .gjs-cv-canvas {
            background: #f1f5f9;
            width: 100%;
            height: 100%;
        }

        .gjs-frame-wrapper {
            background: #f1f5f9;
        }

        .panel__right {
            width: 320px;
            background: #1e293b;
            border-left: 1px solid #334155;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .panel__right-tabs {
            display: flex;
            background: #0f172a;
            border-bottom: 1px solid #334155;
            padding: 0 10px;
        }

        .panel__right-tab {
            flex: 1;
            padding: 15px 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            color: #94a3b8;
            cursor: pointer;
            border: none;
            background: transparent;
            font-size: 11px;
            font-weight: 500;
            transition: all 0.3s ease;
            position: relative;
            outline: none;
        }

        .panel__right-tab i {
            font-size: 14px;
        }

        .panel__right-tab:hover {
            color: #f1f5f9;
        }

        .panel__right-tab.active {
            color: #38bdf8;
        }

        .panel__right-tab.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 15%;
            right: 15%;
            height: 2px;
            background: #38bdf8;
            border-radius: 2px 2px 0 0;
        }

        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
            text-decoration: none;
        }

        .btn-ghost {
            background: transparent;
            color: #94a3b8;
        }

        .btn-ghost:hover {
            color: #f1f5f9;
            background: #334155;
        }

        .btn-primary {
            background: linear-gradient(135deg, #0ea5e9, #0284c7);
            color: white;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #38bdf8, #0ea5e9);
        }

        .btn-success {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            color: white;
        }

        .btn-success:hover {
            background: linear-gradient(135deg, #4ade80, #22c55e);
        }

        /* Device Buttons */
        .device-btns {
            display: flex;
            background: #334155;
            border-radius: 6px;
            padding: 3px;
        }

        .device-btn {
            padding: 6px 12px;
            border: none;
            background: transparent;
            color: #64748b;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .device-btn:hover {
            color: #f1f5f9;
        }

        .device-btn.active {
            background: #1e293b;
            color: #38bdf8;
        }

        /* Blocks - Polished UI */
        .gjs-blocks-c {
            display: flex;
            flex-wrap: wrap;
            padding: 0;
            gap: 0;
        }

        .gjs-block-category {
            width: 100%;
        }

        .gjs-block-category .gjs-title {
            background: #0f172a;
            padding: 10px 15px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #64748b;
            border-bottom: 1px solid #334155;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* SEO Settings Panel */
        .page-container {
            padding: 16px;
        }

        .settings-group {
            margin-bottom: 24px;
        }

        .settings-group-title {
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #38bdf8;
            margin-bottom: 16px;
            padding-bottom: 8px;
            border-bottom: 1px solid #334155;
        }

        .setting-item {
            margin-bottom: 16px;
        }

        .setting-label {
            display: block;
            font-size: 11px;
            font-weight: 500;
            color: #94a3b8;
            margin-bottom: 6px;
        }

        .setting-input {
            width: 100%;
            background: #1e293b;
            border: 1px solid #334155;
            border-radius: 4px;
            color: #f1f5f9;
            padding: 8px 10px;
            font-size: 12px;
            transition: border-color 0.2s;
            outline: none;
        }

        .setting-input:focus {
            border-color: #38bdf8;
        }

        .setting-input::placeholder {
            color: #475569;
        }

        textarea.setting-input {
            resize: vertical;
            min-height: 80px;
        }

        .gjs-block-category .gjs-title:hover {
            color: #94a3b8;
        }

        .gjs-block-category .gjs-caret-icon {
            font-size: 10px;
            transition: transform 0.2s;
        }

        .gjs-blocks-c .gjs-block {
            width: calc(50% - 6px);
            margin: 3px;
            padding: 16px 8px;
            min-height: 75px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: linear-gradient(145deg, #1e293b, #0f172a);
            border-radius: 10px;
            border: 1px solid #334155;
            cursor: grab;
            transition: all 0.25s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        .gjs-blocks-c .gjs-block:hover {
            border-color: #38bdf8;
            background: linear-gradient(145deg, #334155, #1e293b);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(56, 189, 248, 0.15);
        }

        .gjs-blocks-c .gjs-block:active {
            transform: scale(0.98);
        }

        .gjs-block__media {
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #334155, #1e293b);
            border-radius: 8px;
            margin-bottom: 8px;
        }

        .gjs-block__media i,
        .gjs-block i {
            font-size: 16px;
            color: #64748b;
            transition: color 0.2s;
        }

        .gjs-block:hover .gjs-block__media i,
        .gjs-block:hover i {
            color: #38bdf8;
        }

        .gjs-block-label {
            font-size: 10px;
            font-weight: 500;
            margin-top: 6px;
            color: #94a3b8;
            text-align: center;
            line-height: 1.2;
        }

        .gjs-block:hover .gjs-block-label {
            color: #f1f5f9;
        }

        /* Category colors */
        .gjs-block-category[data-category="Atoms"] .gjs-title::before {
            content: "⚛️";
        }

        .gjs-block-category[data-category="Molecules"] .gjs-title::before {
            content: "🧬";
        }

        .gjs-block-category[data-category="Organisms"] .gjs-title::before {
            content: "🏗️";
        }

        .gjs-block-category[data-category="Layout"] .gjs-title::before {
            content: "📐";
        }

        /* Style Manager */
        .gjs-sm-sector {
            border-bottom: 1px solid #334155;
        }

        .gjs-sm-sector-title {
            padding: 12px 15px;
            background: #1e293b;
            color: #94a3b8;
            font-weight: 600;
            font-size: 12px;
        }

        .gjs-sm-properties {
            padding: 10px 15px;
            background: #1e293b;
        }

        .gjs-field {
            background: #334155;
            border: 1px solid #475569;
            border-radius: 4px;
        }

        .gjs-field input {
            color: #f1f5f9;
        }

        /* Layers - Enhanced with Add Button */
        .gjs-layers {
            padding: 0;
        }

        .gjs-layer {
            background: #1e293b;
            border-bottom: 1px solid #334155;
            position: relative;
            transition: all 0.2s;
        }

        .gjs-layer:hover {
            background: #334155;
        }

        .gjs-layer__title {
            color: #94a3b8;
            padding: 10px 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .gjs-layer:hover .gjs-layer__title {
            color: #f1f5f9;
        }

        /* Layer Action Buttons Container */
        .layer-actions {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
            gap: 6px;
        }

        /* Only show on selected layer */
        .gjs-layer.gjs-layer--selected .layer-actions,
        .gjs-layer.gjs-selected .layer-actions,
        .gjs-layer[class*="selected"] .layer-actions {
            display: flex;
        }

        .layer-action-btn {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            color: white;
        }

        .layer-action-btn.add-btn {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            box-shadow: 0 2px 6px rgba(34, 197, 94, 0.4);
        }

        .layer-action-btn.add-btn:hover {
            transform: scale(1.15);
            box-shadow: 0 4px 12px rgba(34, 197, 94, 0.5);
        }

        .layer-action-btn.duplicate-btn {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            box-shadow: 0 2px 6px rgba(59, 130, 246, 0.4);
        }

        .layer-action-btn.duplicate-btn:hover {
            transform: scale(1.15);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.5);
        }

        .layer-action-btn.delete-btn {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            box-shadow: 0 2px 6px rgba(239, 68, 68, 0.4);
        }

        .layer-action-btn.delete-btn:hover {
            transform: scale(1.15);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.5);
        }

        .gjs-layer-title {
            color: #94a3b8;
        }

        .gjs-layer-name {
            font-size: 12px;
        }

        .gjs-layer-count {
            color: #64748b;
            font-size: 10px;
        }

        .gjs-layer-caret {
            color: #64748b;
        }

        /* Page Title */
        .page-title {
            color: #f1f5f9;
            font-size: 14px;
        }

        .page-title span {
            color: #64748b;
            font-weight: 400;
        }

        /* Status indicator */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
        }

        .status-badge.draft {
            background: #fef3c7;
            color: #92400e;
        }

        .status-badge.published {
            background: #dcfce7;
            color: #166534;
        }

        /* Toast */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 20px;
            background: #22c55e;
            color: white;
            border-radius: 8px;
            font-weight: 500;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s;
            z-index: 9999;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast.error {
            background: #ef4444;
        }
    </style>
</head>

<body>

    <div class="editor-container">
        <!-- Top Bar -->
        <div class="panel__top">
            <div class="panel__top-left">
                <a href="pages.php?action=edit&id=<?= $id ?>" class="btn btn-ghost">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <div class="page-title">
                    <span>Editing:</span> <?= htmlspecialchars($page['title']) ?>
                </div>
                <span class="status-badge <?= $page['status'] ?>"><?= ucfirst($page['status']) ?></span>
            </div>

            <div class="panel__top-center">
                <div class="device-btns">
                    <button class="device-btn active" id="device-desktop" title="Desktop">
                        <i class="fas fa-desktop"></i>
                    </button>
                    <button class="device-btn" id="device-tablet" title="Tablet">
                        <i class="fas fa-tablet-alt"></i>
                    </button>
                    <button class="device-btn" id="device-mobile" title="Mobile">
                        <i class="fas fa-mobile-alt"></i>
                    </button>
                </div>
            </div>

            <div class="panel__top-right">
                <a href="/<?= htmlspecialchars($page['slug']) ?>" target="_blank" class="btn btn-ghost">
                    <i class="fas fa-external-link-alt"></i> Preview
                </a>
                <button id="save-btn" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Draft
                </button>
                <button id="publish-btn" class="btn btn-success">
                    <i class="fas fa-rocket"></i> Publish
                </button>
            </div>
        </div>

        <!-- Main Editor Area -->
        <div class="editor-main">
            <!-- Left Panel: Blocks -->
            <div class="panel__left">
                <div class="panel__left-header">
                    <i class="fas fa-shapes"></i> Blocks
                </div>
                <div id="blocks"></div>
            </div>

            <!-- Center: Canvas -->
            <div id="gjs"></div>

            <!-- Right Panel: Styles -->
            <div class="panel__right">
                <div class="panel__right-tabs">
                    <button class="panel__right-tab active" data-panel="styles">
                        <i class="fas fa-paint-brush"></i> Styles
                    </button>
                    <button class="panel__right-tab" data-panel="settings">
                        <i class="fas fa-cog"></i> Settings
                    </button>
                    <button class="panel__right-tab" data-panel="layers">
                        <i class="fas fa-layer-group"></i> Layers
                    </button>
                    <button class="panel__right-tab" data-panel="page">
                        <i class="fas fa-file-alt"></i> Page
                    </button>
                </div>
                <div class="styles-container"></div>
                <div class="traits-container" style="display:none"></div>
                <div class="layers-container" style="display:none"></div>
                <div class="page-container" style="display:none">
                    <div class="settings-group">
                        <div class="settings-group-title">SEO Settings</div>
                        <div class="setting-item">
                            <label class="setting-label">SEO Title</label>
                            <input type="text" id="seo_title" class="setting-input"
                                placeholder="Page Title for Search Engines"
                                value="<?= htmlspecialchars(\Models\Meta::get($id, 'page', 'seo_title') ?? '') ?>">
                        </div>
                        <div class="setting-item">
                            <label class="setting-label">SEO Description</label>
                            <textarea id="seo_description" class="setting-input"
                                placeholder="Meta description for search engines..."
                                rows="4"><?= htmlspecialchars(\Models\Meta::get($id, 'page', 'seo_description') ?? '') ?></textarea>
                        </div>
                        <div class="setting-item">
                            <label class="setting-label">Social Share Image (OG Image)</label>
                            <div class="og-image-preview-container">
                                <?php $ogImage = \Models\Meta::get($id, 'page', 'og_image'); ?>
                                <img id="og_image_preview"
                                    src="<?= $ogImage ?: 'https://placehold.co/600x315?text=Social+Share+Image' ?>"
                                    style="width: 100%; border-radius: 4px; margin-bottom: 8px; border: 1px solid #334155;">
                                <input type="hidden" id="og_image" value="<?= $ogImage ?? '' ?>">
                                <button class="btn btn-ghost" style="width: 100%;" onclick="openSEOAssetManager()">
                                    <i class="fas fa-image"></i> Choose Social Image
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="toast" id="toast"></div>

    <script src="https://unpkg.com/grapesjs"></script>
    <script>
        // Toast notification
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type + ' show';
            setTimeout(() => toast.classList.remove('show'), 3000);
        }

        // Initialize GrapesJS
        const editor = grapesjs.init({
            container: '#gjs',
            fromElement: false,
            height: '100%',
            width: 'auto',
            storageManager: false,
            deviceManager: {
                devices: [
                    { name: 'Desktop', width: '' },
                    { name: 'Tablet', width: '768px', widthMedia: '992px' },
                    { name: 'Mobile', width: '375px', widthMedia: '480px' }
                ]
            },
            canvas: {
                styles: [
                    'https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css',
                    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
                    'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css'
                ]
            },
            assetManager: {
                assets: <?= $assetsJson ?>,
                upload: '/admin/media.php',
                uploadName: 'file',
                headers: {},
                autoAdd: true,
                showUrlInput: true,
                embedAsBase64: false
            },
            blockManager: {
                appendTo: '#blocks',
                blocks: [
                    // ═══════════════════════════════════════
                    // ATOMS - Basic building blocks
                    // ═══════════════════════════════════════
                    {
                        id: 'text',
                        label: '<div class="gjs-block__media"><i class="fas fa-font"></i></div><div class="gjs-block-label">Text</div>',
                        category: 'Atoms',
                        content: '<p data-gjs-type="text" style="margin: 0; padding: 8px;">Insert your text here</p>',
                    },
                    {
                        id: 'heading-h1',
                        label: '<div class="gjs-block__media"><i class="fas fa-heading"></i></div><div class="gjs-block-label">Heading H1</div>',
                        category: 'Atoms',
                        content: '<h1 style="font-size: 48px; font-weight: 700; margin: 0;">Heading</h1>',
                    },
                    {
                        id: 'heading-h2',
                        label: '<div class="gjs-block__media"><i class="fas fa-h"></i></div><div class="gjs-block-label">Heading H2</div>',
                        category: 'Atoms',
                        content: '<h2 style="font-size: 36px; font-weight: 600; margin: 0;">Subheading</h2>',
                    },
                    {
                        id: 'image',
                        label: '<div class="gjs-block__media"><i class="fas fa-image"></i></div><div class="gjs-block-label">Image</div>',
                        category: 'Atoms',
                        content: { type: 'image' },
                    },
                    {
                        id: 'button',
                        label: '<div class="gjs-block__media"><i class="fas fa-square"></i></div><div class="gjs-block-label">Button</div>',
                        category: 'Atoms',
                        content: '<a href="#" class="button is-primary is-rounded has-shadow-primary">Get Started</a>',
                    },
                    {
                        id: 'link',
                        label: '<div class="gjs-block__media"><i class="fas fa-link"></i></div><div class="gjs-block-label">Link</div>',
                        category: 'Atoms',
                        content: '<a href="#" style="color: #0284c7; text-decoration: none; font-weight: 500;">Link text →</a>',
                    },
                    {
                        id: 'icon',
                        label: '<div class="gjs-block__media"><i class="fas fa-star"></i></div><div class="gjs-block-label">Icon</div>',
                        category: 'Atoms',
                        content: '<i class="fas fa-star" style="font-size: 24px; color: #0284c7;"></i>',
                    },
                    {
                        id: 'divider',
                        label: '<div class="gjs-block__media"><i class="fas fa-minus"></i></div><div class="gjs-block-label">Divider</div>',
                        category: 'Atoms',
                        content: '<hr style="border: none; height: 1px; background: linear-gradient(90deg, transparent, #e2e8f0, transparent); margin: 30px 0;">',
                    },
                    {
                        id: 'spacer',
                        label: '<div class="gjs-block__media"><i class="fas fa-arrows-alt-v"></i></div><div class="gjs-block-label">Spacer</div>',
                        category: 'Atoms',
                        content: '<div style="height: 60px;"></div>',
                    },
                    {
                        id: 'badge',
                        label: '<div class="gjs-block__media"><i class="fas fa-tag"></i></div><div class="gjs-block-label">Badge</div>',
                        category: 'Atoms',
                        content: '<span class="tag is-info is-light is-rounded has-text-weight-bold">New</span>',
                    },
                    {
                        id: 'avatar',
                        label: '<div class="gjs-block__media"><i class="fas fa-user-circle"></i></div><div class="gjs-block-label">Avatar</div>',
                        category: 'Atoms',
                        content: '<div style="width: 48px; height: 48px; background: linear-gradient(135deg, #0ea5e9, #6366f1); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 600; font-size: 18px;">JD</div>',
                    },
                    {
                        id: 'progress-bar',
                        label: '<div class="gjs-block__media"><i class="fas fa-battery-half"></i></div><div class="gjs-block-label">Progress Bar</div>',
                        category: 'Atoms',
                        content: '<progress class="progress is-primary is-small" value="65" max="100">65%</progress>',
                    },
                    {
                        id: 'list-item',
                        label: '<div class="gjs-block__media"><i class="fas fa-list-ul"></i></div><div class="gjs-block-label">List Item</div>',
                        category: 'Atoms',
                        content: `<div style="display: flex; align-items: center; gap: 12px; padding: 12px 0;">
                            <i class="fas fa-check-circle" style="color: #22c55e; font-size: 18px;"></i>
                            <span style="font-size: 15px; color: #334155;">List item text here</span>
                        </div>`,
                    },
                    {
                        id: 'nav-menu',
                        label: '<div class="gjs-block__media"><i class="fas fa-ellipsis-h"></i></div><div class="gjs-block-label">Nav Menu</div>',
                        category: 'Atoms',
                        content: `<nav class="is-flex is-align-items-center" style="gap: 1.5rem;">
                            <a href="#" class="has-text-dark has-text-weight-semibold" style="border-bottom: 2px solid #0284c7; padding-bottom: 4px;">Home</a>
                            <a href="#" class="has-text-grey">Features</a>
                            <a href="#" class="has-text-grey">Pricing</a>
                            <a href="#" class="has-text-grey">About</a>
                            <a href="#" class="has-text-grey">Contact</a>
                        </nav>`,
                    },
                    {
                        id: 'rating-stars',
                        label: '<div class="gjs-block__media"><i class="fas fa-star-half-alt"></i></div><div class="gjs-block-label">Rating Stars</div>',
                        category: 'Atoms',
                        content: `<div class="is-flex" style="gap: 0.25rem;">
                            <i class="fas fa-star has-text-warning"></i>
                            <i class="fas fa-star has-text-warning"></i>
                            <i class="fas fa-star has-text-warning"></i>
                            <i class="fas fa-star has-text-warning"></i>
                            <i class="fas fa-star-half-alt has-text-warning"></i>
                        </div>`,
                    },
                    // ═══════════════════════════════════════
                    // MOLECULES - Combinations of atoms
                    // ═══════════════════════════════════════
                    {
                        id: 'card',
                        label: '<div class="gjs-block__media"><i class="fas fa-id-card"></i></div><div class="gjs-block-label">Card</div>',
                        category: 'Molecules',
                        content: `<div style="background: white; border-radius: 16px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); border: 1px solid #f1f5f9;">
                            <h3 style="font-size: 20px; font-weight: 600; margin: 0 0 12px 0;">Card Title</h3>
                            <p style="color: #64748b; font-size: 14px; line-height: 1.6; margin: 0;">Card description goes here. Add more details about this item.</p>
                        </div>`,
                    },
                    {
                        id: 'image-card',
                        label: '<div class="gjs-block__media"><i class="fas fa-portrait"></i></div><div class="gjs-block-label">Image Card</div>',
                        category: 'Molecules',
                        content: `<div class="card shadow-sm" style="border-radius: 16px; overflow: hidden;">
                            <div class="card-image">
                                <figure class="image is-4by2">
                                    <img src="https://placehold.co/400x200/e2e8f0/64748b?text=Image" alt="Placeholder">
                                </figure>
                            </div>
                            <div class="card-content p-4">
                                <h3 class="title is-5 mb-2">Card Title</h3>
                                <p class="subtitle is-6 has-text-grey">Brief description here.</p>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'feature-item',
                        label: '<div class="gjs-block__media"><i class="fas fa-check-circle"></i></div><div class="gjs-block-label">Feature Item</div>',
                        category: 'Molecules',
                        content: `<div class="media">
                            <div class="media-left">
                                <div class="has-background-info-light is-flex is-align-items-center is-justify-content-center" style="width: 48px; height: 48px; border-radius: 12px;">
                                    <i class="fas fa-check has-text-info is-size-5"></i>
                                </div>
                            </div>
                            <div class="media-content">
                                <h4 class="title is-6 mb-1">Feature Title</h4>
                                <p class="is-size-7 has-text-grey">Describe your feature or benefit here.</p>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'testimonial',
                        label: '<div class="gjs-block__media"><i class="fas fa-quote-left"></i></div><div class="gjs-block-label">Testimonial</div>',
                        category: 'Molecules',
                        content: `<div class="box p-5 has-background-white-bis shadow-sm" style="border-radius: 16px; position: relative;">
                            <i class="fas fa-quote-left has-text-grey-lighter" style="position: absolute; top: 1.5rem; left: 1.5rem; font-size: 1.5rem;"></i>
                            <div style="padding-left: 2.5rem;">
                                <p class="is-size-6 italic has-text-dark mb-4">"Amazing product! It has completely transformed the way we work."</p>
                                <div class="media is-vcentered">
                                    <div class="media-left">
                                        <figure class="image is-40x48">
                                            <div class="is-rounded" style="width: 40px; height: 40px; background: #0284c7; border-radius: 50%;"></div>
                                        </figure>
                                    </div>
                                    <div class="media-content">
                                        <p class="is-size-7 has-text-weight-bold">John Doe</p>
                                        <p class="is-size-7 has-text-grey">CEO, Company</p>
                                    </div>
                                </div>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'stat-item',
                        label: '<div class="gjs-block__media"><i class="fas fa-chart-bar"></i></div><div class="gjs-block-label">Stat Item</div>',
                        category: 'Molecules',
                        content: `<div class="has-text-centered p-4">
                            <div class="title is-1 has-text-primary mb-2">99%</div>
                            <div class="subtitle is-6 has-text-grey">Customer Satisfaction</div>
                        </div>`,
                    },
                    {
                        id: 'cta-button-group',
                        label: '<div class="gjs-block__media"><i class="fas fa-layer-group"></i></div><div class="gjs-block-label">Button Group</div>',
                        category: 'Molecules',
                        content: `<div class="buttons">
                            <a href="#" class="button is-primary is-medium">Get Started</a>
                            <a href="#" class="button is-primary is-outlined is-medium">Learn More</a>
                        </div>`,
                    },
                    {
                        id: 'search-bar',
                        label: '<div class="gjs-block__media"><i class="fas fa-search"></i></div><div class="gjs-block-label">Search Bar</div>',
                        category: 'Molecules',
                        content: `<div class="field has-addons" style="max-width: 500px;">
                            <div class="control is-expanded">
                                <input class="input is-medium" type="text" placeholder="Search...">
                            </div>
                            <div class="control">
                                <button class="button is-primary is-medium">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'newsletter',
                        label: '<div class="gjs-block__media"><i class="fas fa-paper-plane"></i></div><div class="gjs-block-label">Newsletter</div>',
                        category: 'Molecules',
                        content: `<div class="box p-5 has-background-white-bis has-text-centered shadow-sm" style="border-radius: 20px;">
                            <h3 class="title is-4 mb-2">Subscribe to our Newsletter</h3>
                            <p class="subtitle is-6 has-text-grey mb-5">Get the latest updates straight to your inbox.</p>
                            <div class="field has-addons is-justify-content-center">
                                <div class="control" style="width: 100%; max-width: 300px;">
                                    <input class="input" type="email" placeholder="Enter your email">
                                </div>
                                <div class="control">
                                    <button class="button is-primary">Subscribe</button>
                                </div>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'social-links',
                        label: '<div class="gjs-block__media"><i class="fab fa-twitter"></i></div><div class="gjs-block-label">Social Links</div>',
                        category: 'Molecules',
                        content: `<div class="buttons">
                            <a class="button is-info is-rounded" style="background-color: #1da1f2 !important;"><i class="fab fa-twitter"></i></a>
                            <a class="button is-link is-rounded" style="background-color: #3b5998 !important;"><i class="fab fa-facebook-f"></i></a>
                            <a class="button is-danger is-rounded" style="background: linear-gradient(45deg, #f09433, #e6683c, #dc2743, #cc2366, #bc1888) !important;"><i class="fab fa-instagram"></i></a>
                            <a class="button is-info is-rounded" style="background-color: #0077b5 !important;"><i class="fab fa-linkedin-in"></i></a>
                            <a class="button is-dark is-rounded"><i class="fab fa-github"></i></a>
                        </div>`,
                    },
                    {
                        id: 'video-embed',
                        label: '<div class="gjs-block__media"><i class="fas fa-play-circle"></i></div><div class="gjs-block-label">Video Embed</div>',
                        category: 'Molecules',
                        content: `<div class="box p-0 has-background-dark shadow-lg" style="border-radius: 16px; overflow: hidden;">
                            <figure class="image is-16by9">
                                <div class="is-flex is-align-items-center is-justify-content-center" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;">
                                    <div class="has-text-centered">
                                        <div class="button is-white is-outlined is-large is-rounded mb-4" style="width: 80px; height: 80px; border-width: 2px;">
                                            <i class="fas fa-play ml-1"></i>
                                        </div>
                                        <p class="has-text-grey-light is-size-7">Click to play video</p>
                                    </div>
                                </div>
                            </figure>
                        </div>`,
                    },
                    {
                        id: 'icon-box',
                        label: '<div class="gjs-block__media"><i class="fas fa-cube"></i></div><div class="gjs-block-label">Icon Box</div>',
                        category: 'Molecules',
                        content: `<div class="box has-text-centered p-6 shadow-sm border-hover" style="border-radius: 20px; transition: transform 0.3s;">
                            <div class="has-background-info-light is-inline-flex is-align-items-center is-justify-content-center mb-5" style="width: 64px; height: 64px; border-radius: 16px;">
                                <i class="fas fa-rocket has-text-info is-size-3"></i>
                            </div>
                            <h3 class="title is-5 mb-3">Feature Title</h3>
                            <p class="is-size-6 has-text-grey">Brief description of the feature goes here.</p>
                        </div>`,
                    },
                    {
                        id: 'author-bio',
                        label: '<div class="gjs-block__media"><i class="fas fa-user-edit"></i></div><div class="gjs-block-label">Author Bio</div>',
                        category: 'Molecules',
                        content: `<div class="box p-4 has-background-white-bis shadow-sm" style="border-radius: 12px;">
                            <div class="columns is-vcentered is-mobile">
                                <div class="column is-narrow">
                                    <figure class="image is-64x64">
                                        <div class="is-rounded" style="width: 64px; height: 64px; background: linear-gradient(135deg, #0ea5e9, #6366f1); border-radius: 50%;"></div>
                                    </figure>
                                </div>
                                <div class="column">
                                    <h4 class="title is-5 mb-1">John Doe</h4>
                                    <p class="is-size-7 has-text-grey-dark mb-1">Senior Developer at Company</p>
                                    <p class="is-size-7 has-text-grey italic">Passionate about building great products.</p>
                                </div>
                            </div>
                        </div>`,
                    },
                    // ═══════════════════════════════════════
                    // ORGANISMS - Complex components
                    // ═══════════════════════════════════════
                    {
                        id: 'hero-section',
                        label: '<div class="gjs-block__media"><i class="fas fa-flag"></i></div><div class="gjs-block-label">Hero Section</div>',
                        category: 'Organisms',
                        content: `<section class="section is-medium has-background-dark has-text-centered" style="background: linear-gradient(135deg, #0f172a, #1e293b) !important;">
                            <div class="container">
                                <div class="columns is-centered">
                                    <div class="column is-8-tablet is-10-mobile">
                                        <span class="tag is-info is-light is-rounded mb-5" style="background: rgba(56, 189, 248, 0.1); color: #38bdf8; font-weight: 600;">🚀 Now Available</span>
                                        <h1 class="title is-1 has-text-white mb-5 is-size-2-mobile">Build Something Amazing</h1>
                                        <p class="subtitle is-4 has-text-grey-light mb-6 is-size-5-mobile">Create stunning websites with our powerful visual builder. No coding required.</p>
                                        <div class="buttons is-centered">
                                            <a href="#" class="button is-primary is-medium px-6">Get Started Free</a>
                                            <a href="#" class="button is-white is-outlined is-medium px-6">Watch Demo →</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'features-grid',
                        label: '<div class="gjs-block__media"><i class="fas fa-grip"></i></div><div class="gjs-block-label">Features Grid</div>',
                        category: 'Organisms',
                        content: `<section class="section has-background-light">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Why Choose Us</h2>
                                <p class="subtitle is-5 has-text-centered mb-6 mx-auto" style="max-width: 600px;">Everything you need to build modern websites</p>
                                <div class="columns is-multiline">
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box has-text-centered h-100 p-6">
                                            <div class="icon is-large has-text-primary mb-4"><i class="fas fa-bolt fa-2x"></i></div>
                                            <h3 class="title is-4">Lightning Fast</h3>
                                            <p class="has-text-grey">Optimized for speed and performance.</p>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box has-text-centered h-100 p-6">
                                            <div class="icon is-large has-text-success mb-4"><i class="fas fa-shield-alt fa-2x"></i></div>
                                            <h3 class="title is-4">Secure</h3>
                                            <p class="has-text-grey">Enterprise-grade security built-in.</p>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box has-text-centered h-100 p-6">
                                            <div class="icon is-large has-text-warning mb-4"><i class="fas fa-palette fa-2x"></i></div>
                                            <h3 class="title is-4">Beautiful</h3>
                                            <p class="has-text-grey">Stunning designs out of the box.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'cta-section',
                        label: '<div class="gjs-block__media"><i class="fas fa-bullhorn"></i></div><div class="gjs-block-label">CTA Section</div>',
                        category: 'Organisms',
                        content: `<section class="section is-medium has-background-primary has-text-centered" style="background: linear-gradient(135deg, #0ea5e9, #6366f1) !important;">
                            <div class="container">
                                <div class="columns is-centered">
                                    <div class="column is-8-tablet">
                                        <h2 class="title is-2 has-text-white mb-4 is-size-3-mobile">Ready to Get Started?</h2>
                                        <p class="subtitle is-4 has-text-white mb-6" style="opacity: 0.9;">Join thousands of satisfied customers today.</p>
                                        <a href="#" class="button is-white is-large is-rounded px-6 py-4 shadow-lg">Start Free Trial</a>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'footer',
                        label: '<div class="gjs-block__media"><i class="fas fa-shoe-prints"></i></div><div class="gjs-block-label">Footer</div>',
                        category: 'Organisms',
                        content: `<footer class="footer has-background-dark has-text-white py-6">
                            <div class="container">
                                <div class="columns is-multiline">
                                    <div class="column is-full-mobile is-4-tablet">
                                        <h3 class="title is-4 has-text-white mb-4">Company</h3>
                                        <p class="has-text-grey-light">Building the future of web design.</p>
                                    </div>
                                    <div class="column is-6-mobile is-2-tablet">
                                        <h4 class="title is-6 has-text-grey-light mb-4">Product</h4>
                                        <ul class="is-size-7">
                                            <li class="mb-2"><a href="#" class="has-text-white">Features</a></li>
                                            <li class="mb-2"><a href="#" class="has-text-white">Pricing</a></li>
                                            <li class="mb-2"><a href="#" class="has-text-white">Templates</a></li>
                                        </ul>
                                    </div>
                                    <div class="column is-6-mobile is-2-tablet">
                                        <h4 class="title is-6 has-text-grey-light mb-4">Company</h4>
                                        <ul class="is-size-7">
                                            <li class="mb-2"><a href="#" class="has-text-white">About</a></li>
                                            <li class="mb-2"><a href="#" class="has-text-white">Blog</a></li>
                                            <li class="mb-2"><a href="#" class="has-text-white">Careers</a></li>
                                        </ul>
                                    </div>
                                    <div class="column is-full-mobile is-2-tablet">
                                        <h4 class="title is-6 has-text-grey-light mb-4">Legal</h4>
                                        <ul class="is-size-7">
                                            <li class="mb-2"><a href="#" class="has-text-white">Privacy</a></li>
                                            <li class="mb-2"><a href="#" class="has-text-white">Terms</a></li>
                                        </ul>
                                    </div>
                                </div>
                                <hr class="has-background-grey-dark my-5">
                                <div class="has-text-centered has-text-grey is-size-7">
                                    © 2024 Company. All rights reserved.
                                </div>
                            </div>
                        </footer>`,
                    },
                    {
                        id: 'navbar',
                        label: '<div class="gjs-block__media"><i class="fas fa-bars"></i></div><div class="gjs-block-label">Navbar</div>',
                        category: 'Organisms',
                        content: `<nav class="navbar is-white has-shadow is-spaced" role="navigation" aria-label="main navigation">
                            <div class="container">
                                <div class="navbar-brand">
                                    <a class="navbar-item" href="/">
                                        <strong class="is-size-4">Logo</strong>
                                    </a>
                                    <a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
                                        <span aria-hidden="true"></span>
                                        <span aria-hidden="true"></span>
                                        <span aria-hidden="true"></span>
                                    </a>
                                </div>
                                <div id="navbarBasicExample" class="navbar-menu">
                                    <div class="navbar-start ml-auto">
                                        <a class="navbar-item mx-2">Features</a>
                                        <a class="navbar-item mx-2">Pricing</a>
                                        <a class="navbar-item mx-2">About</a>
                                        <a class="navbar-item mx-2">Contact</a>
                                    </div>
                                    <div class="navbar-end ml-4">
                                        <div class="navbar-item">
                                            <div class="buttons">
                                                <a class="button is-light">Sign In</a>
                                                <a class="button is-primary"><strong>Get Started</strong></a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </nav>`,
                    },
                    {
                        id: 'pricing-section',
                        label: '<div class="gjs-block__media"><i class="fas fa-dollar-sign"></i></div><div class="gjs-block-label">Pricing</div>',
                        category: 'Organisms',
                        content: `<section class="section has-background-light">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Simple, Transparent Pricing</h2>
                                <p class="subtitle is-5 has-text-centered mb-6">Choose the plan that works for you</p>
                                <div class="columns is-multiline is-centered">
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box h-100 p-6">
                                            <h3 class="title is-4">Starter</h3>
                                            <div class="title is-1 my-5">$9<span class="is-size-5 has-text-grey">/mo</span></div>
                                            <p class="subtitle is-6 mb-5">Perfect for individuals</p>
                                            <ul class="mb-5">
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>5 Projects</li>
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>Basic Support</li>
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>1GB Storage</li>
                                            </ul>
                                            <a href="#" class="button is-primary is-outlined is-fullwidth">Get Started</a>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box h-100 p-6 has-background-primary has-text-white shadow-lg" style="transform: scale(1.05);">
                                            <span class="tag is-white is-rounded mb-4">POPULAR</span>
                                            <h3 class="title is-4 has-text-white">Pro</h3>
                                            <div class="title is-1 my-5 has-text-white">$29<span class="is-size-5" style="opacity: 0.8;">/mo</span></div>
                                            <p class="subtitle is-6 mb-5 has-text-white-ter">For growing teams</p>
                                            <ul class="mb-5">
                                                <li class="mb-2"><i class="fas fa-check mr-2"></i>Unlimited Projects</li>
                                                <li class="mb-2"><i class="fas fa-check mr-2"></i>Priority Support</li>
                                                <li class="mb-2"><i class="fas fa-check mr-2"></i>10GB Storage</li>
                                            </ul>
                                            <a href="#" class="button is-white is-fullwidth">Get Started</a>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="box h-100 p-6">
                                            <h3 class="title is-4">Enterprise</h3>
                                            <div class="title is-1 my-5">$99<span class="is-size-5 has-text-grey">/mo</span></div>
                                            <p class="subtitle is-6 mb-5">For large organizations</p>
                                            <ul class="mb-5">
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>Everything in Pro</li>
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>Dedicated Support</li>
                                                <li class="mb-2"><i class="fas fa-check has-text-success mr-2"></i>Unlimited Storage</li>
                                            </ul>
                                            <a href="#" class="button is-dark is-outlined is-fullwidth">Contact Sales</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'faq-section',
                        label: '<div class="gjs-block__media"><i class="fas fa-question-circle"></i></div><div class="gjs-block-label">FAQ</div>',
                        category: 'Organisms',
                        content: `<section class="section">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Frequently Asked Questions</h2>
                                <div class="columns is-centered">
                                    <div class="column is-8-tablet">
                                        <div class="content">
                                            <div class="box mb-4">
                                                <h3 class="title is-5 mb-2 is-flex is-justify-content-space-between is-clickable">How do I get started? <i class="fas fa-chevron-down has-text-grey-light"></i></h3>
                                                <p class="has-text-grey">Simply sign up for a free account and you can start building immediately. No credit card required.</p>
                                            </div>
                                            <div class="box mb-4">
                                                <h3 class="title is-5 mb-2 is-flex is-justify-content-space-between is-clickable">Can I cancel anytime? <i class="fas fa-chevron-down has-text-grey-light"></i></h3>
                                                <p class="has-text-grey">Yes, you can cancel your subscription at any time. No questions asked.</p>
                                            </div>
                                            <div class="box mb-4">
                                                <h3 class="title is-5 mb-2 is-flex is-justify-content-space-between is-clickable">Do you offer refunds? <i class="fas fa-chevron-down has-text-grey-light"></i></h3>
                                                <p class="has-text-grey">We offer a 30-day money-back guarantee if you're not satisfied.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'contact-form',
                        label: '<div class="gjs-block__media"><i class="fas fa-envelope"></i></div><div class="gjs-block-label">Contact Form</div>',
                        category: 'Organisms',
                        content: `<section class="section has-background-light">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-2">Get in Touch</h2>
                                <p class="subtitle is-5 has-text-centered mb-6 has-text-grey">We'd love to hear from you</p>
                                <div class="columns is-centered">
                                    <div class="column is-6-tablet">
                                        <form class="box p-6 shadow-lg">
                                            <div class="columns">
                                                <div class="column">
                                                    <div class="field">
                                                        <label class="label">First Name</label>
                                                        <div class="control">
                                                            <input class="input" type="text" placeholder="John">
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="column">
                                                    <div class="field">
                                                        <label class="label">Last Name</label>
                                                        <div class="control">
                                                            <input class="input" type="text" placeholder="Doe">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="field">
                                                <label class="label">Email</label>
                                                <div class="control">
                                                    <input class="input" type="email" placeholder="john@example.com">
                                                </div>
                                            </div>
                                            <div class="field">
                                                <label class="label">Message</label>
                                                <div class="control">
                                                    <textarea class="textarea" placeholder="Your message..." rows="4"></textarea>
                                                </div>
                                            </div>
                                            <div class="field mt-5">
                                                <div class="control">
                                                    <button type="submit" class="button is-primary is-fullwidth is-medium">Send Message</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'team-section',
                        label: '<div class="gjs-block__media"><i class="fas fa-users"></i></div><div class="gjs-block-label">Team Section</div>',
                        category: 'Organisms',
                        content: `<section class="section">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Meet Our Team</h2>
                                <p class="subtitle is-5 has-text-centered mb-6 mx-auto" style="max-width: 600px;">The people behind the product</p>
                                <div class="columns is-multiline is-centered">
                                    <div class="column is-full-mobile is-3-tablet">
                                        <div class="has-text-centered">
                                            <figure class="image is-128x128 mx-auto mb-4">
                                                <div class="is-rounded has-background-primary-light" style="width: 128px; height: 128px; background: linear-gradient(135deg, #0ea5e9, #6366f1); border-radius: 50%;"></div>
                                            </figure>
                                            <h3 class="title is-4 mb-1">John Doe</h3>
                                            <p class="subtitle is-6 has-text-grey">CEO & Founder</p>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-3-tablet">
                                        <div class="has-text-centered">
                                            <figure class="image is-128x128 mx-auto mb-4">
                                                <div class="is-rounded has-background-success-light" style="width: 128px; height: 128px; background: linear-gradient(135deg, #22c55e, #16a34a); border-radius: 50%;"></div>
                                            </figure>
                                            <h3 class="title is-4 mb-1">Jane Smith</h3>
                                            <p class="subtitle is-6 has-text-grey">CTO</p>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-3-tablet">
                                        <div class="has-text-centered">
                                            <figure class="image is-128x128 mx-auto mb-4">
                                                <div class="is-rounded has-background-warning-light" style="width: 128px; height: 128px; background: linear-gradient(135deg, #f59e0b, #d97706); border-radius: 50%;"></div>
                                            </figure>
                                            <h3 class="title is-4 mb-1">Mike Johnson</h3>
                                            <p class="subtitle is-6 has-text-grey">Lead Designer</p>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-3-tablet">
                                        <div class="has-text-centered">
                                            <figure class="image is-128x128 mx-auto mb-4">
                                                <div class="is-rounded has-background-danger-light" style="width: 128px; height: 128px; background: linear-gradient(135deg, #ec4899, #be185d); border-radius: 50%;"></div>
                                            </figure>
                                            <h3 class="title is-4 mb-1">Sarah Wilson</h3>
                                            <p class="subtitle is-6 has-text-grey">Marketing</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'gallery',
                        label: '<div class="gjs-block__media"><i class="fas fa-images"></i></div><div class="gjs-block-label">Gallery</div>',
                        category: 'Organisms',
                        content: `<section class="section">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Our Gallery</h2>
                                <div class="columns is-multiline is-mobile">
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #f1f5f9, #e2e8f0); border-radius: 12px;"></div>
                                    </div>
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #dbeafe, #bfdbfe); border-radius: 12px;"></div>
                                    </div>
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #dcfce7, #bbf7d0); border-radius: 12px;"></div>
                                    </div>
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #fef3c7, #fde68a); border-radius: 12px;"></div>
                                    </div>
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #fce7f3, #fbcfe8); border-radius: 12px;"></div>
                                    </div>
                                    <div class="column is-6-mobile is-4-tablet">
                                        <div class="box p-0 overflow-hidden shadow-sm" style="aspect-ratio: 1; background: linear-gradient(135deg, #e0e7ff, #c7d2fe); border-radius: 12px;"></div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'blog-posts',
                        label: '<div class="gjs-block__media"><i class="fas fa-newspaper"></i></div><div class="gjs-block-label">Blog Posts</div>',
                        category: 'Organisms',
                        content: `<section class="section">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Latest Articles</h2>
                                <p class="subtitle is-5 has-text-centered mb-6 mx-auto" style="max-width: 600px;">Stay updated with our latest news</p>
                                <div class="columns is-multiline">
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="card h-100 shadow-sm border-0 overflow-hidden" style="border-radius: 16px;">
                                            <div class="card-image">
                                                <figure class="image is-16by9 has-background-primary"></figure>
                                            </div>
                                            <div class="card-content p-5">
                                                <p class="is-size-7 has-text-grey mb-2">January 10, 2024</p>
                                                <h3 class="title is-5 mb-3">Getting Started with Visual Building</h3>
                                                <p class="has-text-grey mb-4">Learn how to create stunning websites...</p>
                                                <a href="#" class="has-text-primary has-text-weight-bold">Read More →</a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="card h-100 shadow-sm border-0 overflow-hidden" style="border-radius: 16px;">
                                            <div class="card-image">
                                                <figure class="image is-16by9 has-background-success"></figure>
                                            </div>
                                            <div class="card-content p-5">
                                                <p class="is-size-7 has-text-grey mb-2">January 8, 2024</p>
                                                <h3 class="title is-5 mb-3">Design Tips for Beginners</h3>
                                                <p class="has-text-grey mb-4">Master the art of web design...</p>
                                                <a href="#" class="has-text-primary has-text-weight-bold">Read More →</a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="column is-full-mobile is-4-tablet">
                                        <div class="card h-100 shadow-sm border-0 overflow-hidden" style="border-radius: 16px;">
                                            <div class="card-image">
                                                <figure class="image is-16by9 has-background-warning"></figure>
                                            </div>
                                            <div class="card-content p-5">
                                                <p class="is-size-7 has-text-grey mb-2">January 5, 2024</p>
                                                <h3 class="title is-5 mb-3">Best Practices for SEO</h3>
                                                <p class="has-text-grey mb-4">Optimize your pages for search...</p>
                                                <a href="#" class="has-text-primary has-text-weight-bold">Read More →</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'partner-logos',
                        label: '<div class="gjs-block__media"><i class="fas fa-handshake"></i></div><div class="gjs-block-label">Partners</div>',
                        category: 'Organisms',
                        content: `<section class="section has-background-light py-5">
                            <div class="container">
                                <div class="has-text-centered mb-5">
                                    <p class="is-size-7 has-text-grey-light is-uppercase has-text-weight-semibold" style="letter-spacing: 2px;">Trusted by leading companies</p>
                                </div>
                                <div class="columns is-vcentered is-centered is-mobile is-multiline is-variable is-8">
                                    <div class="column is-narrow">
                                        <div class="has-background-grey-lighter" style="width: 120px; height: 40px; border-radius: 8px; opacity: 0.5;"></div>
                                    </div>
                                    <div class="column is-narrow">
                                        <div class="has-background-grey-lighter" style="width: 120px; height: 40px; border-radius: 8px; opacity: 0.5;"></div>
                                    </div>
                                    <div class="column is-narrow">
                                        <div class="has-background-grey-lighter" style="width: 120px; height: 40px; border-radius: 8px; opacity: 0.5;"></div>
                                    </div>
                                    <div class="column is-narrow">
                                        <div class="has-background-grey-lighter" style="width: 120px; height: 40px; border-radius: 8px; opacity: 0.5;"></div>
                                    </div>
                                    <div class="column is-narrow">
                                        <div class="has-background-grey-lighter" style="width: 120px; height: 40px; border-radius: 8px; opacity: 0.5;"></div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'timeline',
                        label: '<div class="gjs-block__media"><i class="fas fa-stream"></i></div><div class="gjs-block-label">Timeline</div>',
                        category: 'Organisms',
                        content: `<section class="section">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered mb-6">Our Journey</h2>
                                <div class="columns is-centered">
                                    <div class="column is-8-tablet">
                                        <div style="position: relative; padding-left: 3rem; border-left: 3px solid #0ea5e9;">
                                            <div class="mb-6" style="position: relative;">
                                                <div style="position: absolute; left: -3.5rem; width: 1.5rem; height: 1.5rem; background: #0ea5e9; border-radius: 50%; border: 4px solid white; box-shadow: 0 0 0 2px #0ea5e9;"></div>
                                                <span class="is-size-7 has-text-primary has-text-weight-bold">2020</span>
                                                <h3 class="title is-5 mb-2 mt-1">Company Founded</h3>
                                                <p class="has-text-grey">Started with a vision to revolutionize web design.</p>
                                            </div>
                                            <div class="mb-6" style="position: relative;">
                                                <div style="position: absolute; left: -3.5rem; width: 1.5rem; height: 1.5rem; background: #22c55e; border-radius: 50%; border: 4px solid white; box-shadow: 0 0 0 2px #22c55e;"></div>
                                                <span class="is-size-7 has-text-success has-text-weight-bold">2021</span>
                                                <h3 class="title is-5 mb-2 mt-1">First Major Release</h3>
                                                <p class="has-text-grey">Launched our flagship product to great reception.</p>
                                            </div>
                                            <div class="mb-0" style="position: relative;">
                                                <div style="position: absolute; left: -3.5rem; width: 1.5rem; height: 1.5rem; background: #f59e0b; border-radius: 50%; border: 4px solid white; box-shadow: 0 0 0 2px #f59e0b;"></div>
                                                <span class="is-size-7 has-text-warning has-text-weight-bold">2023</span>
                                                <h3 class="title is-5 mb-2 mt-1">100K Users</h3>
                                                <p class="has-text-grey">Reached a milestone of 100,000 active users.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    {
                        id: 'testimonials-slider',
                        label: '<div class="gjs-block__media"><i class="fas fa-comments"></i></div><div class="gjs-block-label">Testimonials</div>',
                        category: 'Organisms',
                        content: `<section class="section is-medium has-background-dark py-6" style="background: linear-gradient(135deg, #0f172a, #1e293b) !important;">
                            <div class="container">
                                <h2 class="title is-2 has-text-centered has-text-white mb-6">What Our Customers Say</h2>
                                <div class="columns is-centered">
                                    <div class="column is-8-tablet">
                                        <div class="box has-background-white-bis p-6 shadow-lg has-text-centered" style="background: rgba(255,255,255,0.05) !important; border: 1px solid rgba(255,255,255,0.1);">
                                            <i class="fas fa-quote-left is-size-1 has-text-info mb-5" style="opacity: 0.5;"></i>
                                            <p class="title is-4 has-text-white has-text-weight-normal mb-6" style="line-height: 1.6;">"This product has completely transformed how we build websites. The intuitive interface and powerful features make it a joy to use every day."</p>
                                            <div class="is-flex is-align-items-center is-justify-content-center">
                                                <figure class="image is-48x48 mr-3">
                                                    <div class="is-rounded" style="width: 48px; height: 48px; background: linear-gradient(135deg, #0ea5e9, #6366f1); border-radius: 50%;"></div>
                                                </figure>
                                                <div class="has-text-left">
                                                    <p class="has-text-white has-text-weight-bold">Emily Chen</p>
                                                    <p class="has-text-grey-light is-size-7">Product Manager at TechCorp</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>`,
                    },
                    // ═══════════════════════════════════════
                    // LAYOUT - Structural elements
                    // ═══════════════════════════════════════
                    {
                        id: 'section',
                        label: '<div class="gjs-block__media"><i class="fas fa-square-full"></i></div><div class="gjs-block-label">Section</div>',
                        category: 'Layout',
                        content: '<section class="section"><div class="container" style="min-height: 100px;"></div></section>',
                    },
                    {
                        id: 'container',
                        label: '<div class="gjs-block__media"><i class="fas fa-box"></i></div><div class="gjs-block-label">Container</div>',
                        category: 'Layout',
                        content: '<div class="container py-4"></div>',
                    },
                    {
                        id: 'flex-row',
                        label: '<div class="gjs-block__media"><i class="fas fa-columns"></i></div><div class="gjs-block-label">Flex Row</div>',
                        category: 'Layout',
                        content: `<div class="columns is-multiline mb-4">
                            <div class="column is-full-mobile is-6-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 120px;">Column 1</div>
                            </div>
                            <div class="column is-full-mobile is-6-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 120px;">Column 2</div>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'grid-2col',
                        label: '<div class="gjs-block__media"><i class="fas fa-th-large"></i></div><div class="gjs-block-label">2 Columns</div>',
                        category: 'Layout',
                        content: `<div class="columns is-multiline py-4">
                            <div class="column is-full-mobile is-6-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 150px;">Left</div>
                            </div>
                            <div class="column is-full-mobile is-6-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 150px;">Right</div>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'grid-3col',
                        label: '<div class="gjs-block__media"><i class="fas fa-th"></i></div><div class="gjs-block-label">3 Columns</div>',
                        category: 'Layout',
                        content: `<div class="columns is-multiline py-4">
                            <div class="column is-full-mobile is-4-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 150px;">Col 1</div>
                            </div>
                            <div class="column is-full-mobile is-4-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 150px;">Col 2</div>
                            </div>
                            <div class="column is-full-mobile is-4-tablet">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 150px;">Col 3</div>
                            </div>
                        </div>`,
                    },
                    {
                        id: 'grid-4col',
                        label: '<div class="gjs-block__media"><i class="fas fa-grip"></i></div><div class="gjs-block-label">4 Columns</div>',
                        category: 'Layout',
                        content: `<div class="columns is-multiline py-4">
                            <div class="column is-full-mobile is-6-tablet is-3-desktop">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 100px;">1</div>
                            </div>
                            <div class="column is-full-mobile is-6-tablet is-3-desktop">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 100px;">2</div>
                            </div>
                            <div class="column is-full-mobile is-6-tablet is-3-desktop">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 100px;">3</div>
                            </div>
                            <div class="column is-full-mobile is-6-tablet is-3-desktop">
                                <div class="has-background-light p-4 rounded border-dashed" style="min-height: 100px;">4</div>
                            </div>
                        </div>`,
                    },
                ]
            },
            layerManager: {
                appendTo: '.layers-container'
            },
            selectorManager: {
                appendTo: '.styles-container',
            },
            styleManager: {
                appendTo: '.styles-container',
                sectors: [
                    {
                        name: 'Dimension',
                        open: true,
                        properties: [
                            { property: 'width' },
                            { property: 'height' },
                            { property: 'max-width' },
                            { property: 'min-height' },
                        ]
                    },
                    {
                        name: 'Spacing',
                        open: true,
                        properties: [
                            {
                                property: 'margin',
                                type: 'composite',
                                detached: true,
                                properties: [
                                    { name: 'Top', property: 'margin-top' },
                                    { name: 'Right', property: 'margin-right' },
                                    { name: 'Bottom', property: 'margin-bottom' },
                                    { name: 'Left', property: 'margin-left' }
                                ]
                            },
                            {
                                property: 'padding',
                                type: 'composite',
                                detached: true,
                                properties: [
                                    { name: 'Top', property: 'padding-top' },
                                    { name: 'Right', property: 'padding-right' },
                                    { name: 'Bottom', property: 'padding-bottom' },
                                    { name: 'Left', property: 'padding-left' }
                                ]
                            }
                        ]
                    },
                    {
                        name: 'Layout',
                        open: true,
                        buildProps: ['display', 'position', 'top', 'right', 'bottom', 'left', 'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-content', 'gap', 'grid-template-columns', 'grid-template-rows'],
                    },
                    {
                        name: 'Typography',
                        open: false,
                        buildProps: ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'color', 'line-height', 'text-align', 'text-decoration', 'text-transform', 'text-shadow'],
                    },
                    {
                        name: 'Background',
                        open: false,
                        buildProps: ['background-color', 'background-image', 'background-repeat', 'background-position', 'background-size'],
                    },
                    {
                        name: 'Border',
                        open: false,
                        buildProps: ['border', 'border-radius', 'border-width', 'border-style', 'border-color'],
                    },
                    {
                        name: 'Effects',
                        open: false,
                        buildProps: ['opacity', 'box-shadow', 'transition', 'transform', 'filter'],
                    },
                    {
                        name: 'Animation',
                        open: false,
                        properties: [
                            {
                                name: 'Animation Class',
                                property: 'class',
                                type: 'select',
                                options: [
                                    { value: '', name: 'None' },
                                    { value: 'animate__animated animate__fadeIn', name: 'Fade In' },
                                    { value: 'animate__animated animate__fadeInUp', name: 'Fade In Up' },
                                    { value: 'animate__animated animate__fadeInDown', name: 'Fade In Down' },
                                    { value: 'animate__animated animate__slideInLeft', name: 'Slide In Left' },
                                    { value: 'animate__animated animate__slideInRight', name: 'Slide In Right' },
                                    { value: 'animate__animated animate__bounce', name: 'Bounce' },
                                    { value: 'animate__animated animate__pulse', name: 'Pulse' },
                                ]
                            }
                        ]
                    },
                ],
            },
            traitManager: {
                appendTo: '.traits-container',
            },
            panels: { defaults: [] }
        });

        // Device Switching
        document.querySelectorAll('.device-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.device-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');

                if (btn.id === 'device-desktop') editor.setDevice('Desktop');
                else if (btn.id === 'device-tablet') editor.setDevice('Tablet');
                else if (btn.id === 'device-mobile') editor.setDevice('Mobile');
            });
        });

        // ========================================
        // Image Component Type - Extend with src trait and proper asset handling
        // ========================================
        editor.DomComponents.addType('image', {
            model: {
                defaults: {
                    tagName: 'img',
                    resizable: true,
                    droppable: false,
                    traits: [
                        {
                            type: 'text',
                            name: 'src',
                            label: 'Image URL',
                            placeholder: 'https://...'
                        },
                        {
                            type: 'text',
                            name: 'alt',
                            label: 'Alt Text',
                            placeholder: 'Image description'
                        },
                        {
                            type: 'text',
                            name: 'title',
                            label: 'Title'
                        }
                    ],
                    attributes: {
                        src: 'https://placehold.co/600x400/e2e8f0/64748b?text=Select+Image'
                    }
                }
            }
        });


        // Also listen for double-click on image to open asset manager
        editor.on('component:selected', (component) => {
            if (component && component.is('image')) {
                // Ensure traits are updated when component is selected
                const src = component.get('src') || component.getAttributes().src;
                if (src) {
                    component.setAttributes({ src: src });
                }
            }
        });

        // Right Panel Tab Switching
        document.querySelectorAll('.panel__right-tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.panel__right-tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                const panel = tab.dataset.panel;
                document.querySelector('.styles-container').style.display = panel === 'styles' ? 'block' : 'none';
                document.querySelector('.traits-container').style.display = panel === 'settings' ? 'block' : 'none';
                document.querySelector('.layers-container').style.display = panel === 'layers' ? 'block' : 'none';
                document.querySelector('.page-container').style.display = panel === 'page' ? 'block' : 'none';
            });
        });

        // SEO Asset Manager Integration
        let assetTarget = null;
        function openSEOAssetManager() {
            assetTarget = 'seo';
            editor.AssetManager.open();
        }

        editor.on('asset:select', (asset) => {
            const src = asset.get('src') || asset.getSrc();

            if (assetTarget === 'seo') {
                document.getElementById('og_image').value = src;
                document.getElementById('og_image_preview').src = src;
                assetTarget = null;
            } else {
                const selected = editor.getSelected();
                if (selected && selected.is('image')) {
                    selected.set('src', src);
                    selected.addAttributes({ src: src });
                    editor.trigger('component:update', selected);
                }
            }
        });

        // Load existing data
        const initialDataRaw = <?= json_encode($page['grapes_data'] ?? '', JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

        if (initialDataRaw && initialDataRaw !== '""' && initialDataRaw !== '') {
            try {
                // grapes_data is stored as JSON string in DB
                // If it's already an object, use it directly. If it's a string, parse it.
                let projectData = initialDataRaw;
                if (typeof initialDataRaw === 'string' && initialDataRaw.trim().startsWith('{')) {
                    projectData = JSON.parse(initialDataRaw);
                }

                if (projectData && typeof projectData === 'object' && Object.keys(projectData).length > 0) {
                    editor.loadProjectData(projectData);
                }
            } catch (e) {
                console.error("Error loading project data:", e);
            }
        }

        // Save Function
        function saveContent(publish = false) {
            const html = editor.getHtml();
            const css = editor.getCss();
            const projectData = editor.getProjectData();

            // Get SEO Data
            const seoData = {
                seo_title: document.getElementById('seo_title') ? document.getElementById('seo_title').value : '',
                seo_description: document.getElementById('seo_description') ? document.getElementById('seo_description').value : '',
                og_image: document.getElementById('og_image') ? document.getElementById('og_image').value : ''
            };

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    html,
                    css,
                    components: projectData,
                    publish: publish,
                    seo: seoData
                })
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        showToast(publish ? 'Page published successfully!' : 'Draft saved!');
                    } else {
                        showToast('Error saving', 'error');
                    }
                })
                .catch(err => {
                    showToast('Error: ' + err, 'error');
                });
        }

        // Save & Publish buttons
        document.getElementById('save-btn').addEventListener('click', () => saveContent(false));
        document.getElementById('publish-btn').addEventListener('click', () => saveContent(true));

        // Block Picker Modal for Layers
        let selectedLayerComponent = null;

        // Create the block picker modal
        const blockPickerModal = document.createElement('div');
        blockPickerModal.id = 'block-picker-modal';
        blockPickerModal.innerHTML = `
            <div class="block-picker-overlay"></div>
            <div class="block-picker-content">
                <div class="block-picker-header">
                    <h3><i class="fas fa-plus-circle"></i> Add Block</h3>
                    <button class="block-picker-close"><i class="fas fa-times"></i></button>
                </div>
                <div class="block-picker-search">
                    <input type="text" placeholder="Search blocks..." id="block-search-input">
                </div>
                <div class="block-picker-grid" id="block-picker-grid"></div>
            </div>
        `;
        document.body.appendChild(blockPickerModal);

        // Populate block picker grid
        function populateBlockPicker() {
            const grid = document.getElementById('block-picker-grid');
            const blocks = editor.BlockManager.getAll();
            grid.innerHTML = '';

            blocks.forEach(block => {
                const blockEl = document.createElement('div');
                blockEl.className = 'block-picker-item';
                blockEl.dataset.blockId = block.id;
                blockEl.innerHTML = `
                    <div class="block-picker-icon">${block.get('label')}</div>
                `;
                blockEl.addEventListener('click', () => {
                    if (selectedLayerComponent) {
                        const content = block.get('content');
                        if (typeof content === 'object') {
                            selectedLayerComponent.append(content);
                        } else {
                            selectedLayerComponent.append(content);
                        }
                        closeBlockPicker();
                        showToast('Block added!');
                    }
                });
                grid.appendChild(blockEl);
            });
        }

        // Open block picker
        function openBlockPicker(component) {
            selectedLayerComponent = component;
            populateBlockPicker();
            blockPickerModal.classList.add('show');
        }

        // Close block picker
        function closeBlockPicker() {
            blockPickerModal.classList.remove('show');
            selectedLayerComponent = null;
        }

        // Close button
        blockPickerModal.querySelector('.block-picker-close').addEventListener('click', closeBlockPicker);
        blockPickerModal.querySelector('.block-picker-overlay').addEventListener('click', closeBlockPicker);

        // Search functionality
        document.getElementById('block-search-input').addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();
            document.querySelectorAll('.block-picker-item').forEach(item => {
                const text = item.textContent.toLowerCase();
                item.style.display = text.includes(query) ? 'flex' : 'none';
            });
        });

        // Add action buttons to layers (after DOM updates)
        const layersObserver = new MutationObserver(() => {
            document.querySelectorAll('.gjs-layer').forEach(layer => {
                if (!layer.dataset.actionBtnsAttached) {
                    layer.dataset.actionBtnsAttached = 'true';

                    // Create action buttons container
                    const actionsDiv = document.createElement('div');
                    actionsDiv.className = 'layer-actions';
                    actionsDiv.innerHTML = `
                        <button class="layer-action-btn duplicate-btn" title="Duplicate"><i class="fas fa-copy"></i></button>
                        <button class="layer-action-btn add-btn" title="Add Child"><i class="fas fa-plus"></i></button>
                        <button class="layer-action-btn delete-btn" title="Delete"><i class="fas fa-trash"></i></button>
                    `;
                    layer.style.position = 'relative';
                    layer.appendChild(actionsDiv);

                    // Get component for this layer
                    const getLayerComponent = () => {
                        // First select this layer in the editor
                        layer.click();
                        return editor.getSelected();
                    };

                    // Add button click
                    actionsDiv.querySelector('.add-btn').addEventListener('click', (e) => {
                        e.stopPropagation();
                        const component = getLayerComponent();
                        if (component) {
                            openBlockPicker(component);
                        } else {
                            openBlockPicker(editor.getWrapper());
                        }
                    });

                    // Duplicate button click
                    actionsDiv.querySelector('.duplicate-btn').addEventListener('click', (e) => {
                        e.stopPropagation();
                        const component = getLayerComponent();
                        if (component) {
                            const parent = component.parent();
                            const index = parent.components().indexOf(component);
                            const cloned = component.clone();
                            parent.components().add(cloned, { at: index + 1 });
                            editor.select(cloned);
                            showToast('Element duplicated!');
                        }
                    });

                    // Delete button click
                    actionsDiv.querySelector('.delete-btn').addEventListener('click', (e) => {
                        e.stopPropagation();
                        const component = getLayerComponent();
                        if (component && component.get('type') !== 'wrapper') {
                            component.remove();
                            showToast('Element deleted!');
                        }
                    });
                }
            });
        });

        // Start observing layers container
        setTimeout(() => {
            const layersContainer = document.querySelector('.layers-container');
            if (layersContainer) {
                layersObserver.observe(layersContainer, { childList: true, subtree: true });
            }
        }, 1000);

        // ═══════════════════════════════════════════════════
        // LINKED SPACING CONTROLS (Margin & Padding)
        // ═══════════════════════════════════════════════════

        let marginLinked = true;
        let paddingLinked = true;

        // Add link toggles to Spacing sector
        function addSpacingLinkToggles() {
            const spacingSector = document.querySelector('.gjs-sm-sector[data-sector-name="Spacing"], .gjs-sm-sector:has(.gjs-sm-property[data-property="margin-top"])');
            if (!spacingSector) return;

            // Find margin and padding property groups
            const marginProps = spacingSector.querySelector('.gjs-sm-property[data-property="margin"]');
            const paddingProps = spacingSector.querySelector('.gjs-sm-property[data-property="padding"]');

            // Add link button to margin if not already added
            if (marginProps && !marginProps.querySelector('.spacing-link-btn')) {
                addLinkButton(marginProps, 'margin');
            }

            // Add link button to padding if not already added
            if (paddingProps && !paddingProps.querySelector('.spacing-link-btn')) {
                addLinkButton(paddingProps, 'padding');
            }

            // Also add to individual properties
            addIndividualSpacingLinks();
        }

        function addLinkButton(container, type) {
            const label = container.querySelector('.gjs-sm-label');
            if (label && !label.querySelector('.spacing-link-btn')) {
                const linkBtn = document.createElement('button');
                linkBtn.className = 'spacing-link-btn active';
                linkBtn.innerHTML = '<i class="fas fa-link"></i>';
                linkBtn.title = 'Link all sides';
                linkBtn.dataset.type = type;

                linkBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    linkBtn.classList.toggle('active');
                    if (type === 'margin') {
                        marginLinked = linkBtn.classList.contains('active');
                    } else {
                        paddingLinked = linkBtn.classList.contains('active');
                    }
                });

                label.appendChild(linkBtn);
            }
        }

        function addIndividualSpacingLinks() {
            const styleContainer = document.querySelector('.styles-container');
            if (!styleContainer) return;

            // Find all margin/padding input fields
            const marginInputs = styleContainer.querySelectorAll('[data-property^="margin-"] input, [name^="margin-"]');
            const paddingInputs = styleContainer.querySelectorAll('[data-property^="padding-"] input, [name^="padding-"]');

            // Sync margin inputs
            marginInputs.forEach(input => {
                if (!input.dataset.linkedHandler) {
                    input.dataset.linkedHandler = 'true';
                    input.addEventListener('input', () => {
                        if (marginLinked) {
                            const value = input.value;
                            marginInputs.forEach(other => {
                                if (other !== input) {
                                    other.value = value;
                                    other.dispatchEvent(new Event('change', { bubbles: true }));
                                }
                            });
                        }
                    });
                }
            });

            // Sync padding inputs
            paddingInputs.forEach(input => {
                if (!input.dataset.linkedHandler) {
                    input.dataset.linkedHandler = 'true';
                    input.addEventListener('input', () => {
                        if (paddingLinked) {
                            const value = input.value;
                            paddingInputs.forEach(other => {
                                if (other !== input) {
                                    other.value = value;
                                    other.dispatchEvent(new Event('change', { bubbles: true }));
                                }
                            });
                        }
                    });
                }
            });
        }

        // Watch for style manager updates
        editor.on('component:selected', () => {
            setTimeout(addSpacingLinkToggles, 100);
        });

        // Also observe style container for changes
        setTimeout(() => {
            const stylesContainer = document.querySelector('.styles-container');
            if (stylesContainer) {
                const styleObserver = new MutationObserver(() => {
                    setTimeout(addSpacingLinkToggles, 50);
                });
                styleObserver.observe(stylesContainer, { childList: true, subtree: true });
            }
            addSpacingLinkToggles();
        }, 1500);

    </script>

    <style>
        /* Spacing Link Toggle Button */
        .spacing-link-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            background: #475569;
            border: none;
            border-radius: 4px;
            color: #94a3b8;
            cursor: pointer;
            margin-left: 6px;
            font-size: 10px;
            transition: all 0.2s;
            vertical-align: middle;
        }

        .spacing-link-btn:hover {
            background: #64748b;
            color: #f1f5f9;
        }

        .spacing-link-btn.active {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            color: white;
        }

        .spacing-link-btn.active:hover {
            box-shadow: 0 2px 8px rgba(34, 197, 94, 0.4);
        }

        /* Spacing sector styling */
        .gjs-sm-composite .gjs-sm-properties {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
        }

        .gjs-sm-composite .gjs-sm-property {
            margin-bottom: 0;
        }

        /* Block Picker Modal */
        #block-picker-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 10000;
            display: none;
        }

        #block-picker-modal.show {
            display: block;
        }

        .block-picker-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
        }

        .block-picker-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 600px;
            max-width: 90vw;
            max-height: 80vh;
            background: #1e293b;
            border-radius: 16px;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.5);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .block-picker-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 20px;
            border-bottom: 1px solid #334155;
        }

        .block-picker-header h3 {
            margin: 0;
            color: #f1f5f9;
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .block-picker-header h3 i {
            color: #22c55e;
        }

        .block-picker-close {
            background: none;
            border: none;
            color: #64748b;
            font-size: 18px;
            cursor: pointer;
            padding: 5px;
            transition: color 0.2s;
        }

        .block-picker-close:hover {
            color: #f1f5f9;
        }

        .block-picker-search {
            padding: 12px 20px;
            border-bottom: 1px solid #334155;
        }

        .block-picker-search input {
            width: 100%;
            padding: 10px 14px;
            background: #0f172a;
            border: 1px solid #334155;
            border-radius: 8px;
            color: #f1f5f9;
            font-size: 14px;
        }

        .block-picker-search input:focus {
            outline: none;
            border-color: #38bdf8;
        }

        .block-picker-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            padding: 20px;
            overflow-y: auto;
            max-height: 400px;
        }

        .block-picker-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 16px 8px;
            background: linear-gradient(145deg, #334155, #1e293b);
            border: 1px solid #475569;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
            min-height: 80px;
        }

        .block-picker-item:hover {
            border-color: #22c55e;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(34, 197, 94, 0.2);
        }

        .block-picker-icon {
            text-align: center;
            color: #94a3b8;
            font-size: 12px;
        }

        .block-picker-item:hover .block-picker-icon {
            color: #f1f5f9;
        }

        .block-picker-icon .gjs-block__media {
            margin-bottom: 6px;
        }

        .block-picker-icon i {
            font-size: 20px;
            color: #64748b;
        }

        .block-picker-item:hover .block-picker-icon i {
            color: #22c55e;
        }
    </style>
</body>

</html>