<?php
/**
 * Page Builder
 * Visual page builder with drag-drop components
 */
require_once __DIR__ . "/../../src/Core/Auth.php";
require_once __DIR__ . "/../../src/Core/Model.php";
require_once __DIR__ . "/../../src/Core/MultiTenancy.php";
require_once __DIR__ . "/../../src/Core/LayoutRenderer.php";
require_once __DIR__ . "/../../src/Models/Page.php";
require_once __DIR__ . "/../../src/Models/ComponentSchema.php";
require_once __DIR__ . "/../../src/Core/Cache.php";

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

// Database connection
$tenantId = \Core\MultiTenancy::getTenantId();
define('DB_PATH', \Core\MultiTenancy::getDatabasePath($tenantId));
try {
    $pdo = new PDO('sqlite:' . DB_PATH);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    \Core\Model::setPdo($pdo);
    \Models\Page::setPdo($pdo);
    \Models\ComponentSchema::setPdo($pdo);
    \Models\ComponentSchema::createTable();
} catch (PDOException $e) {
    die('Database error: ' . $e->getMessage());
}

// Get page if editing
$pageId = isset($_GET['page_id']) ? (int) $_GET['page_id'] : 0;
$page = null;
$layout = null;

if ($pageId) {
    $page = \Models\Page::find($pageId);
    if ($page) {
        $parsed = \Core\LayoutRenderer::parseContentWithLayout($page['content'] ?? '');
        $layout = $parsed['layout'];

        // If no layout found but content exists, try legacy parsing
        if (!$layout && !empty($page['content'])) {
            $layout = \Core\LayoutRenderer::parseLegacyContent($page['content']);
        }

        if (!$layout) {
            $layout = \Core\LayoutRenderer::createEmptyLayout();
        }
    }
}

if (!$layout) {
    $layout = \Core\LayoutRenderer::createEmptyLayout();
}

// Get component schemas - indexed by name for easy lookup
$schemas = \Models\ComponentSchema::all();
if (empty($schemas)) {
    \Models\ComponentSchema::seedDefaultSchemas();
    $schemas = \Models\ComponentSchema::all();
}

$schemasIndexed = [];
foreach ($schemas as $schema) {
    $schemasIndexed[$schema['component_name']] = $schema;
}

// Group by category
$categories = [];
foreach ($schemas as $schema) {
    $cat = $schema['category'] ?? 'general';
    if (!isset($categories[$cat])) {
        $categories[$cat] = [];
    }
    $categories[$cat][] = $schema;
}

// Get presets
$presets = \Core\LayoutRenderer::getPresets();

// Handle AJAX save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');

    if ($_POST['action'] === 'save') {
        $layoutData = json_decode($_POST['layout'] ?? '{}', true);
        $pageId = (int) ($_POST['page_id'] ?? 0);

        file_put_contents(__DIR__ . '/debug_save.log', date('Y-m-d H:i:s') . " - Save Request for Page $pageId\nLayout: " . substr($_POST['layout'], 0, 100) . "...\n", FILE_APPEND);

        // Convert layout to content
        $content = \Core\LayoutRenderer::layoutToContent($layoutData);

        if ($pageId) {
            \Models\Page::update($pageId, ['content' => $content]);

            // Clear cache
            \Core\Cache::clear();

            echo json_encode(['success' => true, 'message' => 'Page saved!']);
        } else {
            echo json_encode(['success' => false, 'error' => 'No page selected']);
        }
        exit;
    }

    if ($_POST['action'] === 'get_schema') {
        $componentName = $_POST['component'] ?? '';
        if (isset($schemasIndexed[$componentName])) {
            $schema = $schemasIndexed[$componentName];
            $schema['schema'] = is_string($schema['schema']) ? json_decode($schema['schema'], true) : $schema['schema'];
            echo json_encode(['success' => true, 'schema' => $schema]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Schema not found']);
        }
        exit;
    }

    exit;
}

// Get all pages for selector
$pages = \Models\Page::all();

$pageTitle = 'Page Builder';
$currentPage = 'page-builder';

ob_start();
?>

<style>
    .builder-container {
        display: flex;
        gap: 1rem;
        min-height: 70vh;
    }

    .builder-sidebar {
        width: 280px;
        flex-shrink: 0;
    }

    .builder-canvas {
        flex: 1;
        background: #f5f5f5;
        border-radius: 8px;
        padding: 1rem;
        min-height: 500px;
    }

    .builder-row {
        background: white;
        border: 2px dashed #dbdbdb;
        border-radius: 8px;
        margin-bottom: 1rem;
        position: relative;
        overflow: hidden;
    }

    .builder-row:hover {
        border-color: #3273dc;
    }

    .builder-row.has-bg-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .builder-row.has-bg-dark {
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    }

    .builder-row.has-bg-light {
        background: #f5f5f5;
    }

    .builder-row.has-bg-success {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }

    .builder-row.has-bg-warning {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    .builder-row.has-bg-info {
        background: linear-gradient(135deg, #2193b0 0%, #6dd5ed 100%);
    }

    .builder-row-header {
        padding: 0.75rem 1rem;
        background: rgba(255, 255, 255, 0.95);
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: move;
    }

    .builder-row-content {
        padding: 1rem;
    }

    .builder-row.padding-none .builder-row-content {
        padding: 0;
    }

    .builder-row.padding-small .builder-row-content {
        padding: 0.5rem;
    }

    .builder-row.padding-large .builder-row-content {
        padding: 2rem;
    }

    .builder-columns {
        display: flex;
        gap: 1rem;
    }

    .builder-column {
        flex: 1;
        min-height: 80px;
        background: rgba(255, 255, 255, 0.9);
        border: 2px dashed #e5e5e5;
        border-radius: 4px;
        padding: 0.5rem;
    }

    .builder-column:hover {
        border-color: #00d1b2;
    }

    .builder-component {
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 0.5rem 0.75rem;
        margin-bottom: 0.5rem;
        cursor: pointer;
        position: relative;
        transition: all 0.2s;
    }

    .builder-component:hover {
        border-color: #3273dc;
        box-shadow: 0 2px 8px rgba(50, 115, 220, 0.2);
    }

    .builder-component-label {
        font-size: 0.85rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .builder-component-actions {
        position: absolute;
        top: 0.25rem;
        right: 0.25rem;
        opacity: 0;
        transition: opacity 0.2s;
        display: flex;
        gap: 0.25rem;
    }

    .builder-component:hover .builder-component-actions {
        opacity: 1;
    }

    .component-palette-item {
        cursor: grab;
        padding: 0.5rem;
        border: 1px solid #ddd;
        border-radius: 4px;
        margin-bottom: 0.5rem;
        background: white;
        transition: all 0.2s;
    }

    .component-palette-item:hover {
        border-color: #3273dc;
        background: #f5f5f5;
    }

    .add-row-btn {
        width: 100%;
        padding: 1rem;
        border: 2px dashed #ccc;
        border-radius: 8px;
        background: transparent;
        cursor: pointer;
        color: #666;
        transition: all 0.2s;
    }

    .add-row-btn:hover {
        border-color: #3273dc;
        color: #3273dc;
    }

    .preset-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 0.5rem;
    }

    .preset-item {
        padding: 0.5rem;
        border: 2px solid #ddd;
        border-radius: 4px;
        cursor: pointer;
        text-align: center;
        transition: all 0.2s;
    }

    .preset-item:hover {
        border-color: #3273dc;
    }

    .preset-preview {
        display: flex;
        gap: 2px;
        height: 20px;
        margin-bottom: 0.25rem;
    }

    .preset-preview-col {
        background: #3273dc;
        border-radius: 2px;
        opacity: 0.3;
    }

    .col-width-12 {
        flex: 12;
    }

    .col-width-8 {
        flex: 8;
    }

    .col-width-6 {
        flex: 6;
    }

    .col-width-4 {
        flex: 4;
    }

    .col-width-3 {
        flex: 3;
    }

    /* Row settings indicator */
    .row-settings-badge {
        font-size: 0.7rem;
        padding: 0.15rem 0.5rem;
        background: #f0f0f0;
        border-radius: 10px;
        margin-left: 0.5rem;
    }

    /* Component edit form */
    .component-form-field {
        margin-bottom: 1rem;
    }

    .component-form-field label {
        display: block;
        font-weight: 600;
        margin-bottom: 0.25rem;
        font-size: 0.9rem;
    }

    /* Responsive Preview */
    .builder-canvas-wrapper {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        background: #e0e0e0;
        border-radius: 8px;
        padding: 1rem;
        transition: all 0.3s;
    }

    .builder-canvas {
        width: 100%;
        background: #f5f5f5;
        min-height: 500px;
        transition: width 0.3s ease;
        padding: 1rem;
        border-radius: 8px;
    }

    .builder-canvas.is-mobile {
        width: 375px;
        border: 12px solid #333;
        border-radius: 20px;
        padding: 20px 1rem;
    }

    .builder-canvas.is-tablet {
        width: 768px;
        border: 12px solid #333;
        border-radius: 12px;
        padding: 20px 1rem;
    }

    .responsive-controls {
        background: white;
        padding: 0.5rem;
        border-radius: 20px;
        display: inline-flex;
        gap: 0.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
</style>

<!-- SortableJS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<div class="level mb-4">
    <div class="level-left">
        <div class="field has-addons">
            <div class="control">
                <div class="select">
                    <select id="pageSelector">
                        <option value="">Select a page...</option>
                        <?php foreach ($pages as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= $p['id'] == $pageId ? 'selected' : '' ?>>
                                <?= htmlspecialchars($p['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="control">
                <button class="button is-info" onclick="loadPage()">
                    <span class="icon"><i class="fas fa-folder-open"></i></span>
                </button>
            </div>
        </div>
    </div>

    <div class="level-item">
        <div class="responsive-controls">
            <button class="button is-small is-primary is-selected" onclick="setDevice('desktop')" id="btn-desktop"
                title="Desktop">
                <span class="icon"><i class="fas fa-desktop"></i></span>
            </button>
            <button class="button is-small is-light" onclick="setDevice('tablet')" id="btn-tablet" title="Tablet">
                <span class="icon"><i class="fas fa-tablet-alt"></i></span>
            </button>
            <button class="button is-small is-light" onclick="setDevice('mobile')" id="btn-mobile" title="Mobile">
                <span class="icon"><i class="fas fa-mobile-alt"></i></span>
            </button>
        </div>
    </div>

    <div class="level-right">
        <div class="buttons">
            <button class="button is-light" onclick="previewPage()">
                <span class="icon"><i class="fas fa-eye"></i></span>
                <span>Preview</span>
            </button>
            <button class="button is-primary" onclick="savePage()">
                <span class="icon"><i class="fas fa-save"></i></span>
                <span>Save Page</span>
            </button>
        </div>
    </div>
</div>

<div class="builder-container">
    <!-- Sidebar -->
    <div class="builder-sidebar">
        <div class="admin-card">
            <h3 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-plus-square"></i></span>
                Add Row
            </h3>
            <div class="preset-grid mb-3">
                <?php foreach ($presets as $key => $preset): ?>
                    <div class="preset-item" data-preset="<?= $key ?>" onclick="addRow('<?= $key ?>')">
                        <div class="preset-preview">
                            <?php foreach ($preset['columns'] as $w): ?>
                                <div class="preset-preview-col col-width-<?= $w ?>"></div>
                            <?php endforeach; ?>
                        </div>
                        <small><?= htmlspecialchars($preset['label']) ?></small>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="admin-card">
            <h3 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-puzzle-piece"></i></span>
                Components
            </h3>
            <div class="field mb-3">
                <div class="control has-icons-left">
                    <input type="text" class="input is-small" id="componentSearch" placeholder="Search...">
                    <span class="icon is-left"><i class="fas fa-search"></i></span>
                </div>
            </div>
            <div id="componentPalette" style="max-height: 400px; overflow-y: auto;">
                <?php foreach ($categories as $catName => $catComponents): ?>
                    <p class="is-size-7 has-text-weight-bold has-text-grey mb-2 mt-3">
                        <?= ucfirst(str_replace('-', ' ', $catName)) ?>
                    </p>
                    <?php foreach ($catComponents as $comp): ?>
                        <div class="component-palette-item" data-component="<?= htmlspecialchars($comp['component_name']) ?>"
                            data-name="<?= htmlspecialchars($comp['display_name']) ?>"
                            data-icon="<?= htmlspecialchars($comp['icon'] ?? 'fas fa-puzzle-piece') ?>">
                            <span class="icon is-small has-text-primary mr-2">
                                <i class="<?= htmlspecialchars($comp['icon'] ?? 'fas fa-puzzle-piece') ?>"></i>
                            </span>
                            <?= htmlspecialchars($comp['display_name']) ?>
                        </div>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Canvas -->
    <div class="builder-canvas" id="builderCanvas">
        <?php if (!$pageId): ?>
            <div class="has-text-centered py-6" id="noPageMessage">
                <span class="icon is-large has-text-grey-light">
                    <i class="fas fa-file-alt fa-3x"></i>
                </span>
                <p class="has-text-grey mt-4">Select a page to start building</p>
            </div>
        <?php else: ?>
            <div id="rowsContainer"></div>
            <button class="add-row-btn" onclick="showPresetModal()">
                <span class="icon"><i class="fas fa-plus"></i></span>
                Add Row
            </button>
        <?php endif; ?>
    </div>
</div>

<!-- Row Settings Modal -->
<div class="modal" id="rowSettingsModal">
    <div class="modal-background" onclick="closeRowSettings()"></div>
    <div class="modal-card" style="max-width: 500px;">
        <header class="modal-card-head">
            <p class="modal-card-title"><i class="fas fa-cog mr-2"></i>Row Settings</p>
            <button class="delete" onclick="closeRowSettings()"></button>
        </header>
        <section class="modal-card-body">
            <input type="hidden" id="rowSettingsRowId">

            <div class="field">
                <label class="label">Background</label>
                <div class="control">
                    <div class="select is-fullwidth">
                        <select id="rowBg">
                            <option value="">None (White)</option>
                            <option value="primary">Primary (Purple Gradient)</option>
                            <option value="dark">Dark (Navy)</option>
                            <option value="light">Light (Gray)</option>
                            <option value="info">Info (Blue Gradient)</option>
                            <option value="success">Success (Green Gradient)</option>
                            <option value="warning">Warning (Pink Gradient)</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="field">
                <label class="label">Padding</label>
                <div class="control">
                    <div class="select is-fullwidth">
                        <select id="rowPadding">
                            <option value="">Normal</option>
                            <option value="none">None</option>
                            <option value="small">Small</option>
                            <option value="large">Large</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="field">
                <label class="checkbox">
                    <input type="checkbox" id="rowFullWidth">
                    Full Width (No Container)
                </label>
            </div>

            <div class="field">
                <label class="label">Custom CSS Class</label>
                <div class="control">
                    <input type="text" class="input" id="rowCssClass" placeholder="my-custom-class">
                </div>
            </div>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-primary" onclick="saveRowSettings()">
                <span class="icon"><i class="fas fa-check"></i></span>
                <span>Apply</span>
            </button>
            <button class="button" onclick="closeRowSettings()">Cancel</button>
        </footer>
    </div>
</div>

<!-- Component Edit Modal -->
<div class="modal" id="componentEditModal">
    <div class="modal-background" onclick="closeComponentEdit()"></div>
    <div class="modal-card" style="max-width: 600px; max-height: 90vh;">
        <header class="modal-card-head">
            <p class="modal-card-title" id="componentEditTitle"><i class="fas fa-edit mr-2"></i>Edit Component</p>
            <button class="delete" onclick="closeComponentEdit()"></button>
        </header>
        <section class="modal-card-body" id="componentEditBody" style="max-height: 60vh; overflow-y: auto;">
            <!-- Dynamic form fields -->
        </section>
        <footer class="modal-card-foot">
            <button class="button is-primary" onclick="saveComponentEdit()">
                <span class="icon"><i class="fas fa-check"></i></span>
                <span>Apply</span>
            </button>
            <button class="button is-info is-light" onclick="duplicateComponent()">
                <span class="icon"><i class="fas fa-copy"></i></span>
                <span>Duplicate</span>
            </button>
            <button class="button" onclick="closeComponentEdit()">Cancel</button>
        </footer>
    </div>
</div>

<!-- Preset Modal -->
<div class="modal" id="presetModal">
    <div class="modal-background" onclick="this.parentElement.classList.remove('is-active')"></div>
    <div class="modal-card" style="max-width: 500px;">
        <header class="modal-card-head">
            <p class="modal-card-title">Choose Layout</p>
            <button class="delete" onclick="this.closest('.modal').classList.remove('is-active')"></button>
        </header>
        <section class="modal-card-body">
            <div class="preset-grid" style="grid-template-columns: repeat(2, 1fr); gap: 1rem;">
                <?php foreach ($presets as $key => $preset): ?>
                    <div class="preset-item" onclick="addRowFromModal('<?= $key ?>')">
                        <div class="preset-preview" style="height: 40px; margin-bottom: 0.5rem;">
                            <?php foreach ($preset['columns'] as $w): ?>
                                <div class="preset-preview-col col-width-<?= $w ?>"></div>
                            <?php endforeach; ?>
                        </div>
                        <strong><?= htmlspecialchars($preset['label']) ?></strong>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>
</div>

<script>
    // Layout data
    let layoutData = <?= json_encode($layout) ?>;
    let currentPageId = <?= $pageId ?>;
    const presets = <?= json_encode($presets) ?>;
    const componentSchemas = <?= json_encode($schemasIndexed) ?>;

    // Current editing context
    let editingRowId = null;
    let editingComponent = { rowId: null, colIndex: null, compIndex: null };

    // Initialize
    document.addEventListener('DOMContentLoaded', function () {
        if (currentPageId) {
            renderLayout();
            initDragDrop();
        }

        // Component search
        document.getElementById('componentSearch').addEventListener('input', function () {
            const query = this.value.toLowerCase();
            document.querySelectorAll('.component-palette-item').forEach(item => {
                item.style.display = item.textContent.toLowerCase().includes(query) ? 'block' : 'none';
            });
        });
    });

    // Render layout
    function renderLayout() {
        const container = document.getElementById('rowsContainer');
        if (!container) return;

        container.innerHTML = '';
        layoutData.rows.forEach((row, i) => container.appendChild(createRowElement(row, i)));
        initDragDrop();
    }

    // Create row element
    function createRowElement(row, rowIndex) {
        const preset = presets[row.layout] || presets.full;

        const rowEl = document.createElement('div');
        rowEl.className = 'builder-row';
        rowEl.dataset.rowId = row.id;
        rowEl.dataset.rowIndex = rowIndex;

        // Apply row settings classes
        if (row.background) rowEl.classList.add('has-bg-' + row.background);
        if (row.padding) rowEl.classList.add('padding-' + row.padding);

        // Settings badge
        let settingsBadge = '';
        if (row.background || row.padding || row.fullWidth) {
            const parts = [];
            if (row.background) parts.push(row.background);
            if (row.padding) parts.push(row.padding + ' padding');
            if (row.fullWidth) parts.push('full-width');
            settingsBadge = `<span class="row-settings-badge">${parts.join(', ')}</span>`;
        }

        rowEl.innerHTML = `
        <div class="builder-row-header">
            <span><i class="fas fa-grip-lines mr-2"></i>${preset.label}${settingsBadge}</span>
            <div class="buttons are-small">
                <button class="button is-small is-info is-light" onclick="editRowSettings('${row.id}')" title="Row Settings">
                    <span class="icon"><i class="fas fa-cog"></i></span>
                </button>
                <button class="button is-small is-warning is-light" onclick="duplicateRow('${row.id}')" title="Duplicate Row">
                    <span class="icon"><i class="fas fa-copy"></i></span>
                </button>
                <button class="button is-small is-danger is-light" onclick="removeRow('${row.id}')" title="Delete Row">
                    <span class="icon"><i class="fas fa-trash"></i></span>
                </button>
            </div>
        </div>
        <div class="builder-row-content">
            <div class="builder-columns">
                ${row.columns.map((col, colIndex) => `
                    <div class="builder-column" data-col-index="${colIndex}" style="flex: ${preset.columns[colIndex] || 12};">
                        ${col.components && col.components.length > 0
                ? col.components.map((comp, compIndex) => createComponentHtml(comp, row.id, colIndex, compIndex)).join('')
                : '<span class="has-text-grey is-size-7">Drop components here</span>'
            }
                    </div>
                `).join('')}
            </div>
        </div>
    `;

        return rowEl;
    }

    // Create component HTML
    function createComponentHtml(component, rowId, colIndex, compIndex) {
        let name = 'Component';
        let icon = 'fas fa-puzzle-piece';
        let attrs = {};

        if (typeof component === 'string') {
            const match = component.match(/\[component:(\w+)([^\]]*)\]/);
            if (match) {
                name = match[1];
                // Parse attributes
                const attrStr = match[2];
                const attrRegex = /(\w+)="([^"]*)"/g;
                let m;
                while ((m = attrRegex.exec(attrStr)) !== null) {
                    attrs[m[1]] = m[2];
                }
            }
            // Get icon from schema
            if (componentSchemas[name]) {
                icon = componentSchemas[name].icon || icon;
            }
        }

        // Show first attribute as preview
        let preview = '';
        if (attrs.title) {
            preview = `<span class="is-size-7 has-text-grey ml-2">"${attrs.title.substring(0, 20)}${attrs.title.length > 20 ? '...' : ''}"</span>`;
        }

        return `
        <div class="builder-component" 
             data-comp-index="${compIndex}" 
             data-row-id="${rowId}"
             data-col-index="${colIndex}"
             onclick="openComponentEdit('${rowId}', ${colIndex}, ${compIndex})">
            <div class="builder-component-actions">
                <button class="button is-small is-danger is-light" onclick="event.stopPropagation(); removeComponent('${rowId}', ${colIndex}, ${compIndex})">
                    <span class="icon is-small"><i class="fas fa-times"></i></span>
                </button>
            </div>
            <div class="builder-component-label">
                <span class="icon is-small has-text-primary"><i class="${icon}"></i></span>
                ${name}${preview}
            </div>
        </div>
    `;
    }

    // ============ ROW SETTINGS ============
    function editRowSettings(rowId) {
        editingRowId = rowId;
        const row = layoutData.rows.find(r => r.id === rowId);
        if (!row) return;

        document.getElementById('rowSettingsRowId').value = rowId;
        document.getElementById('rowBg').value = row.background || '';
        document.getElementById('rowPadding').value = row.padding || '';
        document.getElementById('rowFullWidth').checked = !!row.fullWidth;
        document.getElementById('rowCssClass').value = row.cssClass || '';

        document.getElementById('rowSettingsModal').classList.add('is-active');
    }

    function closeRowSettings() {
        document.getElementById('rowSettingsModal').classList.remove('is-active');
        editingRowId = null;
    }

    function saveRowSettings() {
        if (!editingRowId) return;

        layoutData.rows.forEach(row => {
            if (row.id === editingRowId) {
                row.background = document.getElementById('rowBg').value || null;
                row.padding = document.getElementById('rowPadding').value || null;
                row.fullWidth = document.getElementById('rowFullWidth').checked;
                row.cssClass = document.getElementById('rowCssClass').value || null;
            }
        });

        closeRowSettings();
        renderLayout();
    }

    // ============ COMPONENT EDITING ============
    function openComponentEdit(rowId, colIndex, compIndex) {
        editingComponent = { rowId, colIndex, compIndex };

        const row = layoutData.rows.find(r => r.id === rowId);
        if (!row || !row.columns[colIndex]) return;

        const component = row.columns[colIndex].components[compIndex];
        if (typeof component !== 'string') return;

        // Parse component
        const match = component.match(/\[component:(\w+)([^\]]*)\]/);
        if (!match) return;

        const compName = match[1];
        const attrStr = match[2];

        // Parse existing attributes
        const attrs = {};
        const attrRegex = /(\w+)="([^"]*)"/g;
        let m;
        while ((m = attrRegex.exec(attrStr)) !== null) {
            attrs[m[1]] = m[2].replace(/&quot;/g, '"');
        }

        // Get schema
        const schema = componentSchemas[compName];
        if (!schema) {
            alert('No schema found for: ' + compName);
            return;
        }

        const schemaData = typeof schema.schema === 'string' ? JSON.parse(schema.schema) : schema.schema;

        // Update modal title
        document.getElementById('componentEditTitle').innerHTML =
            `<i class="${schema.icon || 'fas fa-puzzle-piece'} mr-2"></i>Edit ${schema.display_name}`;

        // Build form
        const body = document.getElementById('componentEditBody');
        body.innerHTML = '';

        (schemaData.fields || []).forEach(field => {
            const value = attrs[field.name] || '';
            body.appendChild(createFormField(field, value));
        });

        document.getElementById('componentEditModal').classList.add('is-active');
    }

    function createFormField(field, value) {
        const div = document.createElement('div');
        div.className = 'component-form-field';

        const label = document.createElement('label');
        label.textContent = field.label || field.name;
        if (field.required) label.innerHTML += ' <span class="has-text-danger">*</span>';
        div.appendChild(label);

        const control = document.createElement('div');
        control.className = 'control';

        switch (field.type) {
            case 'textarea':
            case 'richtext':
                const ta = document.createElement('textarea');
                ta.className = 'textarea';
                ta.name = field.name;
                ta.rows = field.rows || 3;
                ta.value = value;
                control.appendChild(ta);
                break;

            case 'select':
                const selDiv = document.createElement('div');
                selDiv.className = 'select is-fullwidth';
                const sel = document.createElement('select');
                sel.name = field.name;
                sel.innerHTML = '<option value="">-- Select --</option>';
                (field.options || []).forEach(opt => {
                    const o = document.createElement('option');
                    o.value = typeof opt === 'object' ? opt.value : opt;
                    o.textContent = typeof opt === 'object' ? opt.label : opt;
                    if (o.value === value) o.selected = true;
                    sel.appendChild(o);
                });
                selDiv.appendChild(sel);
                control.appendChild(selDiv);
                break;

            case 'checkbox':
                const checkLabel = document.createElement('label');
                checkLabel.className = 'checkbox';
                const cb = document.createElement('input');
                cb.type = 'checkbox';
                cb.name = field.name;
                cb.checked = value === '1' || value === 'true';
                checkLabel.appendChild(cb);
                checkLabel.appendChild(document.createTextNode(' ' + (field.label || field.name)));
                control.appendChild(checkLabel);
                div.removeChild(label);
                break;

            case 'number':
                const numInput = document.createElement('input');
                numInput.type = 'number';
                numInput.className = 'input';
                numInput.name = field.name;
                numInput.value = value;
                numInput.step = 'any';
                control.appendChild(numInput);
                break;

            default: // text, url, email, etc
                const input = document.createElement('input');
                input.type = field.type === 'url' ? 'url' : (field.type === 'email' ? 'email' : 'text');
                input.className = 'input';
                input.name = field.name;
                input.value = value;
                input.placeholder = field.placeholder || '';
                control.appendChild(input);
        }

        div.appendChild(control);
        return div;
    }

    function closeComponentEdit() {
        document.getElementById('componentEditModal').classList.remove('is-active');
        editingComponent = { rowId: null, colIndex: null, compIndex: null };
    }

    function saveComponentEdit() {
        const { rowId, colIndex, compIndex } = editingComponent;
        if (!rowId) return;

        const row = layoutData.rows.find(r => r.id === rowId);
        if (!row || !row.columns[colIndex]) return;

        const component = row.columns[colIndex].components[compIndex];
        const match = component.match(/\[component:(\w+)/);
        if (!match) return;

        const compName = match[1];

        // Gather form data
        const form = document.getElementById('componentEditBody');
        const inputs = form.querySelectorAll('input, textarea, select');

        let shortcode = '[component:' + compName;
        inputs.forEach(input => {
            let value = input.type === 'checkbox' ? (input.checked ? '1' : '') : input.value;
            if (value) {
                value = value.replace(/"/g, '&quot;');
                shortcode += ` ${input.name}="${value}"`;
            }
        });
        shortcode += ']';

        row.columns[colIndex].components[compIndex] = shortcode;

        closeComponentEdit();
        renderLayout();
    }

    function duplicateComponent() {
        const { rowId, colIndex, compIndex } = editingComponent;
        if (!rowId) return;

        const row = layoutData.rows.find(r => r.id === rowId);
        if (!row || !row.columns[colIndex]) return;

        const component = row.columns[colIndex].components[compIndex];
        row.columns[colIndex].components.splice(compIndex + 1, 0, component);

        closeComponentEdit();
        renderLayout();
    }

    // ============ DRAG & DROP ============
    function initDragDrop() {
        const rowsContainer = document.getElementById('rowsContainer');
        if (rowsContainer) {
            new Sortable(rowsContainer, {
                animation: 150,
                handle: '.builder-row-header',
                onEnd: function (evt) {
                    const rows = [...layoutData.rows];
                    const [moved] = rows.splice(evt.oldIndex, 1);
                    rows.splice(evt.newIndex, 0, moved);
                    layoutData.rows = rows;
                }
            });
        }

        document.querySelectorAll('.builder-column').forEach(col => {
            new Sortable(col, {
                group: 'components',
                animation: 150,
                filter: '.has-text-grey',
                onAdd: function (evt) {
                    const item = evt.item;
                    const componentName = item.dataset.component;

                    if (componentName) {
                        const rowEl = evt.to.closest('.builder-row');
                        const rowId = rowEl.dataset.rowId;
                        const colIndex = parseInt(evt.to.dataset.colIndex);

                        const shortcode = `[component:${componentName}]`;
                        addComponentToLayout(rowId, colIndex, shortcode, evt.newIndex);
                        renderLayout();
                    }
                },
                onEnd: function (evt) {
                    // Handle reordering within/between columns
                    if (evt.from !== evt.to || evt.oldIndex !== evt.newIndex) {
                        // Already handled by onAdd for new items
                    }
                }
            });
        });

        const palette = document.getElementById('componentPalette');
        if (palette) {
            new Sortable(palette, {
                group: { name: 'components', pull: 'clone', put: false },
                sort: false,
                animation: 150
            });
        }
    }

    function addComponentToLayout(rowId, colIndex, component, position) {
        layoutData.rows.forEach(row => {
            if (row.id === rowId && row.columns[colIndex]) {
                if (position !== undefined) {
                    row.columns[colIndex].components.splice(position, 0, component);
                } else {
                    row.columns[colIndex].components.push(component);
                }
            }
        });
    }

    // ============ ROW ACTIONS ============
    function addRow(preset) {
        const columns = [];
        (presets[preset]?.columns || [12]).forEach(() => columns.push({ components: [] }));

        layoutData.rows.push({
            id: 'row-' + Date.now(),
            layout: preset,
            columns: columns
        });

        renderLayout();
    }

    function showPresetModal() {
        document.getElementById('presetModal').classList.add('is-active');
    }

    function addRowFromModal(preset) {
        addRow(preset);
        document.getElementById('presetModal').classList.remove('is-active');
    }

    function removeRow(rowId) {
        if (!confirm('Remove this row?')) return;
        layoutData.rows = layoutData.rows.filter(r => r.id !== rowId);
        renderLayout();
    }

    function duplicateRow(rowId) {
        const row = layoutData.rows.find(r => r.id === rowId);
        if (!row) return;

        const newRow = JSON.parse(JSON.stringify(row));
        newRow.id = 'row-' + Date.now();

        const index = layoutData.rows.findIndex(r => r.id === rowId);
        layoutData.rows.splice(index + 1, 0, newRow);

        renderLayout();
    }

    function removeComponent(rowId, colIndex, compIndex) {
        layoutData.rows.forEach(row => {
            if (row.id === rowId && row.columns[colIndex]) {
                row.columns[colIndex].components.splice(compIndex, 1);
            }
        });
        renderLayout();
    }

    // ============ PAGE ACTIONS ============
    function loadPage() {
        const pageId = document.getElementById('pageSelector').value;
        if (pageId) window.location.href = '/admin/page-builder.php?page_id=' + pageId;
    }

    function previewPage() {
        if (currentPageId) window.open('/?preview=1&page_id=' + currentPageId, '_blank');
    }
    // Save page
    function savePage() {
        if (!currentPageId) { alert('Please select a page first'); return; }

        fetch('/admin/page-builder.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=save&page_id=' + currentPageId + '&layout=' + encodeURIComponent(JSON.stringify(layoutData))
        })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    // Show success notification
                    const notif = document.createElement('div');
                    notif.className = 'notification is-success is-light';
                    notif.innerHTML = '<button class="delete" onclick="this.parentElement.remove()"></button>Page saved successfully!';
                    document.querySelector('.level').after(notif);
                    setTimeout(() => notif.remove(), 3000);
                } else {
                    alert('Error: ' + (data.error || 'Unknown error'));
                }
            });
    }

    // Responsive Preview
    function setDevice(device) {
        const canvas = document.getElementById('builderCanvas');

        // Remove all current classes
        canvas.classList.remove('is-mobile', 'is-tablet');

        // Update buttons
        document.querySelectorAll('.responsive-controls button').forEach(btn => {
            btn.classList.remove('is-primary', 'is-selected');
            btn.classList.add('is-light');
        });

        const btn = document.getElementById('btn-' + device);
        btn.classList.remove('is-light');
        btn.classList.add('is-primary', 'is-selected');

        if (device === 'mobile') {
            canvas.classList.add('is-mobile');
        } else if (device === 'tablet') {
            canvas.classList.add('is-tablet');
        }
    }
</script>

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