/**
 * Editor - Handles all content types with style-aware approach
 */
import { StyleAwareEditor } from './style-aware-editor.js';

export class Editor {
    constructor() {
        this.currentOverlay = null;
        this.currentStyleEditor = null;
    }

    /**
     * Edit any content element with style-aware interface
     * @param {Object} meta - Element metadata {element, contentId, contentType}
     * @param {string|Object} currentContent - Current content value
     * @param {Function} onSave - Save callback
     * @param {Function} onCancel - Cancel callback
     */
    async edit(meta, currentContent, onSave, onCancel) {
        const { element } = meta;
        
        // Handle both single elements and groups uniformly
        const elements = Array.isArray(element) ? element : [element];
        const primaryElement = elements[0];
        
        // Close any existing editor
        this.close();
        
        try {
            // Create style-aware editor
            const styleEditor = new StyleAwareEditor(primaryElement, {
                onSave: (content) => {
                    onSave(content);
                    this.close();
                },
                onCancel: () => {
                    onCancel();
                    this.close();
                },
                onChange: (content) => {
                    // Optional: trigger change events if needed
                }
            });
            
            // Initialize the editor
            await styleEditor.initialize();
            
            // Create overlay and position
            const editorElement = styleEditor.getEditorElement();
            const overlay = this.createOverlay(editorElement);
            
            // Position relative to primary element
            this.positionForm(primaryElement, overlay);
            
            // Show editor
            document.body.appendChild(overlay);
            this.currentOverlay = overlay;
            this.currentStyleEditor = styleEditor;
            
            // Focus first input
            const firstInput = editorElement.querySelector('textarea, input[type="text"], [contenteditable="true"]');
            if (firstInput) {
                setTimeout(() => firstInput.focus(), 100);
            }
            
            return overlay;
            
        } catch (error) {
            console.error('Failed to create style-aware editor:', error);
            // Fallback to simple text editing
            return this.createFallbackEditor(primaryElement, onSave, onCancel);
        }
    }

    /**
     * Create fallback editor for simple text editing when style-aware editor fails
     */
    createFallbackEditor(element, onSave, onCancel) {
        const form = document.createElement('div');
        form.className = 'insertr-fallback-editor';
        
        const textarea = document.createElement('textarea');
        textarea.className = 'insertr-fallback-textarea';
        textarea.value = element.textContent;
        textarea.rows = 4;
        textarea.placeholder = 'Enter content...';
        
        const actions = document.createElement('div');
        actions.className = 'insertr-form-actions';
        
        const saveBtn = document.createElement('button');
        saveBtn.textContent = 'Save';
        saveBtn.className = 'insertr-btn-save';
        saveBtn.onclick = () => {
            element.textContent = textarea.value;
            onSave({ type: 'text', content: textarea.value });
            this.close();
        };
        
        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = 'Cancel';
        cancelBtn.className = 'insertr-btn-cancel';
        cancelBtn.onclick = () => {
            onCancel();
            this.close();
        };
        
        actions.appendChild(saveBtn);
        actions.appendChild(cancelBtn);
        form.appendChild(textarea);
        form.appendChild(actions);
        
        const overlay = this.createOverlay(form);
        this.positionForm(element, overlay);
        
        document.body.appendChild(overlay);
        this.currentOverlay = overlay;
        
        setTimeout(() => textarea.focus(), 100);
        
        return overlay;
    }

    /**
     * Handle content changes from style-aware editor
     */
    handleContentChange(element, content) {
        // Optional: implement change events if needed
    }

    /**
     * Create overlay with backdrop
     */
    createOverlay(form) {
        const overlay = document.createElement('div');
        overlay.className = 'insertr-form-overlay';
        overlay.appendChild(form);
        return overlay;
    }

    /**
     * Position form relative to primary element
     */
    positionForm(element, overlay) {
        const rect = element.getBoundingClientRect();
        // Support both old and new editor formats
        const form = overlay.querySelector('.insertr-edit-form') || 
                    overlay.querySelector('.insertr-style-aware-editor') || 
                    overlay.querySelector('.insertr-fallback-editor');
        
        if (!form) {
            console.error('No form element found in overlay for positioning');
            return;
        }
        
        const viewportWidth = window.innerWidth;
        
        // Calculate optimal width
        let formWidth;
        if (viewportWidth < 768) {
            formWidth = Math.min(viewportWidth - 40, 500);
        } else {
            const minComfortableWidth = 600;
            const maxWidth = Math.min(viewportWidth * 0.9, 800);
            formWidth = Math.max(minComfortableWidth, Math.min(rect.width * 1.5, maxWidth));
        }
        
        form.style.width = `${formWidth}px`;
        
        // Position below element
        const top = rect.bottom + window.scrollY + 10;
        const centerLeft = rect.left + window.scrollX + (rect.width / 2) - (formWidth / 2);
        const minLeft = 20;
        const maxLeft = window.innerWidth - formWidth - 20;
        const left = Math.max(minLeft, Math.min(centerLeft, maxLeft));
        
        overlay.style.position = 'absolute';
        overlay.style.top = `${top}px`;
        overlay.style.left = `${left}px`;
        overlay.style.zIndex = '10000';
        
        // Ensure visibility
        this.ensureModalVisible(overlay);
    }

    /**
     * Ensure modal is visible by scrolling if needed
     */
    ensureModalVisible(overlay) {
        requestAnimationFrame(() => {
            // Support both old and new editor formats
            const modal = overlay.querySelector('.insertr-edit-form') || 
                         overlay.querySelector('.insertr-style-aware-editor') || 
                         overlay.querySelector('.insertr-fallback-editor');
            
            if (!modal) {
                console.error('No modal element found for visibility check');
                return;
            }
            
            const modalRect = modal.getBoundingClientRect();
            const viewportHeight = window.innerHeight;
            
            if (modalRect.bottom > viewportHeight) {
                const scrollAmount = modalRect.bottom - viewportHeight + 20;
                window.scrollBy({
                    top: scrollAmount,
                    behavior: 'smooth'
                });
            }
        });
    }

    /**
     * Close current editor
     */
    close() {
        if (this.currentStyleEditor) {
            this.currentStyleEditor.destroy();
            this.currentStyleEditor = null;
        }
        
        if (this.currentOverlay) {
            this.currentOverlay.remove();
            this.currentOverlay = null;
        }
    }

    /**
     * Escape HTML to prevent XSS
     */
    escapeHtml(text) {
        if (typeof text !== 'string') return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}