import { InsertrFormRenderer } from '../ui/form-renderer.js';
import { CollectionManager } from '../ui/collection-manager.js';

/**
 * InsertrEditor - Content editing workflow and business logic
 * Pure business logic - no visual styling or DOM manipulation
 * 
 * Responsibilities:
 * - Manage editing workflow
 * - Handle content persistence
 * - Coordinate with form renderer
 * - Emit editing events
 */
export class InsertrEditor {
    constructor(core, auth, apiClient, options = {}) {
        this.core = core;
        this.auth = auth;
        this.apiClient = apiClient;
        this.options = options;
        this.isActive = false;
        this.formRenderer = new InsertrFormRenderer(apiClient);
        
        // Event listeners for mode changes
        this.listeners = {
            modeChange: [],
            editStart: [],
            editEnd: []
        };
    }

    /**
     * Event emitter methods
     */
    on(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event].push(callback);
        }
    }

    off(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        }
    }

    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => callback(data));
        }
    }
    
    start() {
        if (this.isActive) return;
        
        console.log('🚀 Starting Insertr Editor');
        this.isActive = true;
        
        // Initialize all enhanced elements for editing
        const elements = this.core.getAllElements();
        console.log(`📝 Found ${elements.length} editable elements`);
        
        elements.forEach(meta => this.initializeElement(meta));
        
        // Emit mode change event for UI updates
        this.emit('modeChange', { isActive: this.isActive });
    }
    
    initializeElement(meta) {
        const { element } = meta;
        
        if (meta.editorType === 'collection') {
            // Initialize collection management
            this.initializeCollection(meta);
        } else {
            // Add click handler for editing individual elements
            this.addClickHandler(element, meta);
        }
    }
    
    initializeCollection(meta) {
        const collectionManager = new CollectionManager(meta, this.apiClient, this.auth);
        if (collectionManager.collectionId) {
            collectionManager.initialize();
        }
    }
    
    addClickHandler(element, meta) {
        element.addEventListener('click', (e) => {
            // Only allow editing if authenticated and in edit mode
            if (!this.auth.isAuthenticated() || !this.auth.isEditMode()) {
                return; // Let normal click behavior happen
            }
            
            e.preventDefault();
            this.openEditor(meta);
        });
    }
    
    openEditor(meta) {
        const { element } = meta;
        const currentContent = this.extractCurrentContent(element);
        
        // Show professional form instead of prompt
        this.formRenderer.showEditForm(
            meta,
            currentContent,
            (formData) => this.handleSave(meta, formData),
            () => this.handleCancel(meta)
        );
    }
    
    extractCurrentContent(element) {
        // For links, extract both text and URL
        if (element.tagName.toLowerCase() === 'a') {
            return {
                text: element.textContent.trim(),
                url: element.getAttribute('href') || ''
            };
        }
        
        // For other elements, just return text content
        return element.textContent.trim();
    }
    
    async handleSave(meta, formData) {
        console.log('💾 Saving content:', meta.contentId, formData);
        
        try {
            // Extract content value from formData
            let contentValue;
            if (typeof formData === 'string') {
                contentValue = formData;
            } else if (formData.content) {
                contentValue = formData.content;
            } else if (formData.text) {
                contentValue = formData.text;
            } else {
                contentValue = formData;
            }
            
            let result;
            if (meta.contentId) {
                // Update existing content
                result = await this.apiClient.updateContent(meta.contentId, contentValue);
            } else {
                // Create new content - server handles ID extraction/generation from markup
                result = await this.apiClient.createContent(
                    contentValue, 
                    meta.htmlMarkup  // Always send HTML markup - server is smart about ID handling
                );
            }
            
            if (result) {
                // Store the backend-generated/confirmed ID in the element
                meta.element.setAttribute('data-content-id', result.id);
                console.log(`✅ Content saved: ${result.id}`, contentValue);
            } else {
                console.error('❌ Failed to save content to server');
            }
            
            // Close form
            this.formRenderer.closeForm();
            
        } catch (error) {
            console.error('❌ Error saving content:', error);
            this.formRenderer.closeForm();
        }
    }
    

    
    handleCancel(meta) {
        console.log('❌ Edit cancelled:', meta.contentId);
    }
    


}