<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Builder — <?= e($page['title']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.2/Sortable.min.js"></script>
    <script>
        tailwind.config = {
            theme: { extend: { fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }, colors: { brand: { 500:'#3b6ff1', 600:'#2452e6' }, surface: { border:'#1e2536', hover:'#1c2338', card:'#161b27' } } } }
        }
    </script>
    <style>
        * { font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background:#0f1117; color:#e2e8f0; margin:0; overflow:hidden; }
        ::-webkit-scrollbar { width:5px; }
        ::-webkit-scrollbar-track { background:#0f1117; }
        ::-webkit-scrollbar-thumb { background:#2d3748; border-radius:3px; }
        .sidebar { width:280px; background:#0d1120; border-right:1px solid #1e2536; height:100vh; display:flex; flex-direction:column; flex-shrink:0; }
        .canvas-area { flex:1; height:100vh; display:flex; flex-direction:column; overflow:hidden; }
        .topbar { height:56px; background:#0d1120; border-bottom:1px solid #1e2536; display:flex; align-items:center; padding:0 1rem; gap:.75rem; flex-shrink:0; }
        .preview-frame { flex:1; overflow-y:auto; padding:1.5rem; }
        .canvas-page { max-width:720px; margin:0 auto; background:#fff; border-radius:12px; min-height:600px; overflow:hidden; box-shadow:0 20px 60px rgba(0,0,0,.5); }
        .form-input { background:#0f1117; border:1px solid #1e2536; border-radius:8px; padding:.55rem .85rem; color:#e2e8f0; font-size:.85rem; width:100%; outline:none; }
        .form-input:focus { border-color:#3b6ff1; }
        .form-label { display:block; font-size:.72rem; font-weight:700; color:#64748b; margin-bottom:.3rem; text-transform:uppercase; letter-spacing:.04em; }
        .btn-primary { background:linear-gradient(135deg,#3b6ff1,#6047ea); color:#fff; border-radius:8px; padding:.5rem 1.1rem; font-weight:700; font-size:.82rem; cursor:pointer; border:none; transition:all .2s; box-shadow:0 4px 12px rgba(59,111,241,.3); }
        .btn-primary:hover { transform:translateY(-1px); }
        .btn-secondary { background:#1e2536; color:#94a3b8; border-radius:8px; padding:.5rem 1.1rem; font-weight:600; font-size:.82rem; cursor:pointer; border:1px solid #2d3748; transition:all .2s; }
        .btn-secondary:hover { background:#252e45; color:#e2e8f0; }
        .section-block { position:relative; border:2px dashed transparent; transition:all .2s; }
        .section-block:hover { border-color:rgba(59,111,241,.4); }
        .section-block.selected { border-color:#3b6ff1; }
        .section-controls { position:absolute; top:-1px; right:-1px; display:none; gap:2px; background:#3b6ff1; border-radius:0 0 0 8px; padding:4px 6px; }
        .section-block:hover .section-controls { display:flex; }
        .section-block.selected .section-controls { display:flex; }
        .sortable-ghost { opacity:.4; background:rgba(59,111,241,.1) !important; border:2px dashed #3b6ff1 !important; }
        .panel-section { border-bottom:1px solid #1e2536; padding:1rem; }
        #toast-container { position:fixed; bottom:1.5rem; right:1.5rem; z-index:9999; display:flex; flex-direction:column; gap:.5rem; }
        .toast { display:flex; align-items:center; gap:.75rem; padding:.75rem 1rem; border-radius:10px; font-size:.82rem; font-weight:600; min-width:220px; animation:slideIn .3s ease; }
        .toast-success { background:#0d2818; border:1px solid rgba(34,197,94,.3); color:#4ade80; }
        .toast-error { background:#280d0d; border:1px solid rgba(239,68,68,.3); color:#f87171; }
        @keyframes slideIn { from { transform:translateX(100%); opacity:0; } to { transform:translateX(0); opacity:1; } }
    </style>
</head>
<body class="flex">

<!-- Left Sidebar: Elements + Settings -->
<div class="sidebar">
    <div class="p-4 border-b border-surface-border flex items-center gap-3">
        <a href="<?= url('/funnels/'.$funnel['id'].'/edit') ?>" class="text-slate-500 hover:text-white transition-colors">
            <i class="fas fa-arrow-left"></i>
        </a>
        <div>
            <div class="font-bold text-white text-sm leading-tight"><?= e($page['title']) ?></div>
            <div class="text-xs text-slate-600">Page Builder</div>
        </div>
    </div>

    <!-- Tabs -->
    <div class="flex border-b border-surface-border">
        <button class="builder-tab flex-1 py-2.5 text-xs font-semibold text-brand-400 border-b-2 border-brand-500 transition-colors" data-tab="elements" onclick="switchTab('elements')">
            <i class="fas fa-th mr-1"></i>Elements
        </button>
        <button class="builder-tab flex-1 py-2.5 text-xs font-semibold text-slate-500 border-b-2 border-transparent transition-colors" data-tab="settings" onclick="switchTab('settings')">
            <i class="fas fa-sliders-h mr-1"></i>Settings
        </button>
    </div>

    <!-- Elements Panel -->
    <div id="tab-elements" class="flex-1 overflow-y-auto p-3">
        <p class="text-xs text-slate-600 font-semibold mb-3 uppercase tracking-wider">Add Section</p>
        <div class="grid grid-cols-2 gap-2">
            <?php
            $elements = [
                ['type'=>'header',  'icon'=>'fa-heading',    'label'=>'Header'],
                ['type'=>'text',    'icon'=>'fa-align-left', 'label'=>'Text'],
                ['type'=>'image',   'icon'=>'fa-image',      'label'=>'Image'],
                ['type'=>'button',  'icon'=>'fa-mouse-pointer','label'=>'Button'],
                ['type'=>'form',    'icon'=>'fa-wpforms',    'label'=>'Form'],
                ['type'=>'divider', 'icon'=>'fa-minus',      'label'=>'Divider'],
                ['type'=>'spacer',  'icon'=>'fa-arrows-alt-v','label'=>'Spacer'],
                ['type'=>'html',    'icon'=>'fa-code',       'label'=>'HTML'],
            ];
            foreach ($elements as $el): ?>
            <button onclick="addSection('<?= $el['type'] ?>')" class="flex flex-col items-center gap-1.5 p-3 rounded-lg border border-surface-border hover:border-brand-600 hover:bg-brand-900/10 text-slate-400 hover:text-brand-400 transition-all text-xs">
                <i class="fas <?= $el['icon'] ?> text-base"></i>
                <span class="font-medium"><?= $el['label'] ?></span>
            </button>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Settings Panel -->
    <div id="tab-settings" class="flex-1 overflow-y-auto hidden">
        <div id="noSelectionMsg" class="p-4 text-center py-12">
            <i class="fas fa-mouse-pointer text-3xl text-slate-700 mb-3 block"></i>
            <p class="text-slate-500 text-sm">Click a section to edit its settings</p>
        </div>
        <div id="settingsPanel" class="hidden"></div>
    </div>

    <!-- Save Button -->
    <div class="p-3 border-t border-surface-border">
        <button onclick="savePage()" class="btn-primary w-full" id="saveBtn">
            <i class="fas fa-save mr-2"></i>Save Page
        </button>
    </div>
</div>

<!-- Canvas -->
<div class="canvas-area">
    <!-- Topbar -->
    <div class="topbar">
        <span class="text-slate-500 text-xs"><i class="fas fa-info-circle mr-1"></i>Drag sections to reorder</span>
        <div class="ml-auto flex gap-2">
            <button onclick="togglePreview()" class="btn-secondary text-xs py-2 px-3" id="previewBtn"><i class="fas fa-eye mr-1"></i>Preview</button>
            <a href="<?= url('/funnel/'.$funnel['slug'].'/page/'.$page['id']) ?>" target="_blank" class="btn-secondary text-xs py-2 px-3"><i class="fas fa-external-link-alt mr-1"></i>Live View</a>
            <button onclick="savePage()" class="btn-primary text-xs py-2 px-3"><i class="fas fa-save mr-1"></i>Save</button>
        </div>
    </div>

    <!-- Preview -->
    <div class="preview-frame" id="previewFrame">
        <div class="canvas-page" id="canvasPage">
            <div id="sectionsContainer">
                <!-- Sections rendered here -->
            </div>
            <div id="dropZone" class="text-center py-16 text-gray-300" style="display:none">
                <i class="fas fa-plus-circle text-4xl text-gray-200 mb-3 block"></i>
                <p class="text-sm text-gray-400">Click elements on the left to add sections</p>
            </div>
        </div>
    </div>
</div>

<!-- Upload Image Modal -->
<div id="uploadModal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4" style="background:rgba(0,0,0,.8)">
    <div class="bg-surface-card w-full max-w-sm p-6 rounded-2xl relative" style="background:#161b27; border:1px solid #1e2536;">
        <button onclick="closeUploadModal()" class="absolute top-4 right-4 text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        <h3 class="font-bold text-white mb-4">Upload Image</h3>
        <div class="border-2 border-dashed border-surface-border rounded-xl p-6 text-center mb-4 hover:border-brand-500 transition-colors" onclick="document.getElementById('imageUploadInput').click()" id="uploadDropZone" style="cursor:pointer">
            <i class="fas fa-cloud-upload-alt text-3xl text-slate-600 mb-2 block"></i>
            <p class="text-slate-500 text-sm">Click to choose image</p>
            <p class="text-xs text-slate-700 mt-1">JPG, PNG, GIF, WEBP — Max 5MB</p>
        </div>
        <input type="file" id="imageUploadInput" class="hidden" accept="image/*" onchange="uploadImage(this)">
        <div id="uploadProgress" class="hidden">
            <div class="flex items-center gap-3 p-3 rounded-lg" style="background:#0f1117">
                <i class="fas fa-spinner fa-spin text-brand-400"></i>
                <span class="text-sm text-slate-300">Uploading...</span>
            </div>
        </div>
    </div>
</div>

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

<script>
const APP_URL  = '<?= APP_URL ?>';
const PAGE_ID  = <?= $page['id'] ?>;
const FORMS    = <?= json_encode($forms) ?>;

let sections = [];
let selectedSectionId = null;
let uploadCallback = null;
let isPreviewing = false;

// ─── Initialize ───────────────────────────────────────────
(function init() {
    const raw = <?= json_encode($page['content'] ?? '[]') ?>;
    try { sections = JSON.parse(raw); } catch(e) { sections = []; }
    if (!Array.isArray(sections)) sections = [];
    renderAll();

    new Sortable(document.getElementById('sectionsContainer'), {
        handle: '.drag-handle-sec',
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: (e) => {
            const moved = sections.splice(e.oldIndex, 1)[0];
            sections.splice(e.newIndex, 0, moved);
        }
    });
})();

function uid() { return 's' + Date.now() + Math.random().toString(36).substr(2,5); }

// ─── Tab Switching ────────────────────────────────────────
function switchTab(tab) {
    document.getElementById('tab-elements').classList.toggle('hidden', tab !== 'elements');
    document.getElementById('tab-settings').classList.toggle('hidden', tab !== 'settings');
    document.querySelectorAll('.builder-tab').forEach(btn => {
        const isActive = btn.dataset.tab === tab;
        btn.classList.toggle('text-brand-400', isActive);
        btn.classList.toggle('border-brand-500', isActive);
        btn.classList.toggle('text-slate-500', !isActive);
        btn.classList.toggle('border-transparent', !isActive);
    });
}

// ─── Add Section ──────────────────────────────────────────
function addSection(type) {
    const defaults = {
        header:  { type:'header',  tag:'h1', text:'Your Headline Here', align:'center', color:'#1a1a2e', bg:'#ffffff', padding:'40px 30px' },
        text:    { type:'text',    text:'Add your text content here. Click to edit.', align:'left', color:'#374151', bg:'#ffffff', padding:'20px 30px', fontSize:'16px' },
        image:   { type:'image',   src:'', alt:'Image', width:'100%', align:'center', bg:'#ffffff', padding:'20px 30px' },
        button:  { type:'button',  text:'Click Here', url:'#', align:'center', bg:'#ffffff', btnBg:'#3b6ff1', btnColor:'#ffffff', padding:'20px 30px', size:'medium' },
        form:    { type:'form',    form_id:'', bg:'#f9fafb', padding:'30px 30px' },
        divider: { type:'divider', color:'#e5e7eb', bg:'#ffffff', padding:'10px 30px' },
        spacer:  { type:'spacer',  height:'40px', bg:'#ffffff' },
        html:    { type:'html',    content:'<p>Custom HTML here</p>', bg:'#ffffff', padding:'20px 30px' },
    };
    const section = { id: uid(), ...defaults[type] };
    sections.push(section);
    renderAll();
    selectSection(section.id);
    switchTab('settings');
    document.getElementById('canvasPage').querySelector('#dropZone')?.style && (document.getElementById('dropZone').style.display = 'none');
}

// ─── Render All ───────────────────────────────────────────
function renderAll() {
    const container = document.getElementById('sectionsContainer');
    container.innerHTML = '';
    if (!sections.length) {
        document.getElementById('dropZone').style.display = 'block';
    } else {
        document.getElementById('dropZone').style.display = 'none';
        sections.forEach(s => {
            const el = document.createElement('div');
            el.className = 'section-block' + (selectedSectionId === s.id ? ' selected' : '');
            el.dataset.id = s.id;
            el.onclick = () => selectSection(s.id);
            el.innerHTML = `
                <div class="section-controls">
                    <button onclick="event.stopPropagation();moveSection('${s.id}',-1)" class="text-white hover:opacity-70 px-1 text-xs" title="Move Up"><i class="fas fa-chevron-up"></i></button>
                    <button onclick="event.stopPropagation();moveSection('${s.id}',1)" class="text-white hover:opacity-70 px-1 text-xs" title="Move Down"><i class="fas fa-chevron-down"></i></button>
                    <span class="drag-handle-sec text-white opacity-70 cursor-grab px-1 text-xs" title="Drag"><i class="fas fa-grip-vertical"></i></span>
                    <button onclick="event.stopPropagation();duplicateSection('${s.id}')" class="text-white hover:opacity-70 px-1 text-xs" title="Duplicate"><i class="fas fa-copy"></i></button>
                    <button onclick="event.stopPropagation();deleteSection('${s.id}')" class="text-white hover:opacity-70 px-1 text-xs" title="Delete"><i class="fas fa-trash"></i></button>
                </div>
                ${renderSectionHTML(s)}`;
            container.appendChild(el);
        });
    }
}

function renderSectionHTML(s) {
    const pad = s.padding || '20px 30px';
    const bg  = s.bg || '#ffffff';
    switch(s.type) {
        case 'header': return `<div style="background:${bg};padding:${pad};text-align:${s.align||'center'}">
            <${s.tag||'h1'} style="color:${s.color||'#1a1a2e'};margin:0;font-family:'Plus Jakarta Sans',sans-serif;font-weight:800;">${escH(s.text)}</${s.tag||'h1'}></div>`;
        case 'text': return `<div style="background:${bg};padding:${pad};text-align:${s.align||'left'}">
            <p style="color:${s.color||'#374151'};margin:0;font-size:${s.fontSize||'16px'};line-height:1.7;">${s.text.replace(/\n/g,'<br>')}</p></div>`;
        case 'image': return `<div style="background:${bg};padding:${pad};text-align:${s.align||'center'}">
            ${s.src ? `<img src="${escH(s.src)}" alt="${escH(s.alt||'')}" style="max-width:${s.width||'100%'};height:auto;border-radius:8px;">` :
            `<div onclick="event.stopPropagation();openUploadModal('${s.id}')" style="border:2px dashed #d1d5db;border-radius:8px;padding:40px;cursor:pointer;background:#f9fafb;color:#9ca3af;text-align:center;">
                <i class="fas fa-image" style="font-size:2rem;display:block;margin-bottom:.5rem;"></i>Click to upload image</div>`}</div>`;
        case 'button': return `<div style="background:${bg};padding:${pad};text-align:${s.align||'center'}">
            <a href="${escH(s.url||'#')}" style="display:inline-block;background:${s.btnBg||'#3b6ff1'};color:${s.btnColor||'#fff'};padding:${s.size==='large'?'16px 40px':s.size==='small'?'8px 20px':'12px 30px'};border-radius:8px;font-weight:700;text-decoration:none;font-size:${s.size==='large'?'18px':s.size==='small'?'13px':'15px'};font-family:sans-serif;">${escH(s.text)}</a></div>`;
        case 'form': {
            const form = FORMS.find(f => f.id == s.form_id);
            return `<div style="background:${bg};padding:${pad}">
                ${form ? `<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:24px;text-align:center;color:#6b7280;font-size:14px;"><i class="fas fa-wpforms" style="font-size:2rem;color:#3b6ff1;display:block;margin-bottom:.5rem;"></i><strong>${escH(form.name)}</strong><br><span style="font-size:12px;">Form embedded here</span></div>` :
                `<div style="background:#f9fafb;border:2px dashed #d1d5db;border-radius:12px;padding:30px;text-align:center;color:#9ca3af;font-size:14px;"><i class="fas fa-wpforms" style="font-size:2rem;display:block;margin-bottom:.5rem;"></i>No form selected — choose in settings</div>`}</div>`;
        }
        case 'divider': return `<div style="background:${bg};padding:${pad}"><hr style="border:none;border-top:1px solid ${s.color||'#e5e7eb'};margin:0;"></div>`;
        case 'spacer': return `<div style="background:${bg};height:${s.height||'40px'}"></div>`;
        case 'html': return `<div style="background:${bg};padding:${pad}">${s.content||''}</div>`;
        default: return `<div style="padding:20px;">Unknown section type: ${s.type}</div>`;
    }
}

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

// ─── Select & Settings ────────────────────────────────────
function selectSection(id) {
    selectedSectionId = id;
    const s = sections.find(x => x.id === id);
    if (!s) return;
    document.querySelectorAll('.section-block').forEach(el => el.classList.toggle('selected', el.dataset.id === id));
    renderSettings(s);
    switchTab('settings');
}

function renderSettings(s) {
    document.getElementById('noSelectionMsg').classList.add('hidden');
    const panel = document.getElementById('settingsPanel');
    panel.classList.remove('hidden');

    const common = `
        <div class="panel-section">
            <p class="form-label mb-1">Background</p>
            <input type="color" value="${s.bg||'#ffffff'}" oninput="updateProp('${s.id}','bg',this.value)" class="w-full h-8 rounded cursor-pointer">
        </div>
        <div class="panel-section">
            <p class="form-label mb-1">Padding</p>
            <input type="text" value="${s.padding||'20px 30px'}" oninput="updateProp('${s.id}','padding',this.value)" class="form-input text-xs">
        </div>`;

    let specific = '';
    switch(s.type) {
        case 'header':
            specific = `<div class="panel-section">
                <p class="form-label mb-1">Heading Text</p>
                <textarea oninput="updateProp('${s.id}','text',this.value)" rows="2" class="form-input text-sm">${s.text||''}</textarea>
            </div>
            <div class="panel-section">
                <p class="form-label mb-1">Tag</p>
                <select onchange="updateProp('${s.id}','tag',this.value)" class="form-input text-sm">
                    ${['h1','h2','h3','h4','p'].map(t=>`<option value="${t}" ${s.tag===t?'selected':''}>${t.toUpperCase()}</option>`).join('')}
                </select>
            </div>
            <div class="panel-section"><p class="form-label mb-1">Text Color</p><input type="color" value="${s.color||'#1a1a2e'}" oninput="updateProp('${s.id}','color',this.value)" class="w-full h-8 rounded cursor-pointer"></div>
            <div class="panel-section"><p class="form-label mb-1">Alignment</p>
                <div class="flex gap-1">${['left','center','right'].map(a=>`<button onclick="updateProp('${s.id}','align','${a}')" class="flex-1 py-1.5 text-xs rounded ${s.align===a?'bg-brand-500 text-white':'bg-surface-border text-slate-400'}">${a}</button>`).join('')}</div></div>`;
            break;
        case 'text':
            specific = `<div class="panel-section"><p class="form-label mb-1">Content</p>
                <textarea oninput="updateProp('${s.id}','text',this.value)" rows="5" class="form-input text-sm">${s.text||''}</textarea></div>
                <div class="panel-section"><p class="form-label mb-1">Font Size</p><input type="text" value="${s.fontSize||'16px'}" oninput="updateProp('${s.id}','fontSize',this.value)" class="form-input text-sm"></div>
                <div class="panel-section"><p class="form-label mb-1">Text Color</p><input type="color" value="${s.color||'#374151'}" oninput="updateProp('${s.id}','color',this.value)" class="w-full h-8 rounded cursor-pointer"></div>
                <div class="panel-section"><p class="form-label mb-1">Alignment</p><div class="flex gap-1">${['left','center','right'].map(a=>`<button onclick="updateProp('${s.id}','align','${a}')" class="flex-1 py-1.5 text-xs rounded ${s.align===a?'bg-brand-500 text-white':'bg-surface-border text-slate-400'}">${a}</button>`).join('')}</div></div>`;
            break;
        case 'image':
            specific = `<div class="panel-section"><p class="form-label mb-1">Image</p>
                ${s.src ? `<img src="${escH(s.src)}" class="w-full rounded-lg mb-2 object-cover" style="max-height:120px;">` : ''}
                <button onclick="openUploadModal('${s.id}')" class="btn-secondary w-full text-xs py-2"><i class="fas fa-upload mr-1"></i>Upload Image</button>
                ${s.src ? `<button onclick="updateProp('${s.id}','src','')" class="btn-secondary w-full text-xs py-1.5 mt-1 text-red-400">Remove Image</button>` : ''}
            </div>
            <div class="panel-section"><p class="form-label mb-1">Width</p><input type="text" value="${s.width||'100%'}" oninput="updateProp('${s.id}','width',this.value)" class="form-input text-sm"></div>
            <div class="panel-section"><p class="form-label mb-1">Alt Text</p><input type="text" value="${s.alt||''}" oninput="updateProp('${s.id}','alt',this.value)" class="form-input text-sm"></div>
            <div class="panel-section"><p class="form-label mb-1">Alignment</p><div class="flex gap-1">${['left','center','right'].map(a=>`<button onclick="updateProp('${s.id}','align','${a}')" class="flex-1 py-1.5 text-xs rounded ${s.align===a?'bg-brand-500 text-white':'bg-surface-border text-slate-400'}">${a}</button>`).join('')}</div></div>`;
            break;
        case 'button':
            specific = `<div class="panel-section"><p class="form-label mb-1">Button Text</p><input type="text" value="${s.text||''}" oninput="updateProp('${s.id}','text',this.value)" class="form-input text-sm"></div>
                <div class="panel-section"><p class="form-label mb-1">URL</p><input type="text" value="${s.url||''}" oninput="updateProp('${s.id}','url',this.value)" class="form-input text-sm" placeholder="https://..."></div>
                <div class="panel-section"><p class="form-label mb-1">Size</p><div class="flex gap-1">${['small','medium','large'].map(sz=>`<button onclick="updateProp('${s.id}','size','${sz}')" class="flex-1 py-1.5 text-xs rounded ${s.size===sz?'bg-brand-500 text-white':'bg-surface-border text-slate-400'}">${sz}</button>`).join('')}</div></div>
                <div class="panel-section"><p class="form-label mb-1">Button Color</p><input type="color" value="${s.btnBg||'#3b6ff1'}" oninput="updateProp('${s.id}','btnBg',this.value)" class="w-full h-8 rounded cursor-pointer"></div>
                <div class="panel-section"><p class="form-label mb-1">Text Color</p><input type="color" value="${s.btnColor||'#ffffff'}" oninput="updateProp('${s.id}','btnColor',this.value)" class="w-full h-8 rounded cursor-pointer"></div>
                <div class="panel-section"><p class="form-label mb-1">Alignment</p><div class="flex gap-1">${['left','center','right'].map(a=>`<button onclick="updateProp('${s.id}','align','${a}')" class="flex-1 py-1.5 text-xs rounded ${s.align===a?'bg-brand-500 text-white':'bg-surface-border text-slate-400'}">${a}</button>`).join('')}</div></div>`;
            break;
        case 'form':
            specific = `<div class="panel-section"><p class="form-label mb-1">Select Form</p>
                <select onchange="updateProp('${s.id}','form_id',this.value)" class="form-input text-sm">
                    <option value="">— No form —</option>
                    ${FORMS.map(f=>`<option value="${f.id}" ${s.form_id==f.id?'selected':''}>${f.name}</option>`).join('')}
                </select></div>`;
            break;
        case 'divider':
            specific = `<div class="panel-section"><p class="form-label mb-1">Line Color</p><input type="color" value="${s.color||'#e5e7eb'}" oninput="updateProp('${s.id}','color',this.value)" class="w-full h-8 rounded cursor-pointer"></div>`;
            break;
        case 'spacer':
            specific = `<div class="panel-section"><p class="form-label mb-1">Height</p><input type="text" value="${s.height||'40px'}" oninput="updateProp('${s.id}','height',this.value)" class="form-input text-sm" placeholder="40px"></div>`;
            break;
        case 'html':
            specific = `<div class="panel-section"><p class="form-label mb-1">HTML Content</p><textarea oninput="updateProp('${s.id}','content',this.value)" rows="8" class="form-input text-xs font-mono">${s.content||''}</textarea></div>`;
            break;
    }

    panel.innerHTML = `<div class="p-3 border-b border-surface-border flex items-center gap-2">
        <span class="text-xs font-bold text-white uppercase">${s.type}</span>
        <span class="text-xs text-slate-600">Section</span>
        <button onclick="deleteSection('${s.id}')" class="ml-auto text-red-400 hover:text-red-300 text-xs px-2 py-1 rounded hover:bg-red-900/20"><i class="fas fa-trash mr-1"></i>Delete</button>
    </div>${specific}${common}`;
}

function updateProp(id, key, value) {
    const s = sections.find(x => x.id === id);
    if (!s) return;
    s[key] = value;
    renderAll();
    if (selectedSectionId === id) {
        renderSettings(s);
        selectSection(id);
    }
}

function moveSection(id, dir) {
    const idx = sections.findIndex(x => x.id === id);
    if (idx < 0) return;
    const newIdx = idx + dir;
    if (newIdx < 0 || newIdx >= sections.length) return;
    [sections[idx], sections[newIdx]] = [sections[newIdx], sections[idx]];
    renderAll();
}

function duplicateSection(id) {
    const idx = sections.findIndex(x => x.id === id);
    if (idx < 0) return;
    const copy = JSON.parse(JSON.stringify(sections[idx]));
    copy.id = uid();
    sections.splice(idx + 1, 0, copy);
    renderAll();
    showToast('Section duplicated', 'success');
}

function deleteSection(id) {
    sections = sections.filter(x => x.id !== id);
    if (selectedSectionId === id) {
        selectedSectionId = null;
        document.getElementById('settingsPanel').classList.add('hidden');
        document.getElementById('noSelectionMsg').classList.remove('hidden');
    }
    renderAll();
}

// ─── Image Upload ─────────────────────────────────────────
function openUploadModal(sectionId) {
    uploadCallback = sectionId;
    document.getElementById('uploadModal').classList.remove('hidden');
}
function closeUploadModal() {
    document.getElementById('uploadModal').classList.add('hidden');
    document.getElementById('imageUploadInput').value = '';
    document.getElementById('uploadProgress').classList.add('hidden');
}

async function uploadImage(input) {
    const file = input.files[0];
    if (!file) return;
    document.getElementById('uploadProgress').classList.remove('hidden');
    const fd = new FormData();
    fd.append('image', file);
    try {
        const resp = await fetch(APP_URL + '/landing/upload-image', { method:'POST', body:fd });
        const data = await resp.json();
        if (data.success) {
            updateProp(uploadCallback, 'src', data.url);
            closeUploadModal();
            showToast('Image uploaded!', 'success');
        } else {
            showToast(data.message || 'Upload failed.', 'error');
            document.getElementById('uploadProgress').classList.add('hidden');
        }
    } catch(e) {
        showToast('Upload error.', 'error');
        document.getElementById('uploadProgress').classList.add('hidden');
    }
}

// ─── Save Page ────────────────────────────────────────────
async function savePage() {
    const btn = document.getElementById('saveBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Saving...';

    const resp = await fetch(APP_URL + '/landing/save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ page_id: PAGE_ID, content: sections })
    });
    const data = await resp.json();
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Page';
    if (data.success) showToast(data.message || 'Saved!', 'success');
    else showToast(data.message || 'Error saving.', 'error');
}

// ─── Preview Toggle ───────────────────────────────────────
function togglePreview() {
    isPreviewing = !isPreviewing;
    document.querySelectorAll('.section-controls').forEach(el => el.style.display = isPreviewing ? 'none' : '');
    document.querySelectorAll('.section-block').forEach(el => {
        el.style.pointerEvents = isPreviewing ? 'none' : '';
        el.classList.toggle('border-none', isPreviewing);
    });
    document.getElementById('previewBtn').innerHTML = isPreviewing ? '<i class="fas fa-edit mr-1"></i>Edit Mode' : '<i class="fas fa-eye mr-1"></i>Preview';
}

function showToast(message, type = 'success') {
    const container = document.getElementById('toast-container');
    const icons = { success:'fa-check-circle', error:'fa-times-circle', info:'fa-info-circle' };
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<i class="fas ${icons[type]||icons.info}"></i><span>${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => { toast.style.animation='slideOut .3s ease forwards'; setTimeout(()=>toast.remove(),300); }, 3500);
}

document.getElementById('uploadModal').addEventListener('click', function(e) { if(e.target===this) closeUploadModal(); });
</script>
</body>
</html>
