import { InsertrFormRenderer } from '../ui/form-renderer.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;
        
        // Add click handler for editing
        this.addClickHandler(element, meta);
    }
    
    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 based on type
            let contentValue;
            if (meta.element.tagName.toLowerCase() === 'a') {
                // For links, save the text content (URL is handled separately if needed)
                contentValue = formData.text || formData;
            } else {
                contentValue = formData.text || formData;
            }
            
            // Universal upsert - server handles ID extraction/generation from markup
            const contentType = this.determineContentType(meta.element);
            const result = await this.apiClient.createContent(
                contentValue, 
                contentType, 
                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);
                meta.element.setAttribute('data-content-type', result.type);
                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();
        }
    }
    
    determineContentType(element) {
        const tagName = element.tagName.toLowerCase();
        
        if (tagName === 'a' || tagName === 'button') {
            return 'link';
        }
        
        // ALL text elements use markdown for consistent editing experience
        return 'markdown';
    }
    
    handleCancel(meta) {
        console.log('❌ Edit cancelled:', meta.contentId);
    }
    


}