/**
 * Template Builder Core
 * Main application logic for drag-and-drop template builder
 */

class TemplateBuilderApp {
    constructor(options) {
        this.templateId = options.templateId || 0;
        this.templateData = options.templateData || {};
        this.apiUrl = options.apiUrl;
        this.themeMode = options.themeMode || 'light';

        this.structure = this.templateData.template_structure || {
            sections: [],
            layout_type: 'flex',
            max_width: 1200
        };

        this.components = [];
        this.selectedElement = null;
        this.draggedElement = null;
        this.history = [];
        this.historyIndex = -1;
        this.autoSaveTimeout = null;

        this.init();
    }

    /**
     * Initialize the application
     */
    init() {
        this.loadComponents();
        this.setupEventListeners();
        this.render();
        this.addToHistory();
    }

    /**
     * Load available components from API
     */
    async loadComponents() {
        try {
            const response = await fetch(`${this.apiUrl}?action=get_components`);
            const data = await response.json();

            if (data.success) {
                this.components = data.components;
                this.renderComponentsList();
            }
        } catch (error) {
            console.error('Failed to load components:', error);
            this.showNotification('Failed to load components', 'error');
        }
    }

    /**
     * Render components list in sidebar
     */
    renderComponentsList() {
        const container = document.getElementById('components-list');
        container.innerHTML = '';

        const activeCategory = document.querySelector('.tb-category-btn.active').dataset.category;

        const filteredComponents = activeCategory === 'all'
            ? this.components
            : this.components.filter(c => c.component_category === activeCategory);

        if (filteredComponents.length === 0) {
            container.innerHTML = '<div class="tb-loading">No components found</div>';
            return;
        }

        filteredComponents.forEach(component => {
            const item = this.createComponentItem(component);
            container.appendChild(item);
        });
    }

    /**
     * Create component list item element
     */
    createComponentItem(component) {
        const div = document.createElement('div');
        div.className = 'tb-component-item';
        div.draggable = true;
        div.dataset.component = component.component_slug;

        div.innerHTML = `
            <div class="tb-component-thumb">
                ${component.thumbnail
                    ? `<img src="${component.thumbnail}" alt="${component.component_name}" />`
                    : `<i class="icon-${this.getCategoryIcon(component.component_category)}"></i>`
                }
            </div>
            <h4 class="tb-component-name">${component.component_name}</h4>
            <p class="tb-component-desc">${component.description || ''}</p>
        `;

        // Drag events
        div.addEventListener('dragstart', (e) => this.onComponentDragStart(e, component));
        div.addEventListener('dragend', (e) => this.onComponentDragEnd(e));

        return div;
    }

    /**
     * Get icon for component category
     */
    getCategoryIcon(category) {
        const icons = {
            header: 'menu',
            hero: 'image',
            video_grid: 'grid',
            video_list: 'list',
            sidebar: 'sidebar',
            text: 'text',
            image: 'picture',
            custom: 'code'
        };
        return icons[category] || 'box';
    }

    /**
     * Setup all event listeners
     */
    setupEventListeners() {
        // Header buttons
        document.getElementById('tb-back-btn').addEventListener('click', () => this.goBack());
        document.getElementById('tb-save-btn').addEventListener('click', () => this.save());
        document.getElementById('tb-publish-btn').addEventListener('click', () => this.publish());
        document.getElementById('tb-preview-btn').addEventListener('click', () => this.preview());
        document.getElementById('tb-undo-btn').addEventListener('click', () => this.undo());
        document.getElementById('tb-redo-btn').addEventListener('click', () => this.redo());

        // Template name
        document.getElementById('tb-template-name').addEventListener('change', (e) => {
            this.templateData.template_name = e.target.value;
            this.scheduleAutoSave();
        });

        // Device preview buttons
        document.querySelectorAll('.tb-device-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.switchDevice(e.target.closest('.tb-device-btn').dataset.device));
        });

        // Category buttons
        document.querySelectorAll('.tb-category-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.switchCategory(e.target));
        });

        // Component search
        document.getElementById('component-search').addEventListener('input', (e) => {
            this.searchComponents(e.target.value);
        });

        // Canvas drop zone
        const canvas = document.getElementById('builder-canvas');
        canvas.addEventListener('dragover', (e) => this.onCanvasDragOver(e));
        canvas.addEventListener('drop', (e) => this.onCanvasDrop(e));

        // Zoom controls
        document.getElementById('zoom-in').addEventListener('click', () => this.zoom(0.1));
        document.getElementById('zoom-out').addEventListener('click', () => this.zoom(-0.1));
        document.getElementById('zoom-fit').addEventListener('click', () => this.zoomFit());

        // Grid toggle
        document.getElementById('show-grid').addEventListener('change', (e) => {
            canvas.classList.toggle('show-grid', e.target.checked);
        });

        // Modal close buttons
        document.querySelectorAll('[data-modal-close]').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const modalId = e.target.closest('[data-modal-close]').dataset.modalClose ||
                               e.target.closest('.tb-modal').id;
                this.closeModal(modalId);
            });
        });

        // Page settings
        document.getElementById('template-type').addEventListener('change', (e) => {
            this.structure.template_type = e.target.value;
            this.addToHistory();
        });

        document.getElementById('page-max-width').addEventListener('change', (e) => {
            this.structure.max_width = parseInt(e.target.value);
            this.render();
            this.addToHistory();
        });

        document.getElementById('page-layout-type').addEventListener('change', (e) => {
            this.structure.layout_type = e.target.value;
            this.render();
            this.addToHistory();
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => this.handleKeyboard(e));
    }

    /**
     * Handle component drag start
     */
    onComponentDragStart(e, component) {
        this.draggedElement = {
            type: 'component',
            data: component
        };

        e.dataTransfer.effectAllowed = 'copy';
        e.dataTransfer.setData('text/plain', component.component_slug);

        e.target.classList.add('dragging');
    }

    /**
     * Handle component drag end
     */
    onComponentDragEnd(e) {
        e.target.classList.remove('dragging');
        this.draggedElement = null;

        // Remove all drag-over classes
        document.querySelectorAll('.drag-over').forEach(el => {
            el.classList.remove('drag-over');
        });
    }

    /**
     * Handle canvas drag over
     */
    onCanvasDragOver(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';

        // Find the nearest section or create indicator for new section
        const target = e.target.closest('.tb-section') || e.target.closest('.tb-canvas');

        if (target.classList.contains('tb-section')) {
            target.classList.add('drag-over');
        }
    }

    /**
     * Handle canvas drop
     */
    onCanvasDrop(e) {
        e.preventDefault();

        if (!this.draggedElement) return;

        const dropTarget = e.target.closest('.tb-section');

        if (this.draggedElement.type === 'component') {
            if (dropTarget) {
                // Add to existing section
                this.addComponentToSection(dropTarget.dataset.sectionId, this.draggedElement.data);
            } else {
                // Create new section with component
                this.addNewSection(this.draggedElement.data);
            }

            this.render();
            this.addToHistory();
            this.scheduleAutoSave();
        }

        // Clean up
        document.querySelectorAll('.drag-over').forEach(el => {
            el.classList.remove('drag-over');
        });
    }

    /**
     * Add new section with optional component
     */
    addNewSection(component = null) {
        const section = {
            id: 'section-' + Date.now(),
            columns: 1,
            gap: 20,
            blocks: [],
            styles: {}
        };

        if (component) {
            section.blocks.push(this.createBlock(component));
        }

        this.structure.sections.push(section);

        // Hide drop hint
        document.getElementById('drop-hint').classList.add('hidden');
    }

    /**
     * Add component to existing section
     */
    addComponentToSection(sectionId, component) {
        const section = this.structure.sections.find(s => s.id === sectionId);

        if (section) {
            section.blocks.push(this.createBlock(component));
        }
    }

    /**
     * Create block from component
     */
    createBlock(component) {
        const settings = {};

        // Initialize with default values from schema
        if (component.component_settings_schema) {
            Object.entries(component.component_settings_schema).forEach(([key, schema]) => {
                settings[key] = schema.default;
            });
        }

        return {
            id: 'block-' + Date.now(),
            component: component.component_slug,
            settings: settings
        };
    }

    /**
     * Render the entire canvas
     */
    render() {
        const container = document.getElementById('sections-container');
        container.innerHTML = '';

        this.structure.sections.forEach(section => {
            const sectionEl = this.renderSection(section);
            container.appendChild(sectionEl);
        });

        // Show/hide drop hint
        const dropHint = document.getElementById('drop-hint');
        dropHint.classList.toggle('hidden', this.structure.sections.length > 0);

        // Update canvas max-width
        const canvas = document.getElementById('builder-canvas');
        const canvasContainer = canvas.querySelector('.tb-sections-container');
        if (canvasContainer) {
            canvasContainer.style.maxWidth = this.structure.max_width + 'px';
        }
    }

    /**
     * Render a section
     */
    renderSection(section) {
        const div = document.createElement('div');
        div.className = 'tb-section';
        div.dataset.sectionId = section.id;

        // Apply styles
        if (section.styles) {
            Object.entries(section.styles).forEach(([key, value]) => {
                div.style[key] = value;
            });
        }

        // Create controls
        const controls = document.createElement('div');
        controls.className = 'tb-section-controls';
        controls.innerHTML = `
            <button class="tb-btn tb-btn-icon tb-btn-sm" data-action="move-up" title="Move Up">
                <i class="icon-arrow-up"></i>
            </button>
            <button class="tb-btn tb-btn-icon tb-btn-sm" data-action="move-down" title="Move Down">
                <i class="icon-arrow-down"></i>
            </button>
            <button class="tb-btn tb-btn-icon tb-btn-sm" data-action="duplicate" title="Duplicate">
                <i class="icon-copy"></i>
            </button>
            <button class="tb-btn tb-btn-icon tb-btn-sm tb-btn-danger" data-action="delete" title="Delete">
                <i class="icon-trash"></i>
            </button>
        `;

        controls.querySelectorAll('button').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.handleSectionAction(section.id, btn.dataset.action);
            });
        });

        div.appendChild(controls);

        // Create columns container
        const columns = document.createElement('div');
        columns.className = 'tb-columns';
        columns.style.gridTemplateColumns = `repeat(${section.columns}, 1fr)`;
        columns.style.gap = section.gap + 'px';

        // Render blocks
        section.blocks.forEach(block => {
            const blockEl = this.renderBlock(block, section.id);
            columns.appendChild(blockEl);
        });

        div.appendChild(columns);

        // Click to select
        div.addEventListener('click', (e) => {
            if (e.target === div || e.target.className === 'tb-columns') {
                this.selectElement('section', section.id);
            }
        });

        // Drag over for reordering
        div.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
        });

        div.addEventListener('drop', (e) => {
            e.stopPropagation();
        });

        return div;
    }

    /**
     * Render a block
     */
    renderBlock(block, sectionId) {
        const component = this.components.find(c => c.component_slug === block.component);

        if (!component) {
            const div = document.createElement('div');
            div.className = 'tb-block';
            div.innerHTML = `<p>Component "${block.component}" not found</p>`;
            return div;
        }

        const div = document.createElement('div');
        div.className = 'tb-block';
        div.dataset.blockId = block.id;
        div.dataset.sectionId = sectionId;
        div.dataset.component = block.component;

        // Render component preview
        const preview = document.createElement('div');
        preview.className = 'tb-block-preview';
        preview.innerHTML = this.renderComponentPreview(component, block.settings);
        div.appendChild(preview);

        // Create controls
        const controls = document.createElement('div');
        controls.className = 'tb-block-controls';
        controls.innerHTML = `
            <button class="tb-btn tb-btn-icon tb-btn-sm" data-action="edit" title="Edit">
                <i class="icon-edit"></i>
            </button>
            <button class="tb-btn tb-btn-icon tb-btn-sm" data-action="duplicate" title="Duplicate">
                <i class="icon-copy"></i>
            </button>
            <button class="tb-btn tb-btn-icon tb-btn-sm tb-btn-danger" data-action="delete" title="Delete">
                <i class="icon-trash"></i>
            </button>
        `;

        controls.querySelectorAll('button').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.handleBlockAction(sectionId, block.id, btn.dataset.action);
            });
        });

        div.appendChild(controls);

        // Click to select
        div.addEventListener('click', (e) => {
            e.stopPropagation();
            this.selectElement('block', block.id, sectionId);
        });

        return div;
    }

    /**
     * Render component preview (simplified)
     */
    renderComponentPreview(component, settings) {
        // This is a simplified preview - real implementation would parse the template
        return `
            <div class="component-preview" style="padding: 20px; background: #f9fafb; border-radius: 4px;">
                <strong>${component.component_name}</strong>
                <p style="margin: 5px 0 0; font-size: 12px; color: #666;">${component.description || ''}</p>
            </div>
        `;
    }

    /**
     * Handle section actions
     */
    handleSectionAction(sectionId, action) {
        const index = this.structure.sections.findIndex(s => s.id === sectionId);

        if (index === -1) return;

        switch (action) {
            case 'move-up':
                if (index > 0) {
                    [this.structure.sections[index], this.structure.sections[index - 1]] =
                    [this.structure.sections[index - 1], this.structure.sections[index]];
                }
                break;

            case 'move-down':
                if (index < this.structure.sections.length - 1) {
                    [this.structure.sections[index], this.structure.sections[index + 1]] =
                    [this.structure.sections[index + 1], this.structure.sections[index]];
                }
                break;

            case 'duplicate':
                const copy = JSON.parse(JSON.stringify(this.structure.sections[index]));
                copy.id = 'section-' + Date.now();
                this.structure.sections.splice(index + 1, 0, copy);
                break;

            case 'delete':
                if (confirm('Delete this section?')) {
                    this.structure.sections.splice(index, 1);
                }
                break;
        }

        this.render();
        this.addToHistory();
        this.scheduleAutoSave();
    }

    /**
     * Handle block actions
     */
    handleBlockAction(sectionId, blockId, action) {
        const section = this.structure.sections.find(s => s.id === sectionId);
        if (!section) return;

        const index = section.blocks.findIndex(b => b.id === blockId);
        if (index === -1) return;

        switch (action) {
            case 'edit':
                this.selectElement('block', blockId, sectionId);
                break;

            case 'duplicate':
                const copy = JSON.parse(JSON.stringify(section.blocks[index]));
                copy.id = 'block-' + Date.now();
                section.blocks.splice(index + 1, 0, copy);
                break;

            case 'delete':
                if (confirm('Delete this component?')) {
                    section.blocks.splice(index, 1);
                }
                break;
        }

        this.render();
        this.addToHistory();
        this.scheduleAutoSave();
    }

    /**
     * Select element (section or block)
     */
    selectElement(type, id, sectionId = null) {
        // Deselect previous
        document.querySelectorAll('.tb-section.selected, .tb-block.selected').forEach(el => {
            el.classList.remove('selected');
        });

        this.selectedElement = {type, id, sectionId};

        // Update UI
        const element = type === 'section'
            ? document.querySelector(`.tb-section[data-section-id="${id}"]`)
            : document.querySelector(`.tb-block[data-block-id="${id}"]`);

        if (element) {
            element.classList.add('selected');
        }

        this.showProperties();
    }

    /**
     * Show properties panel for selected element
     */
    showProperties() {
        // Hide all property sections
        document.getElementById('no-selection').style.display = 'none';
        document.getElementById('page-settings').style.display = 'none';
        document.getElementById('component-settings').style.display = 'none';
        document.getElementById('section-settings').style.display = 'none';

        if (!this.selectedElement) {
            document.getElementById('no-selection').style.display = 'block';
            return;
        }

        if (this.selectedElement.type === 'section') {
            this.showSectionProperties();
        } else if (this.selectedElement.type === 'block') {
            this.showComponentProperties();
        }
    }

    /**
     * Show section properties
     */
    showSectionProperties() {
        const section = this.structure.sections.find(s => s.id === this.selectedElement.id);
        if (!section) return;

        document.getElementById('section-settings').style.display = 'block';

        // Set values
        document.getElementById('section-columns').value = section.columns || 1;
        document.getElementById('section-gap').value = section.gap || 20;

        // Event listeners (remove old ones first)
        const columnsInput = document.getElementById('section-columns');
        const gapInput = document.getElementById('section-gap');

        columnsInput.onchange = (e) => {
            section.columns = parseInt(e.target.value);
            this.render();
            this.addToHistory();
        };

        gapInput.onchange = (e) => {
            section.gap = parseInt(e.target.value);
            this.render();
            this.addToHistory();
        };

        // Delete button
        document.getElementById('delete-section').onclick = () => {
            this.handleSectionAction(section.id, 'delete');
            this.selectedElement = null;
            this.showProperties();
        };
    }

    /**
     * Show component properties
     */
    showComponentProperties() {
        const section = this.structure.sections.find(s => s.id === this.selectedElement.sectionId);
        if (!section) return;

        const block = section.blocks.find(b => b.id === this.selectedElement.id);
        if (!block) return;

        const component = this.components.find(c => c.component_slug === block.component);
        if (!component) return;

        document.getElementById('component-settings').style.display = 'block';
        document.getElementById('selected-component-name').textContent = component.component_name;

        // Render settings fields
        const fieldsContainer = document.getElementById('component-settings-fields');
        fieldsContainer.innerHTML = '';

        if (component.component_settings_schema) {
            Object.entries(component.component_settings_schema).forEach(([key, schema]) => {
                const field = this.createSettingField(key, schema, block.settings[key]);
                fieldsContainer.appendChild(field);

                // Update on change
                const input = field.querySelector('input, select, textarea');
                if (input) {
                    input.addEventListener('change', (e) => {
                        block.settings[key] = this.getInputValue(e.target, schema.type);
                        this.render();
                        this.addToHistory();
                        this.scheduleAutoSave();
                    });
                }
            });
        }

        // Delete button
        document.getElementById('delete-component').onclick = () => {
            this.handleBlockAction(section.id, block.id, 'delete');
            this.selectedElement = null;
            this.showProperties();
        };
    }

    /**
     * Create setting field based on schema
     */
    createSettingField(key, schema, value) {
        const div = document.createElement('div');
        div.className = 'tb-form-group';

        const label = document.createElement('label');
        label.textContent = this.formatLabel(key);
        div.appendChild(label);

        let input;

        switch (schema.type) {
            case 'number':
                input = document.createElement('input');
                input.type = 'number';
                input.className = 'tb-input';
                input.value = value ?? schema.default ?? 0;
                if (schema.min !== undefined) input.min = schema.min;
                if (schema.max !== undefined) input.max = schema.max;
                if (schema.step !== undefined) input.step = schema.step;
                break;

            case 'text':
                input = document.createElement('input');
                input.type = 'text';
                input.className = 'tb-input';
                input.value = value ?? schema.default ?? '';
                break;

            case 'textarea':
                input = document.createElement('textarea');
                input.className = 'tb-textarea';
                input.value = value ?? schema.default ?? '';
                input.rows = 4;
                break;

            case 'color':
                input = document.createElement('input');
                input.type = 'color';
                input.className = 'tb-input';
                input.value = value ?? schema.default ?? '#000000';
                break;

            case 'boolean':
                const checkboxLabel = document.createElement('label');
                checkboxLabel.className = 'tb-checkbox';
                input = document.createElement('input');
                input.type = 'checkbox';
                input.checked = value ?? schema.default ?? false;
                const span = document.createElement('span');
                span.textContent = 'Enable';
                checkboxLabel.appendChild(input);
                checkboxLabel.appendChild(span);
                div.removeChild(label);
                div.appendChild(checkboxLabel);
                return div;

            case 'select':
                input = document.createElement('select');
                input.className = 'tb-select';
                if (schema.options) {
                    schema.options.forEach(option => {
                        const opt = document.createElement('option');
                        opt.value = option;
                        opt.textContent = this.formatLabel(option);
                        if (option === (value ?? schema.default)) opt.selected = true;
                        input.appendChild(opt);
                    });
                }
                break;

            default:
                input = document.createElement('input');
                input.type = 'text';
                input.className = 'tb-input';
                input.value = value ?? schema.default ?? '';
        }

        div.appendChild(input);
        return div;
    }

    /**
     * Format label from key
     */
    formatLabel(key) {
        return key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
    }

    /**
     * Get input value based on type
     */
    getInputValue(input, type) {
        switch (type) {
            case 'number':
                return parseFloat(input.value) || 0;
            case 'boolean':
                return input.checked;
            default:
                return input.value;
        }
    }

    /**
     * Switch device preview
     */
    switchDevice(device) {
        document.querySelectorAll('.tb-device-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.device === device);
        });

        document.getElementById('builder-canvas').dataset.device = device;
    }

    /**
     * Switch component category
     */
    switchCategory(button) {
        document.querySelectorAll('.tb-category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        button.classList.add('active');

        this.renderComponentsList();
    }

    /**
     * Search components
     */
    searchComponents(query) {
        const items = document.querySelectorAll('.tb-component-item');
        const lowerQuery = query.toLowerCase();

        items.forEach(item => {
            const name = item.querySelector('.tb-component-name').textContent.toLowerCase();
            const desc = item.querySelector('.tb-component-desc').textContent.toLowerCase();
            const matches = name.includes(lowerQuery) || desc.includes(lowerQuery);
            item.style.display = matches ? '' : 'none';
        });
    }

    /**
     * Add current state to history
     */
    addToHistory() {
        // Remove any history after current index
        this.history = this.history.slice(0, this.historyIndex + 1);

        // Add new state
        const state = JSON.parse(JSON.stringify(this.structure));
        this.history.push(state);
        this.historyIndex++;

        // Limit history to 50 states
        if (this.history.length > 50) {
            this.history.shift();
            this.historyIndex--;
        }

        this.updateHistoryButtons();
    }

    /**
     * Undo
     */
    undo() {
        if (this.historyIndex > 0) {
            this.historyIndex--;
            this.structure = JSON.parse(JSON.stringify(this.history[this.historyIndex]));
            this.render();
            this.updateHistoryButtons();
        }
    }

    /**
     * Redo
     */
    redo() {
        if (this.historyIndex < this.history.length - 1) {
            this.historyIndex++;
            this.structure = JSON.parse(JSON.stringify(this.history[this.historyIndex]));
            this.render();
            this.updateHistoryButtons();
        }
    }

    /**
     * Update history buttons state
     */
    updateHistoryButtons() {
        document.getElementById('tb-undo-btn').disabled = this.historyIndex <= 0;
        document.getElementById('tb-redo-btn').disabled = this.historyIndex >= this.history.length - 1;
    }

    /**
     * Schedule auto save
     */
    scheduleAutoSave() {
        if (this.autoSaveTimeout) {
            clearTimeout(this.autoSaveTimeout);
        }

        this.autoSaveTimeout = setTimeout(() => {
            this.save(true);
        }, 3000);
    }

    /**
     * Save template
     */
    async save(isAutoSave = false) {
        const templateName = document.getElementById('tb-template-name').value;

        if (!templateName && !isAutoSave) {
            this.showNotification('Please enter a template name', 'error');
            return;
        }

        const data = {
            action: this.templateId ? 'update_template' : 'create_template',
            template_id: this.templateId,
            template_name: templateName,
            template_structure: JSON.stringify(this.structure),
            template_type: document.getElementById('template-type').value
        };

        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                if (result.template_id && !this.templateId) {
                    this.templateId = result.template_id;
                    document.getElementById('template-id').value = result.template_id;
                }

                if (!isAutoSave) {
                    this.showNotification('Template saved successfully', 'success');
                }
            } else {
                this.showNotification(result.error || 'Failed to save template', 'error');
            }
        } catch (error) {
            console.error('Save error:', error);
            this.showNotification('Failed to save template', 'error');
        }
    }

    /**
     * Publish template
     */
    async publish() {
        if (!this.templateId) {
            await this.save();
        }

        const data = {
            action: 'publish_template',
            template_id: this.templateId
        };

        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                this.showNotification('Template published successfully', 'success');
            } else {
                this.showNotification(result.error || 'Failed to publish template', 'error');
            }
        } catch (error) {
            console.error('Publish error:', error);
            this.showNotification('Failed to publish template', 'error');
        }
    }

    /**
     * Preview template
     */
    preview() {
        const modal = document.getElementById('preview-modal');
        const iframe = document.getElementById('preview-iframe');

        // Generate preview URL
        const previewUrl = `${this.apiUrl}?action=preview&template_id=${this.templateId}`;
        iframe.src = previewUrl;

        modal.style.display = 'block';
    }

    /**
     * Close modal
     */
    closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }

    /**
     * Go back
     */
    goBack() {
        if (confirm('Are you sure you want to leave? Any unsaved changes will be lost.')) {
            window.location.href = '/account.php?s=templates';
        }
    }

    /**
     * Handle keyboard shortcuts
     */
    handleKeyboard(e) {
        // Ctrl/Cmd + S - Save
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            this.save();
        }

        // Ctrl/Cmd + Z - Undo
        if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
            e.preventDefault();
            this.undo();
        }

        // Ctrl/Cmd + Shift + Z - Redo
        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z') {
            e.preventDefault();
            this.redo();
        }

        // Delete - Delete selected element
        if (e.key === 'Delete' && this.selectedElement) {
            e.preventDefault();
            if (this.selectedElement.type === 'section') {
                this.handleSectionAction(this.selectedElement.id, 'delete');
            } else if (this.selectedElement.type === 'block') {
                this.handleBlockAction(this.selectedElement.sectionId, this.selectedElement.id, 'delete');
            }
            this.selectedElement = null;
            this.showProperties();
        }
    }

    /**
     * Zoom
     */
    zoom(delta) {
        // Implement zoom functionality
        console.log('Zoom:', delta);
    }

    /**
     * Zoom to fit
     */
    zoomFit() {
        // Implement zoom to fit
        console.log('Zoom fit');
    }

    /**
     * Show notification
     */
    showNotification(message, type = 'info') {
        // Simple notification - can be replaced with better UI
        alert(message);
    }
}
