/**
 * AI Magic Theme Wizard JavaScript
 * Single page layout with page selection and real-time progress
 */
(function ($) {
    'use strict';

    const AIMagicWizard = {
        // State
        isRunning: false,
        isStopping: false,
        totalItems: 0,
        processedItems: 0,
        totalCost: 0,
        pages: [],
        selectedPages: {},

        init: function () {
            this.$form = $('#ai-magic-wizard-form');
            this.bindEvents();
            this.loadPages(); // Load pages on init
        },

        bindEvents: function () {
            const self = this;

            // Run button
            $('#ai-magic-wizard-run').on('click', function () {
                self.startWizard();
            });

            // Select all / Deselect all
            $('#ai-magic-select-all').on('click', function () {
                self.selectAllPages();
            });

            $('#ai-magic-deselect-all').on('click', function () {
                self.deselectAllPages();
            });

            // Stop button
            $('#ai-magic-wizard-stop').on('click', function () {
                self.stopWizard();
            });

            // Toggle all groups expand/collapse
            $('#ai-magic-toggle-groups').on('click', function () {
                self.toggleAllGroups();
            });

            // Provider change - update model list
            $('#ai-magic-provider').on('change', function () {
                const providerId = $(this).val();
                const models = aiMagicWizard.providerModels[providerId] || [];
                const $modelSelect = $('#ai-magic-model');

                $modelSelect.empty();
                models.forEach(function (model) {
                    const recommended = model.recommended ? ' ⭐' : '';
                    $modelSelect.append(
                        $('<option></option>')
                            .val(model.id)
                            .text(model.name + recommended)
                    );
                });
            });

            // Page selection change
            $(document).on('change', '.ai-magic-page-item input[type="checkbox"]', function () {
                const $item = $(this).closest('.ai-magic-page-item');
                const pageId = $item.data('page-id');

                if ($(this).is(':checked')) {
                    $item.addClass('selected');
                    self.selectedPages[pageId] = {
                        id: pageId,
                        title: $item.find('.ai-magic-page-item-title').text().trim(),
                        customName: ''
                    };
                } else {
                    $item.removeClass('selected');
                    delete self.selectedPages[pageId];
                }

                self.updateSelectedCount();
            });

            // Custom name input
            $(document).on('input', '.ai-magic-custom-name input', function () {
                const $item = $(this).closest('.ai-magic-page-item');
                const pageId = $item.data('page-id');

                if (self.selectedPages[pageId]) {
                    self.selectedPages[pageId].customName = $(this).val();
                }
            });

            // Prompt example chips
            $(document).on('click', '.ai-magic-example-chip', function () {
                let prompt = $(this).data('prompt');
                const $textarea = $('#ai-magic-prompt-textarea');

                // Remove "Language: X" from prompt - language is selected separately via dropdown
                prompt = prompt.replace(/\s*Language:\s*\w+\.?/gi, '');

                $textarea.val(prompt.trim());
                $textarea.focus();

                // Highlight selected chip
                $('.ai-magic-example-chip').removeClass('active');
                $(this).addClass('active');
            });

            // Group checkbox handler
            $(document).on('change', '.ai-magic-group-checkbox', function (e) {
                e.stopPropagation();
                const $group = $(this).closest('.ai-magic-page-group');
                const isChecked = $(this).is(':checked');

                $group.find('.ai-magic-page-item input[type="checkbox"]').each(function () {
                    const $item = $(this).closest('.ai-magic-page-item');
                    const pageId = $item.data('page-id');

                    if (isChecked) {
                        $(this).prop('checked', true);
                        $item.addClass('selected');
                        self.selectedPages[pageId] = {
                            id: pageId,
                            title: $item.find('.ai-magic-page-item-title').text().trim(),
                            customName: ''
                        };
                    } else {
                        $(this).prop('checked', false);
                        $item.removeClass('selected');
                        delete self.selectedPages[pageId];
                    }
                });

                self.updateSelectedCount();
            });
        },

        loadPages: function () {
            const self = this;
            const $list = $('#ai-magic-page-list-content');

            $list.html('<div style="padding: 20px; text-align: center; color: #666;"><span class="spinner is-active" style="float: none;"></span> ' + aiMagicWizard.i18n.loading + '</div>');

            $.ajax({
                url: aiMagicWizard.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'ai_magic_wizard_get_pages',
                    nonce: aiMagicWizard.nonce
                },
                success: function (response) {
                    if (response.success && response.data.pages) {
                        self.pages = response.data.pages;
                        self.renderPageList();
                    } else {
                        $list.html('<div class="ai-magic-page-list-empty">' + aiMagicWizard.i18n.noPages + '</div>');
                    }
                },
                error: function () {
                    $list.html('<div class="ai-magic-page-list-empty">' + aiMagicWizard.i18n.networkError + '</div>');
                }
            });
        },

        renderPageList: function () {
            const self = this;
            const $list = $('#ai-magic-page-list-content');

            if (!this.pages || !this.pages.length) {
                $list.html('<div class="ai-magic-page-list-empty">' + aiMagicWizard.i18n.noPages + '</div>');
                return;
            }

            // Group pages by post type
            const groups = {};
            this.pages.forEach(function (page) {
                if (!groups[page.post_type]) {
                    groups[page.post_type] = [];
                }
                groups[page.post_type].push(page);
            });

            let html = '';

            // Render each group
            Object.keys(groups).forEach(function (postType) {
                const pages = groups[postType];

                // Check if all pages in group are selected
                const allSelected = pages.every(function (p) { return self.selectedPages[p.id]; });
                const groupChecked = allSelected ? 'checked' : '';

                html += '<div class="ai-magic-page-group" data-group-type="' + self.escapeHtml(postType) + '">';
                html += '<div class="ai-magic-page-group-header" data-group="' + self.escapeHtml(postType) + '">';
                html += '<input type="checkbox" class="ai-magic-group-checkbox" ' + groupChecked + '>';
                html += '<span class="dashicons dashicons-arrow-down"></span>';
                html += '<span class="ai-magic-page-group-title">' + self.escapeHtml(postType) + '</span>';
                html += '<span class="ai-magic-page-group-count">' + pages.length + '</span>';
                html += '<div class="ai-magic-group-actions">';
                const toggleLabel = allSelected ? aiMagicWizard.i18n.deselectAll : aiMagicWizard.i18n.selectAll;
                html += '<button type="button" class="ai-magic-group-toggle" data-group="' + self.escapeHtml(postType) + '">' + toggleLabel + '</button>';
                html += '</div>';
                html += '</div>';
                html += '<div class="ai-magic-page-group-content">';

                pages.forEach(function (page) {
                    const selectedPage = self.selectedPages[page.id] || {};
                    const isSelected = selectedPage.id ? 'selected' : '';
                    const isChecked = selectedPage.id ? 'checked' : '';
                    const customName = selectedPage.customName || '';

                    html += '<div class="ai-magic-page-item ' + isSelected + '" data-page-id="' + page.id + '">';
                    html += '<input type="checkbox" ' + isChecked + '>';
                    html += '<div class="ai-magic-page-item-content">';
                    html += '<div class="ai-magic-page-item-title">' + self.escapeHtml(page.title) + '</div>';
                    html += '<div class="ai-magic-page-item-meta">';
                    html += '<span><span class="dashicons dashicons-calendar"></span>' + page.date + '</span>';
                    html += '</div>';
                    html += '<div class="ai-magic-custom-name">';
                    html += '<label class="ai-magic-custom-name-label">' + aiMagicWizard.i18n.customNameLabel + '</label>';
                    html += '<input type="text" value="' + self.escapeHtml(customName) + '" placeholder="' + aiMagicWizard.i18n.customNamePlaceholder + '">';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                });

                html += '</div>';
                html += '</div>';
            });

            $list.html(html);
            this.updateSelectedCount();

            // Toggle group collapse (only when clicking on non-button areas)
            $(document).off('click', '.ai-magic-page-group-header').on('click', '.ai-magic-page-group-header', function (e) {
                // Don't toggle if clicking on buttons or checkbox
                if ($(e.target).closest('.ai-magic-group-actions, .ai-magic-group-checkbox').length) {
                    return;
                }
                const $group = $(this).closest('.ai-magic-page-group');
                $group.toggleClass('collapsed');
                $(this).find('.dashicons-arrow-down, .dashicons-arrow-right').first().toggleClass('dashicons-arrow-down dashicons-arrow-right');
            });

            // Group toggle button (select/deselect)
            $(document).off('click', '.ai-magic-group-toggle').on('click', '.ai-magic-group-toggle', function (e) {
                e.stopPropagation();
                const groupType = $(this).data('group');
                self.toggleGroupPages(groupType);
            });
        },

        toggleGroupPages: function (groupType) {
            const self = this;
            const groupPages = this.pages.filter(function (page) {
                return page.post_type === groupType;
            });

            // Check if all pages in group are currently selected
            const allSelected = groupPages.every(function (p) { return self.selectedPages[p.id]; });

            if (allSelected) {
                // Deselect all in group
                groupPages.forEach(function (page) {
                    delete self.selectedPages[page.id];
                });
            } else {
                // Select all in group
                groupPages.forEach(function (page) {
                    self.selectedPages[page.id] = {
                        id: page.id,
                        title: page.title,
                        customName: self.selectedPages[page.id] ? self.selectedPages[page.id].customName : ''
                    };
                });
            }
            this.renderPageList();
        },

        selectAllPages: function () {
            const self = this;
            this.pages.forEach(function (page) {
                self.selectedPages[page.id] = {
                    id: page.id,
                    title: page.title,
                    customName: ''
                };
            });
            this.renderPageList();
        },

        deselectAllPages: function () {
            this.selectedPages = {};
            this.renderPageList();
        },

        toggleAllGroups: function () {
            const $groups = $('.ai-magic-page-group');
            const $toggleBtn = $('#ai-magic-toggle-groups .dashicons');
            const allCollapsed = $groups.filter('.collapsed').length === $groups.length;

            if (allCollapsed) {
                // Expand all
                $groups.removeClass('collapsed');
                $groups.find('.ai-magic-page-group-header .dashicons-arrow-right').removeClass('dashicons-arrow-right').addClass('dashicons-arrow-down');
                $toggleBtn.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
            } else {
                // Collapse all
                $groups.addClass('collapsed');
                $groups.find('.ai-magic-page-group-header .dashicons-arrow-down').removeClass('dashicons-arrow-down').addClass('dashicons-arrow-right');
                $toggleBtn.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
            }
        },

        updateSelectedCount: function () {
            const count = Object.keys(this.selectedPages).length;
            $('#ai-magic-selected-count').text(count);
            $('#ai-magic-wizard-run').prop('disabled', count === 0);
        },

        startWizard: function () {
            const self = this;
            const prompt = $('textarea[name="prompt"]').val().trim();
            const language = $('#ai-magic-language').val();
            const provider = $('#ai-magic-provider').val();
            const model = $('#ai-magic-model').val();

            if (!prompt) {
                alert(aiMagicWizard.i18n.promptRequired);
                return;
            }

            const selectedCount = Object.keys(this.selectedPages).length;
            if (selectedCount === 0) {
                alert(aiMagicWizard.i18n.selectPages);
                return;
            }

            // Show progress section
            $('#ai-magic-progress-section').show();

            // Scroll to progress
            $('html, body').animate({
                scrollTop: $('#ai-magic-progress-section').offset().top - 50
            }, 500);

            this.isRunning = true;
            this.isStopping = false;
            this.totalItems = selectedCount;
            this.processedItems = 0;
            this.totalCost = 0;

            // Clear log
            $('#ai-magic-log').empty();

            // Update stats
            $('#ai-magic-stats-processed').text('0 / ' + this.totalItems);
            $('#ai-magic-stats-cost').text('$0.0000');
            $('#ai-magic-progress-bar').css('width', '0%');

            // Disable run button
            $('#ai-magic-wizard-run').prop('disabled', true);

            // Process pages
            const pageIds = Object.keys(this.selectedPages);
            this.processNextPage(pageIds, 0, prompt, language, provider, model);
        },

        processNextPage: function (pageIds, index, prompt, language, provider, model) {
            const self = this;

            if (index >= pageIds.length || this.isStopping) {
                this.finishWizard();
                return;
            }

            // Check if stopped
            $.post(aiMagicWizard.ajaxUrl, {
                action: 'ai_magic_wizard_check_stop',
                nonce: aiMagicWizard.nonce
            }, function (response) {
                if (response.success && response.data.stopped) {
                    self.isStopping = true;
                    self.finishWizard();
                    return;
                }

                const pageId = pageIds[index];
                const pageData = self.selectedPages[pageId];

                // Update current item
                $('.ai-magic-current-item-name').text(pageData.customName || pageData.title);

                $.ajax({
                    url: aiMagicWizard.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'ai_magic_wizard_process_page',
                        nonce: aiMagicWizard.nonce,
                        page_id: pageId,
                        custom_name: pageData.customName || '',
                        prompt: prompt,
                        language: language,
                        provider: provider,
                        model: model
                    },
                    success: function (response) {
                        self.processedItems++;

                        if (response.success) {
                            self.totalCost += parseFloat(response.data.cost) || 0;
                            self.addLogEntry({
                                status: 'success',
                                title: pageData.customName || pageData.title,
                                oldText: response.data.old_text || '',
                                newText: response.data.new_text || '',
                                cost: response.data.cost || 0,
                                editUrl: response.data.edit_url || '',
                                viewUrl: response.data.view_url || ''
                            });
                        } else {
                            self.addLogEntry({
                                status: 'error',
                                title: pageData.customName || pageData.title,
                                oldText: response.data.message || aiMagicWizard.i18n.processError
                            });
                        }

                        // Update progress
                        const progress = (self.processedItems / self.totalItems) * 100;
                        $('#ai-magic-progress-bar').css('width', progress + '%');
                        $('#ai-magic-stats-processed').text(self.processedItems + ' / ' + self.totalItems);
                        $('#ai-magic-stats-cost').text('$' + self.totalCost.toFixed(4));

                        // Process next
                        self.processNextPage(pageIds, index + 1, prompt, language, provider, model);
                    },
                    error: function () {
                        self.processedItems++;
                        self.addLogEntry({
                            status: 'error',
                            title: pageData.customName || pageData.title,
                            oldText: aiMagicWizard.i18n.networkError
                        });

                        // Update progress
                        const progress = (self.processedItems / self.totalItems) * 100;
                        $('#ai-magic-progress-bar').css('width', progress + '%');
                        $('#ai-magic-stats-processed').text(self.processedItems + ' / ' + self.totalItems);

                        // Process next
                        self.processNextPage(pageIds, index + 1, prompt, language, provider, model);
                    }
                });
            });
        },

        stopWizard: function () {
            const self = this;
            this.isStopping = true;

            $('#ai-magic-wizard-stop').text(aiMagicWizard.i18n.stopping).prop('disabled', true);

            $.post(aiMagicWizard.ajaxUrl, {
                action: 'ai_magic_wizard_stop',
                nonce: aiMagicWizard.nonce
            });
        },

        finishWizard: function () {
            this.isRunning = false;

            // Hide spinner
            $('#ai-magic-current-item .spinner').removeClass('is-active');

            // Update UI
            if (this.isStopping) {
                $('.ai-magic-current-item-label').text(aiMagicWizard.i18n.stopped);
                $('.ai-magic-current-item-name').text(aiMagicWizard.i18n.stoppedMessage);
            } else {
                $('.ai-magic-current-item-label').text(aiMagicWizard.i18n.completed);
                $('.ai-magic-current-item-name').text(aiMagicWizard.i18n.completedMessage);
            }

            // Hide stop button, show run again
            $('#ai-magic-wizard-stop').hide();

            // Re-enable run button
            $('#ai-magic-wizard-run').prop('disabled', false);

            // Clear stop flag
            $.post(aiMagicWizard.ajaxUrl, {
                action: 'ai_magic_wizard_clear_stop',
                nonce: aiMagicWizard.nonce
            });
        },

        addLogEntry: function (entry) {
            const icon = entry.status === 'success' ? 'dashicons-yes-alt' : 'dashicons-warning';

            let diffHtml = '';
            if (entry.status === 'success' && entry.oldText && entry.newText) {
                const shortOld = entry.oldText.length > 50 ? entry.oldText.substring(0, 50) + '...' : entry.oldText;
                const shortNew = entry.newText.length > 50 ? entry.newText.substring(0, 50) + '...' : entry.newText;

                diffHtml = '<div class="ai-magic-log-diff">';
                // Before section - summary visible, details expandable
                diffHtml += '<details class="ai-magic-log-diff-row before">';
                diffHtml += '<summary>';
                diffHtml += '<span class="ai-magic-log-diff-label">' + aiMagicWizard.i18n.before + '</span>';
                diffHtml += '<span class="ai-magic-log-diff-preview">' + this.escapeHtml(shortOld) + '</span>';
                diffHtml += '</summary>';
                diffHtml += '<div class="ai-magic-log-diff-text">' + this.escapeHtml(entry.oldText) + '</div>';
                diffHtml += '</details>';
                // After section - summary visible, details expandable
                diffHtml += '<details class="ai-magic-log-diff-row after">';
                diffHtml += '<summary>';
                diffHtml += '<span class="ai-magic-log-diff-label">' + aiMagicWizard.i18n.after + '</span>';
                diffHtml += '<span class="ai-magic-log-diff-preview">' + this.escapeHtml(shortNew) + '</span>';
                diffHtml += '</summary>';
                diffHtml += '<div class="ai-magic-log-diff-text">' + this.escapeHtml(entry.newText) + '</div>';
                diffHtml += '</details>';
                diffHtml += '</div>';
            } else if (entry.status === 'error') {
                diffHtml = '<div class="ai-magic-log-diff error">';
                diffHtml += '<div class="ai-magic-log-diff-row before">';
                diffHtml += '<span class="ai-magic-log-diff-label">' + aiMagicWizard.i18n.error + '</span>';
                diffHtml += '<div class="ai-magic-log-diff-text">' + this.escapeHtml(entry.oldText) + '</div>';
                diffHtml += '</div>';
                diffHtml += '</div>';
            }

            // Build links HTML
            let linksHtml = '';
            if (entry.editUrl || entry.viewUrl) {
                linksHtml = '<div class="ai-magic-log-links">';
                if (entry.editUrl) {
                    linksHtml += '<a href="' + entry.editUrl + '" target="_blank" class="edit-link"><span class="dashicons dashicons-edit"></span> Edit</a>';
                }
                if (entry.viewUrl) {
                    linksHtml += '<a href="' + entry.viewUrl + '" target="_blank" class="edit-link"><span class="dashicons dashicons-visibility"></span> View</a>';
                }
                linksHtml += '</div>';
            }

            let costHtml = '';
            if (entry.cost > 0) {
                costHtml = '<div class="ai-magic-log-cost">$' + parseFloat(entry.cost).toFixed(4) + '</div>';
            }

            const $entry = $('<div class="ai-magic-log-item ' + entry.status + '">' +
                '<div class="ai-magic-log-icon"><span class="dashicons ' + icon + '"></span></div>' +
                '<div class="ai-magic-log-content">' +
                '<div class="ai-magic-log-title">' + this.escapeHtml(entry.title) + linksHtml + '</div>' +
                diffHtml +
                '</div>' +
                costHtml +
                '</div>');

            $('#ai-magic-log').prepend($entry);
        },

        escapeHtml: function (text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    };

    $(document).ready(function () {
        if ($('#ai-magic-wizard-form').length) {
            AIMagicWizard.init();
        }
    });

})(jQuery);
