/**
 * RSL Layout Control Panel
 *
 * Visual UI component for managing layout state through LayoutStateManager. Provides
 * an intuitive interface for undo/redo operations, preset management, import/export,
 * and HTML-to-JSON conversion. Automatically integrates with JSONLayoutEngine when available.
 *
 * @fileoverview Interactive control panel for RSL state management
 * @version 1.0.0
 * @license MIT
 *
 * Key Features:
 * - Undo/redo controls with history visualization
 * - Preset save/load/delete interface
 * - JSON import/export functionality
 * - HTML to JSON converter with multi-layout support
 * - DOM-to-JSON extraction tools
 * - Collapsible panel with toggle
 * - Real-time UI updates via event listeners
 * - Automatic initialization on StateManager ready
 * - Support for both JSON and HTML-driven workflows
 *
 * Usage:
 * // Automatically initialized if StateManager exists
 * // Access via: RSL.ControlPanel
 *
 * // Manual initialization (if needed)
 * const panel = new LayoutControlPanel(RSL.StateManager);
 *
 * // Panel auto-updates on state changes
 * // Users interact with UI directly
 *
 * Public API:
 * - RSL.ControlPanel.updateUI() - Manually refresh UI state
 * - RSL.ControlPanel.updatePresetList() - Refresh preset list
 * - Panel is automatically created and managed on DOM ready
 *
 * Events Emitted:
 * None (listens to rsl:statechange and rsl:presetchange events)
 *
 * Events Consumed:
 * - rsl:statechange - Updates undo/redo buttons
 * - rsl:presetchange - Refreshes preset list
 * - rsl:statemanager:ready - Triggers initialization
 */

(function() {
    'use strict';

    /**
     * LayoutControlPanel class
     * Creates and manages the visual control panel UI
     */
    class LayoutControlPanel {
        /**
         * Create a new control panel instance
         *
         * @param {LayoutStateManager} stateManager - State manager instance to control
         */
        constructor(stateManager) {
            this.stateManager = stateManager;
            this.panel = null;
            this.jsonMode = false;
            this.init();
        }

        /**
         * Initialize the control panel
         *
         * Creates panel HTML, attaches to DOM, sets up event listeners,
         * and performs initial UI update.
         *
         * @private
         */
        init() {
            // Check if JSON engine is available
            this.jsonMode = !!(window.RSL && window.RSL.JSONLayout);

            // Create the control panel HTML
            this.panel = document.createElement('div');
            this.panel.className = 'rsl-control-panel';
            this.panel.innerHTML = this._getPanelHTML();

            document.body.appendChild(this.panel);
            this.attachEventListeners();
            this.updateUI();
            this.updatePresetList();
        }

        /**
         * Generate HTML for the control panel
         *
         * Creates the complete panel structure with conditional JSON sections
         * based on JSONLayoutEngine availability.
         *
         * @private
         * @returns {string} HTML string for panel content
         */
        _getPanelHTML() {
            const jsonSection = this.jsonMode ? `
                <div class="rsl-control-section">
                    <h4>HTML to JSON Converter</h4>
                    <button id="rsl-convert-html" class="rsl-btn">
                        <i class="fa fa-exchange-alt"></i> Convert HTML to JSON
                    </button>
                    <textarea id="rsl-html-input" style="display:none; margin-top: 0.5rem; min-height: 150px;"
                             placeholder="Paste your HTML here..."></textarea>
                    <div style="display: none; gap: 0.5rem; margin-top: 0.5rem;" id="rsl-html-convert-actions">
                        <button id="rsl-html-convert-apply" class="rsl-btn-primary">Convert</button>
                        <button id="rsl-html-convert-cancel" class="rsl-btn">Cancel</button>
                    </div>
                    <textarea id="rsl-html-output" style="display:none; margin-top: 0.5rem; min-height: 200px;"
                             placeholder="JSON output will appear here..." readonly></textarea>
                    <div id="rsl-layout-selector" style="display:none; margin-top: 0.5rem;">
                        <p style="margin: 0 0 0.5rem 0; font-size: 0.875rem; color: #6b7280;">Multiple layouts found. Choose one to import:</p>
                        <div id="rsl-layout-buttons" style="display: flex; flex-direction: column; gap: 0.5rem;"></div>
                    </div>
                </div>
                <div class="rsl-control-section">
                    <h4>JSON Layout</h4>
                    <button id="rsl-build-json" class="rsl-btn">
                        <i class="fa fa-file-code"></i> Extract JSON
                    </button>
                    <button id="rsl-render-json" class="rsl-btn">
                        <i class="fa fa-magic"></i> Render from JSON
                    </button>
                    <textarea id="rsl-json-editor" style="display:none; margin-top: 0.5rem;"
                             placeholder="JSON layout configuration"></textarea>
                </div>
            ` : '';

            return `
                <div class="rsl-control-header">
                    <h3>Layout Controls</h3>
                    <button class="rsl-control-toggle" aria-label="Toggle control panel">
                        <i class="fa fa-sliders"></i>
                    </button>
                </div>
                <div class="rsl-control-body">
                    <div class="rsl-control-section">
                        <h4>History</h4>
                        <div class="rsl-history-controls">
                            <button id="rsl-undo" class="rsl-btn" disabled>
                                <i class="fa fa-undo"></i> Undo
                            </button>
                            <button id="rsl-redo" class="rsl-btn" disabled>
                                <i class="fa fa-redo"></i> Redo
                            </button>
                            <span class="rsl-history-info"></span>
                        </div>
                    </div>

                    <div class="rsl-control-section">
                        <h4>Presets</h4>
                        <div class="rsl-preset-list"></div>
                        <div class="rsl-preset-form">
                            <input type="text" id="rsl-preset-name" placeholder="Preset name" />
                            <button id="rsl-save-preset" class="rsl-btn-primary">Save Current</button>
                        </div>
                    </div>

                    ${jsonSection}

                    <div class="rsl-control-section">
                        <h4>Import/Export</h4>
                        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 0.5rem;">
                            <button id="rsl-export-state" class="rsl-btn">
                                <i class="fa fa-download"></i> Export State
                            </button>
                            <button id="rsl-export-full" class="rsl-btn">
                                <i class="fa fa-file-export"></i> Export Full
                            </button>
                        </div>
                        <button id="rsl-import-state" class="rsl-btn">
                            <i class="fa fa-upload"></i> Import JSON
                        </button>
                        <textarea id="rsl-import-textarea" style="display:none"
                                 placeholder="Paste JSON here"></textarea>
                        <div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;" id="rsl-import-actions" style="display:none">
                            <button id="rsl-import-apply" class="rsl-btn-primary">Apply</button>
                            <button id="rsl-import-cancel" class="rsl-btn">Cancel</button>
                        </div>
                    </div>

                    <div class="rsl-control-section">
                        <h4>Actions</h4>
                        <button id="rsl-clear-storage" class="rsl-btn" style="width: 100%;">
                            <i class="fa fa-trash"></i> Clear All Data
                        </button>
                    </div>
                </div>
            `;
        }

        /**
         * Attach event listeners to all control panel buttons and inputs
         *
         * Sets up handlers for undo/redo, presets, import/export, HTML conversion,
         * JSON operations, and panel toggle functionality.
         *
         * @private
         */
        attachEventListeners() {
            // Toggle panel
            this.panel.querySelector('.rsl-control-toggle').addEventListener('click', () => {
                this.panel.classList.toggle('collapsed');
            });

            // Undo/Redo
            document.getElementById('rsl-undo').addEventListener('click', () => {
                if (this.stateManager.undo()) {
                    this.updateUI();
                }
            });

            document.getElementById('rsl-redo').addEventListener('click', () => {
                if (this.stateManager.redo()) {
                    this.updateUI();
                }
            });

            // Save preset
            document.getElementById('rsl-save-preset').addEventListener('click', () => {
                const name = document.getElementById('rsl-preset-name').value.trim();
                if (name) {
                    this.stateManager.savePreset(name);
                    document.getElementById('rsl-preset-name').value = '';
                    this.updatePresetList();
                }
            });

            // Export state only
            document.getElementById('rsl-export-state').addEventListener('click', () => {
                const json = this.stateManager.exportState({ includeSchema: false });
                this.downloadJSON(json, 'rsl-state-export.json');
            });

            // Export full (state + schema)
            document.getElementById('rsl-export-full').addEventListener('click', () => {
                const container = document.querySelector('.slot-layout')?.parentElement;
                const json = this.stateManager.exportState({
                    includeSchema: this.jsonMode,
                    container: container
                });
                this.downloadJSON(json, 'rsl-full-export.json');
            });

            // Import
            document.getElementById('rsl-import-state').addEventListener('click', () => {
                const textarea = document.getElementById('rsl-import-textarea');
                const actions = document.getElementById('rsl-import-actions');
                const isVisible = textarea.style.display !== 'none';

                textarea.style.display = isVisible ? 'none' : 'block';
                actions.style.display = isVisible ? 'none' : 'flex';

                if (!isVisible) {
                    textarea.focus();
                }
            });

            // Import apply
            document.getElementById('rsl-import-apply').addEventListener('click', () => {
                const textarea = document.getElementById('rsl-import-textarea');
                const json = textarea.value.trim();

                if (json) {
                    try {
                        const parsed = JSON.parse(json);

                        // Check if this is a pure layout schema (no state wrapper)
                        if (parsed.layoutId && parsed.items && !parsed.state && this.jsonMode) {
                            // This is a layout schema, render it directly
                            const container = document.querySelector('.slot-layout')?.parentElement ||
                                            document.querySelector('#layout-container') ||
                                            document.body;

                            window.RSL.JSONLayout.renderLayout(container, parsed);
                            this.stateManager.pushToHistory('Imported layout schema');
                            this.updateUI();

                            textarea.value = '';
                            textarea.style.display = 'none';
                            document.getElementById('rsl-import-actions').style.display = 'none';
                            alert('Layout rendered successfully!');
                        } else {
                            // This is a state export or has both schema + state
                            const container = document.querySelector('.slot-layout')?.parentElement ||
                                            document.querySelector('#layout-container') ||
                                            document.body;
                            const success = this.stateManager.importState(json, { container });

                            if (success) {
                                textarea.value = '';
                                textarea.style.display = 'none';
                                document.getElementById('rsl-import-actions').style.display = 'none';
                                this.updateUI();
                                alert('Import successful!');
                            } else {
                                alert('Import failed. Check console for errors.');
                            }
                        }
                    } catch (error) {
                        alert('Import failed: ' + error.message);
                        console.error(error);
                    }
                }
            });

            // Import cancel
            document.getElementById('rsl-import-cancel').addEventListener('click', () => {
                document.getElementById('rsl-import-textarea').style.display = 'none';
                document.getElementById('rsl-import-actions').style.display = 'none';
            });

            // JSON mode buttons (if available)
            if (this.jsonMode) {
                this._attachJSONModeListeners();
            }

            // Clear storage
            document.getElementById('rsl-clear-storage').addEventListener('click', () => {
                if (confirm('Clear all history and presets? This cannot be undone.')) {
                    this.stateManager.clearStorage();
                    this.updateUI();
                    this.updatePresetList();
                    alert('All data cleared.');
                }
            });

            // Listen for state changes
            window.addEventListener('rsl:statechange', () => this.updateUI());
            window.addEventListener('rsl:presetchange', () => this.updatePresetList());
        }

        /**
         * Attach event listeners for JSON mode features
         *
         * Sets up HTML-to-JSON conversion, DOM extraction, and JSON rendering controls.
         * Only called when JSONLayoutEngine is available.
         *
         * @private
         */
        _attachJSONModeListeners() {
            // HTML to JSON converter
            document.getElementById('rsl-convert-html').addEventListener('click', () => {
                const textarea = document.getElementById('rsl-html-input');
                const actions = document.getElementById('rsl-html-convert-actions');
                const output = document.getElementById('rsl-html-output');
                const isVisible = textarea.style.display !== 'none';

                textarea.style.display = isVisible ? 'none' : 'block';
                actions.style.display = isVisible ? 'none' : 'flex';
                output.style.display = 'none';

                if (!isVisible) {
                    textarea.focus();
                }
            });

            // Convert HTML to JSON - Apply
            document.getElementById('rsl-html-convert-apply').addEventListener('click', () => {
                this._handleHTMLConversion();
            });

            // Convert HTML to JSON - Cancel
            document.getElementById('rsl-html-convert-cancel').addEventListener('click', () => {
                document.getElementById('rsl-html-input').style.display = 'none';
                document.getElementById('rsl-html-convert-actions').style.display = 'none';
                document.getElementById('rsl-html-output').style.display = 'none';
                document.getElementById('rsl-layout-selector').style.display = 'none';
                document.getElementById('rsl-html-input').value = '';
                document.getElementById('rsl-html-output').value = '';
            });

            // Extract JSON from DOM
            document.getElementById('rsl-build-json').addEventListener('click', () => {
                const container = document.querySelector('.slot-layout')?.parentElement;
                if (container && window.RSL.JSONLayout) {
                    try {
                        const config = window.RSL.JSONLayout.buildFromDOM(container);
                        const json = JSON.stringify(config, null, 2);
                        const editor = document.getElementById('rsl-json-editor');
                        editor.value = json;
                        editor.style.display = 'block';
                        editor.style.minHeight = '200px';
                    } catch (error) {
                        alert('Failed to extract JSON: ' + error.message);
                    }
                }
            });

            // Render layout from JSON
            document.getElementById('rsl-render-json').addEventListener('click', () => {
                const editor = document.getElementById('rsl-json-editor');
                const json = editor.value.trim();

                if (json) {
                    try {
                        const config = JSON.parse(json);
                        const container = document.querySelector('.slot-layout')?.parentElement ||
                                        document.body;

                        window.RSL.JSONLayout.renderLayout(container, config);
                        this.stateManager.pushToHistory('Rendered from JSON');
                        this.updateUI();
                        alert('Layout rendered successfully!');
                    } catch (error) {
                        alert('Failed to render: ' + error.message);
                    }
                }
            });
        }

        /**
         * Handle HTML to JSON conversion
         *
         * Parses HTML input, extracts slot-layout elements, converts to JSON,
         * and handles both single and multi-layout scenarios.
         *
         * @private
         */
        _handleHTMLConversion() {
            const htmlInput = document.getElementById('rsl-html-input');
            const htmlOutput = document.getElementById('rsl-html-output');
            const html = htmlInput.value.trim();

            if (!html) {
                alert('Please paste HTML first');
                return;
            }

            try {
                // Create a temporary container
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = html;

                // Find ALL slot-layouts in the HTML
                const slotLayouts = tempDiv.querySelectorAll('.slot-layout');

                if (slotLayouts.length === 0) {
                    alert('No .slot-layout found in the HTML. Please make sure your HTML contains a layout with class="slot-layout"');
                    return;
                }

                let allConfigs = [];

                // Convert each layout to JSON
                slotLayouts.forEach((slotLayout, index) => {
                    // Create a temporary wrapper just for extraction
                    const wrapper = document.createElement('div');
                    wrapper.appendChild(slotLayout.cloneNode(true));

                    // Extract JSON
                    const config = window.RSL.JSONLayout.buildFromDOM(wrapper);
                    allConfigs.push(config);
                });

                const layoutSelector = document.getElementById('rsl-layout-selector');
                const layoutButtons = document.getElementById('rsl-layout-buttons');

                if (allConfigs.length === 1) {
                    // Single layout - just output it
                    const json = JSON.stringify(allConfigs[0], null, 2);
                    htmlOutput.value = json;
                    htmlOutput.style.display = 'block';
                    layoutSelector.style.display = 'none';

                    // Copy to clipboard
                    htmlOutput.select();
                    document.execCommand('copy');

                    alert('Converted to JSON! (Copied to clipboard)');
                } else {
                    // Multiple layouts - show selector buttons
                    htmlOutput.style.display = 'none';
                    layoutSelector.style.display = 'block';

                    // Clear previous buttons
                    layoutButtons.innerHTML = '';

                    // Create a button for each layout
                    allConfigs.forEach((config, index) => {
                        const btn = this._createLayoutButton(config, index, htmlInput);
                        layoutButtons.appendChild(btn);
                    });

                    alert(`Found ${allConfigs.length} layouts! Click on a layout below to import it.`);
                }
            } catch (error) {
                alert('Failed to convert HTML to JSON: ' + error.message);
                console.error(error);
            }
        }

        /**
         * Create a button for layout selection in multi-layout HTML conversion
         *
         * @private
         * @param {Object} config - Layout configuration
         * @param {number} index - Layout index
         * @param {HTMLElement} htmlInput - HTML input textarea element
         * @returns {HTMLElement} Button element
         */
        _createLayoutButton(config, index, htmlInput) {
            const itemCount = config.items?.length || 0;
            const breakpoints = Object.keys(config.breakpoints || {}).join(', ');
            const layoutId = config.layoutId || `layout-${index + 1}`;

            const btn = document.createElement('button');
            btn.className = 'rsl-btn';
            btn.style.cssText = 'text-align: left; padding: 0.75rem; display: flex; flex-direction: column; gap: 0.25rem;';
            btn.innerHTML = `
                <strong style="color: #6E7BFF;">Layout ${index + 1}</strong>
                <small style="color: #6b7280;">ID: ${layoutId.substring(0, 30)}${layoutId.length > 30 ? '...' : ''}</small>
                <small style="color: #6b7280;">${itemCount} items • Breakpoints: ${breakpoints}</small>
            `;

            btn.addEventListener('click', () => {
                const container = document.querySelector('.slot-layout')?.parentElement ||
                                document.querySelector('#layout-container') ||
                                document.body;

                try {
                    window.RSL.JSONLayout.renderLayout(container, config);
                    this.stateManager.pushToHistory(`Imported layout ${index + 1}`);
                    this.updateUI();

                    // Hide the selector
                    document.getElementById('rsl-layout-selector').style.display = 'none';
                    htmlInput.value = '';
                    htmlInput.style.display = 'none';
                    document.getElementById('rsl-html-convert-actions').style.display = 'none';

                    alert(`Layout ${index + 1} imported successfully!`);
                } catch (error) {
                    alert('Failed to import layout: ' + error.message);
                    console.error(error);
                }
            });

            return btn;
        }

        /**
         * Update UI state for undo/redo buttons and history info
         *
         * Enables/disables buttons based on history position and updates
         * the history counter display.
         *
         * @public
         */
        updateUI() {
            // Update undo/redo buttons
            const undoBtn = document.getElementById('rsl-undo');
            const redoBtn = document.getElementById('rsl-redo');
            const historyInfo = this.panel.querySelector('.rsl-history-info');

            if (undoBtn && redoBtn && historyInfo) {
                undoBtn.disabled = this.stateManager.historyIndex <= 0;
                redoBtn.disabled = this.stateManager.historyIndex >= this.stateManager.history.length - 1;

                const current = this.stateManager.historyIndex + 1;
                const total = this.stateManager.history.length;
                historyInfo.textContent = total > 0 ? `${current} / ${total}` : '0 / 0';
            }
        }

        /**
         * Update the preset list display
         *
         * Refreshes the preset list UI with load/delete buttons for each preset.
         * Shows a message if no presets exist.
         *
         * @public
         */
        updatePresetList() {
            const list = this.panel.querySelector('.rsl-preset-list');
            if (!list) return;

            const presets = this.stateManager.getPresetNames();

            if (presets.length === 0) {
                list.innerHTML = '<p style="font-size: 0.75rem; color: #9ca3af; margin: 0;">No presets saved</p>';
                return;
            }

            list.innerHTML = presets.map(name => `
                <div class="rsl-preset-item">
                    <button class="rsl-preset-load" data-preset="${name}">
                        <i class="fa fa-play"></i> ${this._escapeHtml(name)}
                    </button>
                    <button class="rsl-preset-delete" data-preset="${name}">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            `).join('');

            // Attach preset buttons
            list.querySelectorAll('.rsl-preset-load').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const presetName = e.currentTarget.dataset.preset;
                    console.log('Loading preset:', presetName);
                    const success = this.stateManager.loadPreset(presetName);
                    if (success) {
                        console.log('Preset loaded successfully');
                    } else {
                        console.error('Failed to load preset:', presetName);
                    }
                });
            });

            list.querySelectorAll('.rsl-preset-delete').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const presetName = e.currentTarget.dataset.preset;
                    if (confirm(`Delete preset "${presetName}"?`)) {
                        this.stateManager.deletePreset(presetName);
                    }
                });
            });
        }

        /**
         * Download JSON as a file
         *
         * Creates a Blob from JSON string and triggers browser download.
         *
         * @param {string} jsonString - JSON string to download
         * @param {string} filename - Filename for download
         *
         * @example
         * this.downloadJSON(jsonData, 'my-layout.json');
         */
        downloadJSON(jsonString, filename) {
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(url);
        }

        /**
         * Escape HTML to prevent XSS in preset names
         *
         * @private
         * @param {string} text - Text to escape
         * @returns {string} Escaped HTML
         */
        _escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    }

    /**
     * Initialize control panel when DOM is ready
     *
     * Checks for StateManager availability and creates panel instance.
     */
    document.addEventListener('DOMContentLoaded', () => {
        if (window.RSL && window.RSL.StateManager) {
            window.RSL.ControlPanel = new LayoutControlPanel(window.RSL.StateManager);
        }
    });

    /**
     * Also initialize if StateManager loads after DOM ready
     *
     * Handles async script loading scenarios.
     */
    window.addEventListener('rsl:statemanager:ready', () => {
        if (window.RSL && window.RSL.StateManager && !window.RSL.ControlPanel) {
            window.RSL.ControlPanel = new LayoutControlPanel(window.RSL.StateManager);
        }
    });

})();
