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

/**
 * InsertrEditor - Visual editing functionality
 */
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);
    }
    
    start() {
        if (this.isActive) return;
        
        console.log('🚀 Starting Insertr Editor');
        this.isActive = true;
        
        // Add editor styles
        this.addEditorStyles();
        
        // Initialize all enhanced elements
        const elements = this.core.getAllElements();
        console.log(`📝 Found ${elements.length} editable elements`);
        
        elements.forEach(meta => this.initializeElement(meta));
    }
    
    initializeElement(meta) {
        const { element, contentId, contentType } = meta;
        
        // Add visual indicators
        element.style.cursor = 'pointer';
        element.style.position = 'relative';
        
        // Add interaction handlers
        this.addHoverEffects(element);
        this.addClickHandler(element, meta);
    }
    
    addHoverEffects(element) {
        element.addEventListener('mouseenter', () => {
            element.classList.add('insertr-editing-hover');
        });
        
        element.addEventListener('mouseleave', () => {
            element.classList.remove('insertr-editing-hover');
        });
    }
    
    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 - works for both new and existing content
            const contentType = this.determineContentType(meta.element);
            const result = await this.apiClient.createContent(
                meta.contentId, // Use existing ID if available, null if new
                contentValue, 
                contentType, 
                meta.htmlMarkup
            );
            
            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);
    }
    

    addEditorStyles() {
        const styles = `
            .insertr-editing-hover {
                outline: 2px dashed #007cba !important;
                outline-offset: 2px !important;
                background-color: rgba(0, 124, 186, 0.05) !important;
            }
            
            .insertr:hover::after {
                content: "✏️ " attr(data-content-type);
                position: absolute;
                top: -25px;
                left: 0;
                background: #007cba;
                color: white;
                padding: 2px 6px;
                font-size: 11px;
                border-radius: 3px;
                white-space: nowrap;
                z-index: 1000;
                font-family: monospace;
            }

            /* Version History Modal Styles */
            .insertr-version-modal {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                z-index: 10001;
            }

            .insertr-version-backdrop {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }

            .insertr-version-content-modal {
                background: white;
                border-radius: 8px;
                max-width: 600px;
                width: 100%;
                max-height: 80vh;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
                display: flex;
                flex-direction: column;
            }

            .insertr-version-header {
                padding: 20px 20px 0;
                border-bottom: 1px solid #eee;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-shrink: 0;
            }

            .insertr-version-header h3 {
                margin: 0 0 20px;
                color: #333;
                font-size: 18px;
            }

            .insertr-btn-close {
                background: none;
                border: none;
                font-size: 24px;
                cursor: pointer;
                color: #666;
                padding: 0;
                width: 30px;
                height: 30px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .insertr-btn-close:hover {
                color: #333;
            }

            .insertr-version-list {
                overflow-y: auto;
                padding: 20px;
                flex: 1;
            }

            .insertr-version-item {
                border: 1px solid #e1e5e9;
                border-radius: 6px;
                padding: 16px;
                margin-bottom: 12px;
                background: #f8f9fa;
            }

            .insertr-version-meta {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-bottom: 8px;
                font-size: 13px;
            }

            .insertr-version-label {
                font-weight: 600;
                color: #0969da;
            }

            .insertr-version-date {
                color: #656d76;
            }

            .insertr-version-user {
                color: #656d76;
            }

            .insertr-version-content {
                margin-bottom: 12px;
                padding: 8px;
                background: white;
                border-radius: 4px;
                font-family: monospace;
                font-size: 14px;
                color: #24292f;
                white-space: pre-wrap;
            }

            .insertr-version-actions {
                display: flex;
                gap: 8px;
            }

            .insertr-btn-restore {
                background: #0969da;
                color: white;
                border: none;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                font-weight: 500;
            }

            .insertr-btn-restore:hover {
                background: #0860ca;
            }

            .insertr-btn-view-diff {
                background: #f6f8fa;
                color: #24292f;
                border: 1px solid #d1d9e0;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                font-weight: 500;
            }

            .insertr-btn-view-diff:hover {
                background: #f3f4f6;
            }

            .insertr-version-empty {
                text-align: center;
                color: #656d76;
                font-style: italic;
                padding: 40px 20px;
            }

            /* History Button in Form */
            .insertr-btn-history {
                background: #6f42c1;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                font-weight: 500;
                margin-left: auto;
            }

            .insertr-btn-history:hover {
                background: #5a359a;
            }
        `;
        
        const styleSheet = document.createElement('style');
        styleSheet.type = 'text/css';
        styleSheet.innerHTML = styles;
        document.head.appendChild(styleSheet);
    }
}