(function() {
    'use strict';

    window.IDVE = window.IDVE || {};

    var MODE_CONFIG = {
        generate_page: {
            label: 'Generate Page',
            desc: 'Replace the entire page with AI-generated content.',
            placeholder: 'Describe the page you want to create, e.g. "Create a landing page for a bakery with a hero section, about us, menu highlights, and contact info"'
        },
        add_section: {
            label: 'Add Section(s)',
            desc: 'Append new sections to the current page.',
            placeholder: 'Describe the section(s) to add, e.g. "Add a testimonials section with 3 customer quotes in columns"'
        },
        refine_page: {
            label: 'Refine Page',
            desc: 'Modify the current page — change styles, text, layouts, or other properties.',
            placeholder: 'Describe the changes, e.g. "Make all headings blue, increase section spacing, and add drop shadows to the card columns"'
        },
        create_class: {
            label: 'Create CSS Class',
            desc: 'Generate a reusable CSS class for the global stylesheet.',
            placeholder: 'Describe the style, e.g. "Create a card-shadow class with a subtle box shadow and rounded corners"'
        }
    };

    IDVE.AI = {
        currentMode: 'generate_page',

        init: function() {
            if (!idveData.aiEnabled) return;

            // Insert AI button into toolbar before the spacer
            var spacer = document.querySelector('#idve-toolbar .idve-toolbar-spacer');
            if (!spacer) return;

            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'idve-btn idve-btn-ai';
            btn.innerHTML = '<span class="dashicons dashicons-admin-generic"></span> AI';
            btn.title = 'AI Assistant';
            btn.addEventListener('click', this.openModal.bind(this));
            spacer.parentNode.insertBefore(btn, spacer);
        },

        openModal: function() {
            var self = this;
            this.currentMode = 'generate_page';

            var overlay = document.createElement('div');
            overlay.className = 'idve-modal-overlay';

            var html = '<div class="idve-modal idve-ai-modal">';
            html += '<div class="idve-modal-header">';
            html += '<h3>AI Assistant</h3>';
            html += '<button type="button" class="idve-modal-close">&times;</button>';
            html += '</div>';

            html += '<div class="idve-modal-body">';

            // Mode selector
            html += '<div class="idve-ai-modes">';
            var modes = ['generate_page', 'add_section', 'refine_page', 'create_class'];
            for (var i = 0; i < modes.length; i++) {
                var m = modes[i];
                var cfg = MODE_CONFIG[m];
                var checked = m === 'generate_page' ? ' checked' : '';
                html += '<label class="idve-ai-mode">';
                html += '<input type="radio" name="idve-ai-mode" value="' + m + '"' + checked + '>';
                html += '<span>' + cfg.label + '</span>';
                html += '</label>';
            }
            html += '</div>';

            // Mode description
            html += '<p class="idve-ai-mode-desc">' + MODE_CONFIG.generate_page.desc + '</p>';

            // Prompt textarea
            html += '<textarea id="idve-ai-prompt" rows="5" placeholder="' + MODE_CONFIG.generate_page.placeholder + '"></textarea>';

            // Error area
            html += '<div class="idve-ai-error" style="display:none"></div>';

            // Loading area
            html += '<div class="idve-ai-loading" style="display:none">';
            html += '<div class="idve-ai-spinner"></div>';
            html += '<span>Generating...</span>';
            html += '</div>';

            html += '</div>';

            html += '<div class="idve-modal-footer">';
            html += '<button type="button" class="idve-btn idve-ai-cancel">Cancel</button>';
            html += '<button type="button" class="idve-btn idve-btn-primary idve-ai-generate">Generate</button>';
            html += '</div>';
            html += '</div>';

            overlay.innerHTML = html;
            document.body.appendChild(overlay);

            // Store references
            this._overlay = overlay;
            this._promptEl = overlay.querySelector('#idve-ai-prompt');
            this._errorEl = overlay.querySelector('.idve-ai-error');
            this._loadingEl = overlay.querySelector('.idve-ai-loading');
            this._generateBtn = overlay.querySelector('.idve-ai-generate');
            this._descEl = overlay.querySelector('.idve-ai-mode-desc');

            // Close events
            overlay.querySelector('.idve-modal-close').addEventListener('click', function() { self.closeModal(); });
            overlay.querySelector('.idve-ai-cancel').addEventListener('click', function() { self.closeModal(); });
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) self.closeModal();
            });

            // Mode switch
            var radios = overlay.querySelectorAll('input[name="idve-ai-mode"]');
            for (var r = 0; r < radios.length; r++) {
                radios[r].addEventListener('change', function() {
                    self.currentMode = this.value;
                    var cfg = MODE_CONFIG[this.value];
                    self._descEl.textContent = cfg.desc;
                    self._promptEl.placeholder = cfg.placeholder;
                });
            }

            // Generate
            this._generateBtn.addEventListener('click', function() { self.submit(); });

            // Focus prompt
            this._promptEl.focus();
        },

        closeModal: function() {
            if (this._overlay && this._overlay.parentNode) {
                this._overlay.parentNode.removeChild(this._overlay);
            }
            this._overlay = null;
        },

        showError: function(msg) {
            this._errorEl.textContent = msg;
            this._errorEl.style.display = 'block';
        },

        hideError: function() {
            this._errorEl.style.display = 'none';
        },

        submit: function() {
            var self = this;
            var prompt = this._promptEl.value.trim();

            if (!prompt) {
                this.showError('Please enter a prompt.');
                return;
            }

            this.hideError();
            this._loadingEl.style.display = 'flex';
            this._generateBtn.disabled = true;
            this._promptEl.disabled = true;

            // Build context
            var context = {};
            context.currentTree = IDVE.state.tree;

            fetch(idveData.restUrl + 'ai/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': idveData.nonce
                },
                body: JSON.stringify({
                    prompt: prompt,
                    mode: self.currentMode,
                    context: context
                })
            })
            .then(function(res) {
                return res.json().then(function(json) {
                    if (!res.ok) {
                        throw new Error(json.message || 'AI request failed (HTTP ' + res.status + ')');
                    }
                    return json;
                });
            })
            .then(function(json) {
                if (!json.success || !json.data) {
                    throw new Error(json.message || 'Invalid response from AI.');
                }
                self.applyResult(json.data);
                self.closeModal();
            })
            .catch(function(err) {
                self.showError(err.message || 'An error occurred. Please try again.');
                self._loadingEl.style.display = 'none';
                self._generateBtn.disabled = false;
                self._promptEl.disabled = false;
            });
        },

        applyResult: function(data) {
            var mode = this.currentMode;

            // Push undo state before making changes
            IDVE.History.push();

            switch (mode) {
                case 'generate_page':
                    if (data.tree) {
                        if (!confirm('This will replace your entire page. Continue?')) {
                            IDVE.History.undo();
                            return;
                        }
                        IDVE.state.tree = data.tree;
                    }
                    break;

                case 'add_section':
                    if (data.sections && data.sections.length) {
                        for (var i = 0; i < data.sections.length; i++) {
                            IDVE.state.tree.sections.push(data.sections[i]);
                        }
                    }
                    break;

                case 'refine_page':
                    if (data.tree) {
                        IDVE.state.tree = data.tree;
                    }
                    break;

                case 'create_class':
                    if (data.globalCss) {
                        this.appendGlobalCss(data.globalCss);
                    }
                    return; // Don't re-render canvas for CSS-only changes
            }

            // Append global CSS if AI created classes alongside the tree
            if (data.globalCss) {
                this.appendGlobalCss(data.globalCss);
            }

            IDVE.Editor.renderCanvas();
            IDVE.Editor.markDirty();
        },

        openBlockPrompt: function() {
            var self = this;
            var modal = document.querySelector('.idve-settings-modal');
            if (!modal) return;

            // If prompt bar already exists, focus it
            var existing = modal.querySelector('.idve-ai-block-prompt');
            if (existing) {
                existing.querySelector('textarea').focus();
                return;
            }

            // Build prompt bar — inserted between modal-body and modal-footer
            var bar = document.createElement('div');
            bar.className = 'idve-ai-block-prompt';
            bar.innerHTML =
                '<div class="idve-ai-block-prompt-inner">' +
                '<textarea rows="2" placeholder="Describe changes, e.g. \'Make the text larger and change color to blue\'"></textarea>' +
                '<div class="idve-ai-block-prompt-actions">' +
                '<button type="button" class="idve-btn idve-ai-block-cancel">Cancel</button>' +
                '<button type="button" class="idve-btn idve-btn-ai idve-ai-block-generate">Generate</button>' +
                '</div>' +
                '<div class="idve-ai-block-error" style="display:none"></div>' +
                '<div class="idve-ai-block-loading" style="display:none">' +
                '<div class="idve-ai-spinner"></div>' +
                '<span>Generating...</span>' +
                '</div>' +
                '</div>';

            var footer = modal.querySelector('.idve-modal-footer');
            footer.parentNode.insertBefore(bar, footer);

            var textarea = bar.querySelector('textarea');
            textarea.focus();

            // Cancel — remove prompt bar
            bar.querySelector('.idve-ai-block-cancel').addEventListener('click', function() {
                bar.parentNode.removeChild(bar);
            });

            // Generate
            bar.querySelector('.idve-ai-block-generate').addEventListener('click', function() {
                self.submitBlockEdit(bar);
            });
        },

        submitBlockEdit: function(bar) {
            var self = this;
            var textarea = bar.querySelector('textarea');
            var errorEl = bar.querySelector('.idve-ai-block-error');
            var loadingEl = bar.querySelector('.idve-ai-block-loading');
            var generateBtn = bar.querySelector('.idve-ai-block-generate');
            var prompt = textarea.value.trim();

            if (!prompt) {
                errorEl.textContent = 'Please enter a prompt.';
                errorEl.style.display = 'block';
                return;
            }

            errorEl.style.display = 'none';
            loadingEl.style.display = 'flex';
            generateBtn.disabled = true;
            textarea.disabled = true;

            // Build context with current block
            var context = {};
            context.currentTree = IDVE.state.tree;
            var blockId = IDVE.Panel.currentId;
            var found = IDVE.Editor.findElement(blockId);
            if (found) {
                context.selectedElement = found.element;
                context.selectedType = found.type;
            }

            fetch(idveData.restUrl + 'ai/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': idveData.nonce
                },
                body: JSON.stringify({
                    prompt: prompt,
                    mode: 'edit_element',
                    context: context
                })
            })
            .then(function(res) {
                return res.json().then(function(json) {
                    if (!res.ok) throw new Error(json.message || 'AI request failed');
                    return json;
                });
            })
            .then(function(json) {
                if (!json.success || !json.data || !json.data.element) {
                    throw new Error(json.message || 'Invalid response from AI.');
                }

                // Push undo state
                IDVE.History.push();

                // Replace block in tree
                var found = IDVE.Editor.findElement(blockId);
                if (found) {
                    json.data.element.id = found.element.id;
                    if (found.element.type) json.data.element.type = found.element.type;
                    found.parent[found.index] = json.data.element;
                }

                // Re-render canvas and re-open settings modal with updated block
                IDVE.Editor.renderCanvas();
                IDVE.Editor.markDirty();

                // Re-open the settings panel for the same block to show changes
                IDVE.Panel.closeModal();
                IDVE.Panel.openModal(IDVE.state.selectedType || 'block', blockId);
            })
            .catch(function(err) {
                errorEl.textContent = err.message || 'An error occurred.';
                errorEl.style.display = 'block';
                loadingEl.style.display = 'none';
                generateBtn.disabled = false;
                textarea.disabled = false;
            });
        },

        formatCss: function(css) {
            // Normalize whitespace
            css = css.replace(/\s+/g, ' ').trim();
            // Newline after opening brace
            css = css.replace(/\{\s*/g, ' {\n    ');
            // Newline before closing brace
            css = css.replace(/\s*\}\s*/g, '\n}\n\n');
            // Newline after semicolons (within rules)
            css = css.replace(/;\s*/g, ';\n    ');
            // Clean up trailing whitespace on last property before }
            css = css.replace(/;\n    \n\}/g, ';\n}');
            // Remove trailing whitespace/newlines
            return css.trim();
        },

        appendGlobalCss: function(newCss) {
            var self = this;
            // Fetch current global styles, append formatted new CSS, and save
            fetch(idveData.restUrl + 'global-styles', {
                headers: { 'X-WP-Nonce': idveData.nonce }
            })
            .then(function(res) { return res.json(); })
            .then(function(json) {
                var existing = (json.success && json.css) ? json.css : '';
                var formatted = self.formatCss(newCss);
                var combined = existing ? existing + '\n\n' + formatted : formatted;
                return fetch(idveData.restUrl + 'global-styles', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': idveData.nonce
                    },
                    body: JSON.stringify({ css: combined })
                });
            })
            .then(function(res) { return res.json(); })
            .then(function(json) {
                if (json.success) {
                    // Brief visual feedback — no canvas change needed
                    var btn = document.querySelector('.idve-btn-ai');
                    if (btn) {
                        var orig = btn.innerHTML;
                        btn.innerHTML = '<span class="dashicons dashicons-yes"></span> Added';
                        setTimeout(function() { btn.innerHTML = orig; }, 2000);
                    }
                }
            })
            .catch(function() {
                // Silently fail — user can manually add via global styles editor
            });
        }
    };

    // Hook into editor activation
    var origBuildChrome = IDVE.Editor.buildChrome;
    IDVE.Editor.buildChrome = function() {
        origBuildChrome.call(this);
        IDVE.AI.init();
    };
})();
