/**
 * Simple Rich Text Editor
 * A lightweight, custom rich text editor with basic formatting and image upload
 */
class SimpleRichTextEditor {
    constructor(element, options = {}) {
        this.element = element;
        this.options = {
            toolbar: ['bold', 'italic', 'underline', '|', 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify', '|', 'fontSize', 'heading', '|', 'link', 'image', '|', 'ul', 'ol', '|', 'break', 'hr', '|', 'variables', '|', 'clean', 'undo', 'redo'],
            placeholder: options.placeholder || 'Start typing...',
            imageUploadUrl: options.imageUploadUrl || '/upload-image.php',
            variables: options.variables || [
                { label: 'Client Name', value: '{{client_name}}' },
                { label: 'Company Name', value: '{{company_name}}' },
                { label: 'Client Email', value: '{{client_email}}' },
                { label: 'Client Phone', value: '{{client_phone}}' },
                { label: 'Project Name', value: '{{project_name}}' },
                { label: 'Proposal Date', value: '{{proposal_date}}' },
                { label: 'Total Price', value: '{{total_price}}' }
            ],
            ...options
        };
        
        this.init();
    }
    
    init() {
        // Hide original textarea
        this.element.style.display = 'none';
        
        // Create editor container
        this.editor = document.createElement('div');
        this.editor.className = 'simple-rich-editor';
        this.editor.contentEditable = true;
        this.editor.innerHTML = this.element.value || '';
        this.editor.setAttribute('data-placeholder', this.options.placeholder);
        
        // Add styles
        this.addStyles();
        
        // Create toolbar
        this.createToolbar();
        
        // Insert editor after textarea
        this.element.parentNode.insertBefore(this.toolbar, this.element);
        this.element.parentNode.insertBefore(this.editor, this.element);
        
        // Handle events
        this.setupEvents();
        
        // Sync content on input
        this.editor.addEventListener('input', () => {
            this.syncContent();
        });
        
        // Handle paste
        this.editor.addEventListener('paste', (e) => {
            this.handlePaste(e);
        });
        
        // Make existing images resizable
        this.makeImagesResizable();
    }
    
    createToolbar() {
        this.toolbar = document.createElement('div');
        this.toolbar.className = 'simple-rich-toolbar';
        
        const buttons = {
            bold: { icon: '<strong>B</strong>', title: 'Bold' },
            italic: { icon: '<em>I</em>', title: 'Italic' },
            underline: { icon: '<u>U</u>', title: 'Underline' },
            alignLeft: { icon: '⬅', title: 'Align Left' },
            alignCenter: { icon: '⬌', title: 'Align Center' },
            alignRight: { icon: '➡', title: 'Align Right' },
            alignJustify: { icon: '☰', title: 'Align Justify' },
            fontSize: { icon: 'Aa', title: 'Font Size' },
            heading: { icon: 'H', title: 'Heading' },
            link: { icon: '🔗', title: 'Link' },
            image: { icon: '🖼️', title: 'Image' },
            ul: { icon: '☰', title: 'Bullet List' },
            ol: { icon: '📝', title: 'Numbered List' },
            break: { icon: '↵', title: 'Line Break' },
            hr: { icon: '—', title: 'Horizontal Line' },
            clean: { icon: '🧹', title: 'Clear Formatting' },
            undo: { icon: '↶', title: 'Undo' },
            redo: { icon: '↷', title: 'Redo' },
            variables: { icon: '{ }', title: 'Insert Variables' }
        };
        
        this.options.toolbar.forEach((cmd, index) => {
            if (cmd === '|') {
                const separator = document.createElement('div');
                separator.className = 'toolbar-separator';
                this.toolbar.appendChild(separator);
            } else if (buttons[cmd]) {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'toolbar-btn';
                btn.innerHTML = buttons[cmd].icon;
                btn.title = buttons[cmd].title;
                btn.onclick = () => this.execCommand(cmd);
                this.toolbar.appendChild(btn);
            }
        });
    }
    
    execCommand(command) {
        switch(command) {
            case 'bold':
            case 'italic':
            case 'underline':
            case 'insertUnorderedList':
            case 'insertOrderedList':
                document.execCommand(command, false, null);
                break;
                
            case 'alignLeft':
            case 'alignCenter':
            case 'alignRight':
            case 'alignJustify':
                document.execCommand(command === 'alignJustify' ? 'justifyFull' : command, false, null);
                break;
                
            case 'fontSize':
                this.showFontSizeMenu();
                break;
                
            case 'heading':
                this.showHeadingMenu();
                break;
                
            case 'undo':
            case 'redo':
                document.execCommand(command, false, null);
                break;
                
            case 'link':
                const url = prompt('Enter URL:');
                if (url) {
                    document.execCommand('createLink', false, url);
                }
                break;
                
            case 'image':
                this.insertImage();
                break;
                
            case 'break':
                document.execCommand('insertLineBreak', false, null);
                break;
                
            case 'hr':
                document.execCommand('insertHTML', false, '<hr style="margin: 12px 0; border: none; border-top: 1px solid #e2e8f0;">');
                break;
                
            case 'clean':
                document.execCommand('removeFormat', false, null);
                break;
                
            case 'variables':
                this.showVariablesMenu();
                break;
        }
        
        this.editor.focus();
        this.syncContent();
    }
    
    insertImage() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                this.uploadImage(file);
            }
        };
        input.click();
    }
    
    async uploadImage(file) {
        const formData = new FormData();
        formData.append('upload', file);
        
        try {
            const response = await fetch(this.options.imageUploadUrl, {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.uploaded && result.url) {
                // Insert scalable image with resize handles
                const imgHtml = `<img src="${result.url}" alt="Uploaded image" style="max-width: 100%; height: auto; border-radius: 4px; margin: 8px 0;" class="resizable-image">`;
                document.execCommand('insertHTML', false, imgHtml);
                this.makeImagesResizable();
                this.syncContent();
            } else {
                alert('Image upload failed: ' + (result.error?.message || 'Unknown error'));
            }
        } catch (error) {
            alert('Image upload failed: ' + error.message);
        }
    }
    
    showFontSizeMenu() {
        const sizes = [
            { label: 'Small', value: '2' },
            { label: 'Normal', value: '3' },
            { label: 'Large', value: '4' },
            { label: 'Extra Large', value: '5' },
            { label: 'Huge', value: '6' },
            { label: 'Paragraph', value: '3' }
        ];
        
        const menu = this.createDropdownMenu(sizes, 'Select Font Size', (size) => {
            document.execCommand('fontSize', false, size.value);
        });
        
        this.toolbar.appendChild(menu);
    }
    
    showHeadingMenu() {
        const headings = [
            { label: 'Paragraph', value: 'p' },
            { label: 'Heading 1', value: 'h1' },
            { label: 'Heading 2', value: 'h2' },
            { label: 'Heading 3', value: 'h3' },
            { label: 'Heading 4', value: 'h4' },
            { label: 'Heading 5', value: 'h5' },
            { label: 'Heading 6', value: 'h6' }
        ];
        
        const menu = this.createDropdownMenu(headings, 'Select Heading', (heading) => {
            if (heading.value === 'p') {
                document.execCommand('formatBlock', false, 'p');
            } else {
                document.execCommand('formatBlock', false, heading.value);
            }
        });
        
        this.toolbar.appendChild(menu);
    }
    
    showVariablesMenu() {
        const menu = this.createDropdownMenu(this.options.variables, 'Insert Variable', (variable) => {
            document.execCommand('insertHTML', false, `<span class="variable-placeholder" contenteditable="false">${variable.value}</span>`);
        });
        
        this.toolbar.appendChild(menu);
    }
    
    createDropdownMenu(items, title, onSelect) {
        const menu = document.createElement('div');
        menu.className = 'dropdown-menu';
        menu.style.cssText = `
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            z-index: 1000;
            min-width: 150px;
            max-height: 200px;
            overflow-y: auto;
        `;
        
        items.forEach(item => {
            const option = document.createElement('div');
            option.className = 'dropdown-option';
            option.textContent = item.label;
            option.style.cssText = `
                padding: 8px 12px;
                cursor: pointer;
                border-bottom: 1px solid #f1f5f9;
                font-size: 12px;
                color: #475569;
            `;
            option.onmouseover = () => option.style.background = '#f8fafc';
            option.onmouseout = () => option.style.background = 'white';
            option.onclick = () => {
                onSelect(item);
                menu.remove();
            };
            menu.appendChild(option);
        });
        
        // Close menu when clicking outside
        setTimeout(() => {
            document.addEventListener('click', function closeMenu(e) {
                if (!menu.contains(e.target)) {
                    menu.remove();
                    document.removeEventListener('click', closeMenu);
                }
            });
        }, 100);
        
        return menu;
    }
    
    makeImagesResizable() {
        this.editor.querySelectorAll('.resizable-image').forEach(img => {
            img.style.resize = 'both';
            img.style.overflow = 'auto';
            img.style.minWidth = '50px';
            img.style.minHeight = '50px';
        });
    }
    
    handlePaste(e) {
        e.preventDefault();
        
        const text = e.clipboardData.getData('text/plain');
        const html = e.clipboardData.getData('text/html');
        
        if (html) {
            // Paste as HTML but clean it
            document.execCommand('insertHTML', false, this.cleanHTML(html));
        } else {
            // Paste as plain text
            document.execCommand('insertText', false, text);
        }
        
        this.syncContent();
    }
    
    cleanHTML(html) {
        // Basic HTML cleaning - remove dangerous tags
        const div = document.createElement('div');
        div.innerHTML = html;
        
        // Remove script tags and other dangerous elements
        const scripts = div.querySelectorAll('script, style, iframe, object, embed');
        scripts.forEach(el => el.remove());
        
        return div.innerHTML;
    }
    
    setupEvents() {
        // Handle placeholder
        this.editor.addEventListener('focus', () => {
            this.editor.classList.remove('empty');
        });
        
        this.editor.addEventListener('blur', () => {
            if (!this.editor.innerHTML.trim()) {
                this.editor.classList.add('empty');
            }
        });
        
        // Initial placeholder state
        if (!this.editor.innerHTML.trim()) {
            this.editor.classList.add('empty');
        }
    }
    
    syncContent() {
        this.element.value = this.editor.innerHTML;
        
        // Trigger change event
        const event = new Event('input', { bubbles: true });
        this.element.dispatchEvent(event);
    }
    
    addStyles() {
        const styleId = 'simple-rich-editor-styles';
        if (!document.getElementById(styleId)) {
            const style = document.createElement('style');
            style.id = styleId;
            style.textContent = `
                .simple-rich-toolbar {
                    background: #f8fafc;
                    border: 1px solid #e2e8f0;
                    border-bottom: none;
                    border-radius: 8px 8px 0 0;
                    padding: 8px;
                    display: flex;
                    gap: 4px;
                    flex-wrap: wrap;
                }
                
                .toolbar-btn {
                    background: white;
                    border: 1px solid #e2e8f0;
                    border-radius: 4px;
                    padding: 6px 10px;
                    cursor: pointer;
                    font-size: 12px;
                    font-weight: 500;
                    color: #475569;
                    transition: all 0.2s;
                    min-width: 30px;
                    height: 30px;
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .toolbar-separator {
                    width: 1px;
                    height: 20px;
                    background: #e2e8f0;
                    margin: 0 4px;
                }
                
                .toolbar-btn:hover {
                    background: #f1f5f9;
                    border-color: #cbd5e1;
                    color: #1e293b;
                }
                
                .toolbar-btn:active {
                    background: #e2e8f0;
                }
                
                .simple-rich-editor {
                    background: white;
                    border: 1px solid #e2e8f0;
                    border-radius: 0 0 8px 8px;
                    padding: 12px;
                    min-height: 200px;
                    max-height: 400px;
                    overflow-y: auto;
                    font-family: inherit;
                    font-size: 14px;
                    line-height: 1.5;
                    color: #1e293b;
                }
                
                .simple-rich-editor:focus {
                    outline: none;
                    border-color: #3b82f6;
                    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
                }
                
                .simple-rich-editor.empty::before {
                    content: attr(data-placeholder);
                    color: #94a3b8;
                    font-style: italic;
                    pointer-events: none;
                }
                
                .simple-rich-editor img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                    margin: 8px 0;
                }
                
                .simple-rich-editor img.resizable-image {
                    resize: both;
                    overflow: auto;
                    min-width: 50px;
                    min-height: 50px;
                    border: 1px dashed #cbd5e1;
                    cursor: nwse-resize;
                }
                
                .simple-rich-editor img.resizable-image:hover {
                    border-color: #3b82f6;
                }
                
                .variable-placeholder {
                    background: #fef3c7;
                    border: 1px solid #f59e0b;
                    border-radius: 3px;
                    padding: 2px 4px;
                    font-family: monospace;
                    font-size: 12px;
                    color: #92400e;
                    user-select: all;
                }
                
                .simple-rich-editor hr {
                    margin: 12px 0;
                    border: none;
                    border-top: 1px solid #e2e8f0;
                }
                
                .simple-rich-editor a {
                    color: #3b82f6;
                    text-decoration: underline;
                }
                
                .simple-rich-editor ul, .simple-rich-editor ol {
                    margin: 8px 0;
                    padding-left: 24px;
                }
                
                .simple-rich-editor li {
                    margin: 4px 0;
                }
            `;
            document.head.appendChild(style);
        }
    }
    
    // Public methods
    getContent() {
        return this.editor.innerHTML;
    }
    
    setContent(content) {
        this.editor.innerHTML = content;
        this.syncContent();
    }
    
    destroy() {
        this.toolbar.remove();
        this.editor.remove();
        this.element.style.display = '';
    }
}

// Auto-initialize
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.rich').forEach(element => {
        new SimpleRichTextEditor(element, {
            imageUploadUrl: '/upload-image.php'
        });
    });
});
