/**
 * Onboarding Wizard JavaScript
 *
 * Handles the wizard modal for empty sites during trial signup.
 *
 * @package Simple_AI_Auto_Post
 * @since 2.7.0
 */

(function($) {
    'use strict';

    var SaiapWizard = {
        $modal: null,
        $form: null,
        $submitBtn: null,
        seedTopics: [],
        locations: [],
        isSubmitting: false,
        editMode: false,

        /**
         * Initialize the wizard.
         */
        init: function() {
            this.$modal = $('#saiap-onboarding-wizard-modal');
            this.$form = $('#saiap-onboarding-wizard-form');
            this.$submitBtn = $('#saiap-wizard-submit');

            if (!this.$modal.length) {
                return;
            }

            this.bindEvents();
        },

        /**
         * Bind event handlers.
         */
        bindEvents: function() {
            var self = this;

            // Back button
            this.$modal.on('click', '.saiap-wizard-modal__back', function(e) {
                e.preventDefault();
                self.hide();
            });

            // Backdrop click
            this.$modal.on('click', '.saiap-wizard-modal__backdrop', function(e) {
                e.preventDefault();
                self.hide();
            });

            // Escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && self.$modal.is(':visible')) {
                    self.hide();
                }
            });

            // Seed topics tag input
            this.initTagInput();

            // Competitor URL repeater
            this.initRepeater();

            // Form submission
            this.$form.on('submit', function(e) {
                e.preventDefault();
                self.submit();
            });
        },

        /**
         * Initialize the tag input for seed topics.
         */
        initTagInput: function() {
            var self = this;

            // Seed topics tag input
            var $topicsInput = $('#saiap-wizard-seed-topics-input');
            var $topicsList = $('#saiap-wizard-seed-topics-list');
            var $topicsHidden = $('#saiap-wizard-seed-topics');

            $topicsInput.on('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ',') {
                    e.preventDefault();
                    var value = $.trim($topicsInput.val().replace(/,/g, ''));

                    if (value) {
                        if (self.addTag(value, self.seedTopics, $topicsList, $topicsHidden)) {
                            $topicsInput.val('');
                        }
                    }
                }

                // Backspace to remove last tag
                if (e.key === 'Backspace' && !$topicsInput.val() && self.seedTopics.length) {
                    self.removeTag(self.seedTopics.length - 1, self.seedTopics, $topicsList, $topicsHidden);
                }
            });

            // Also add on blur if there's content
            $topicsInput.on('blur', function() {
                var value = $.trim($topicsInput.val().replace(/,/g, ''));
                if (value) {
                    if (self.addTag(value, self.seedTopics, $topicsList, $topicsHidden)) {
                        $topicsInput.val('');
                    }
                }
            });

            // Locations tag input
            var $locationsInput = $('#saiap-wizard-locations-input');
            var $locationsList = $('#saiap-wizard-locations-list');
            var $locationsHidden = $('#saiap-wizard-locations');

            if ($locationsInput.length) {
                $locationsInput.on('keydown', function(e) {
                    if (e.key === 'Enter' || e.key === ',') {
                        e.preventDefault();
                        var value = $.trim($locationsInput.val().replace(/,/g, ''));

                        if (value) {
                            if (self.addTag(value, self.locations, $locationsList, $locationsHidden)) {
                                $locationsInput.val('');
                            }
                        }
                    }

                    // Backspace to remove last tag
                    if (e.key === 'Backspace' && !$locationsInput.val() && self.locations.length) {
                        self.removeTag(self.locations.length - 1, self.locations, $locationsList, $locationsHidden);
                    }
                });

                // Also add on blur if there's content
                $locationsInput.on('blur', function() {
                    var value = $.trim($locationsInput.val().replace(/,/g, ''));
                    if (value) {
                        if (self.addTag(value, self.locations, $locationsList, $locationsHidden)) {
                            $locationsInput.val('');
                        }
                    }
                });
            }
        },

        /**
         * Add a tag to a tags array. (Generic for topics and locations)
         */
        addTag: function(value, tagsArray, $list, $hidden) {
            // Check for duplicates (case-insensitive)
            var lowerValue = value.toLowerCase();
            for (var i = 0; i < tagsArray.length; i++) {
                if (tagsArray[i].toLowerCase() === lowerValue) {
                    return false;
                }
            }

            tagsArray.push(value);
            this.updateTagsList(tagsArray, $list, $hidden);
            return true;
        },

        /**
         * Remove a tag by index from a tags array. (Generic for topics and locations)
         */
        removeTag: function(index, tagsArray, $list, $hidden) {
            tagsArray.splice(index, 1);
            this.updateTagsList(tagsArray, $list, $hidden);
        },

        /**
         * Update the tags list display and hidden input. (Generic for topics and locations)
         */
        updateTagsList: function(tagsArray, $list, $hidden) {
            var self = this;
            $list.empty();

            tagsArray.forEach(function(tag, index) {
                var $tag = $('<span class="saiap-wizard__tag">' +
                    '<span class="saiap-wizard__tag-text">' + self.escapeHtml(tag) + '</span>' +
                    '<button type="button" class="saiap-wizard__tag-remove" data-index="' + index + '" aria-label="Remove">' +
                    '<span class="dashicons dashicons-no-alt"></span>' +
                    '</button>' +
                    '</span>');
                $list.append($tag);
            });

            // Bind remove handlers
            $list.find('.saiap-wizard__tag-remove').on('click', function() {
                var idx = $(this).data('index');
                self.removeTag(idx, tagsArray, $list, $hidden);
            });

            // Update hidden input
            $hidden.val(JSON.stringify(tagsArray));
        },

        /**
         * Legacy method for backwards compatibility with prefill.
         */
        addTopic: function(topic, $list, $hidden) {
            return this.addTag(topic, this.seedTopics, $list, $hidden);
        },

        /**
         * Initialize URL repeater fields.
         */
        initRepeater: function() {
            var self = this;
            var repeaters = [
                { container: '#saiap-wizard-competitor-urls', addBtn: '#saiap-wizard-add-competitor', name: 'competitor_urls[]', placeholder: 'https://example.com' },
                { container: '#saiap-wizard-example-posts', addBtn: '#saiap-wizard-add-example-post', name: 'example_posts[]', placeholder: 'https://yourblog.com/best-post' }
            ];
            var maxItems = 10;

            repeaters.forEach(function(cfg) {
                var $container = $(cfg.container);
                var $addBtn = $(cfg.addBtn);
                if (!$container.length) return;

                $addBtn.on('click', function() {
                    var itemCount = $container.find('.saiap-wizard__repeater-item').length;
                    if (itemCount >= maxItems) return;

                    var $newItem = $('<div class="saiap-wizard__repeater-item">' +
                        '<input type="url" name="' + cfg.name + '" class="saiap-wizard__input saiap-wizard__repeater-input" placeholder="' + cfg.placeholder + '" />' +
                        '<button type="button" class="saiap-wizard__repeater-remove" aria-label="Remove">' +
                        '<span class="dashicons dashicons-no-alt"></span>' +
                        '</button>' +
                        '</div>');
                    $container.append($newItem);
                    self.updateRepeaterState($container, $addBtn, maxItems);
                });

                $container.on('click', '.saiap-wizard__repeater-remove', function() {
                    $(this).closest('.saiap-wizard__repeater-item').remove();
                    self.updateRepeaterState($container, $addBtn, maxItems);
                });
            });
        },

        /**
         * Update repeater button visibility.
         */
        updateRepeaterState: function($container, $addBtn, maxItems) {
            var $items = $container.find('.saiap-wizard__repeater-item');
            var count = $items.length;

            // Show/hide add button
            $addBtn.toggle(count < maxItems);

            // Show/hide remove buttons (hide if only one item)
            $items.find('.saiap-wizard__repeater-remove').toggle(count > 1);
        },

        /**
         * Clear all form fields (used before repopulating in edit mode).
         */
        clearForm: function() {
            // Clear text inputs
            $('#saiap-wizard-site-name').val('');
            $('#saiap-wizard-site-description').val('');
            $('#saiap-wizard-niche').val('');
            $('#saiap-wizard-target-audience').val('');

            // Clear seed topics
            this.seedTopics = [];
            $('#saiap-wizard-seed-topics-list').empty();
            $('#saiap-wizard-seed-topics').val('');

            // Clear locations
            this.locations = [];
            $('#saiap-wizard-locations-list').empty();
            $('#saiap-wizard-locations').val('');

            // Clear competitor URLs - reset to single empty input
            var $container = $('#saiap-wizard-competitor-urls');
            $container.find('.saiap-wizard__repeater-item').not(':first').remove();
            $container.find('input[name="competitor_urls[]"]').val('');

            // Clear example posts - reset to single empty input
            var $exContainer = $('#saiap-wizard-example-posts');
            $exContainer.find('.saiap-wizard__repeater-item').not(':first').remove();
            $exContainer.find('input[name="example_posts[]"]').val('');
        },

        /**
         * Show the wizard modal.
         *
         * @param {Object|null} prefillData Pre-filled wizard data from backend LLM analysis.
         */
        show: function(prefillData) {
            var self = this;

            // Check if we're in edit mode (editing existing business info)
            this.editMode = prefillData && prefillData.editMode === true;

            // In edit mode, clear the form first so we can fully repopulate with current data
            if (this.editMode) {
                this.clearForm();
            }

            // Populate form with prefill data if provided
            if (prefillData && typeof prefillData === 'object') {
                this.populateWithPrefill(prefillData);
            }

            this.$modal.fadeIn(200).attr('aria-hidden', 'false');
            $('body').addClass('saiap-wizard-open');

            // Focus first input that needs attention
            setTimeout(function() {
                // If site description is empty, focus it; otherwise focus the first empty required field
                var $siteDesc = $('#saiap-wizard-site-description');
                if (!$siteDesc.val()) {
                    $siteDesc.focus();
                } else {
                    var $niche = $('#saiap-wizard-niche');
                    if (!$niche.val()) {
                        $niche.focus();
                    } else if (self.seedTopics.length < 3) {
                        $('#saiap-wizard-seed-topics-input').focus();
                    }
                }
            }, 200);
        },

        /**
         * Populate wizard form fields with prefill data.
         *
         * @param {Object} prefillData Pre-filled data from backend.
         */
        populateWithPrefill: function(prefillData) {
            // Site name
            if (prefillData.site_name) {
                var $siteName = $('#saiap-wizard-site-name');
                if (!$siteName.val()) { // Only fill if empty
                    $siteName.val(prefillData.site_name);
                }
            }

            // Site description
            if (prefillData.site_description) {
                var $siteDesc = $('#saiap-wizard-site-description');
                if (!$siteDesc.val()) {
                    $siteDesc.val(prefillData.site_description);
                }
            }

            // Niche
            if (prefillData.niche) {
                var $niche = $('#saiap-wizard-niche');
                if (!$niche.val()) {
                    $niche.val(prefillData.niche);
                }
            }

            // Target audience
            if (prefillData.target_audience) {
                var $audience = $('#saiap-wizard-target-audience');
                if (!$audience.val()) {
                    $audience.val(prefillData.target_audience);
                }
            }

            // Seed topics (add as tags)
            if (prefillData.seed_topics && Array.isArray(prefillData.seed_topics)) {
                var $list = $('#saiap-wizard-seed-topics-list');
                var $hidden = $('#saiap-wizard-seed-topics');

                // Only add if no topics exist yet
                if (this.seedTopics.length === 0) {
                    for (var i = 0; i < prefillData.seed_topics.length; i++) {
                        this.addTopic(prefillData.seed_topics[i], $list, $hidden);
                    }
                }
            }

            // Competitor URLs
            if (prefillData.competitor_urls && Array.isArray(prefillData.competitor_urls) && prefillData.competitor_urls.length > 0) {
                var $container = $('#saiap-wizard-competitor-urls');
                var $existingInputs = $container.find('input[name="competitor_urls[]"]');

                // Only fill if first input is empty
                if ($existingInputs.length > 0 && !$existingInputs.first().val()) {
                    prefillData.competitor_urls.forEach(function(url, index) {
                        if (index === 0) {
                            $existingInputs.first().val(url);
                        } else if (index < 10) {
                            // Add new input for additional URLs (max 10)
                            var $newItem = $('<div class="saiap-wizard__repeater-item">' +
                                '<input type="url" name="competitor_urls[]" class="saiap-wizard__input saiap-wizard__repeater-input" value="' + url + '" />' +
                                '<button type="button" class="saiap-wizard__repeater-remove" aria-label="Remove">' +
                                '<span class="dashicons dashicons-no-alt"></span>' +
                                '</button>' +
                                '</div>');
                            $container.append($newItem);
                        }
                    });
                }
            }

            // Example posts
            if (prefillData.example_posts && Array.isArray(prefillData.example_posts) && prefillData.example_posts.length > 0) {
                var $exContainer = $('#saiap-wizard-example-posts');
                var $exInputs = $exContainer.find('input[name="example_posts[]"]');

                if ($exInputs.length > 0 && !$exInputs.first().val()) {
                    prefillData.example_posts.forEach(function(url, index) {
                        if (index === 0) {
                            $exInputs.first().val(url);
                        } else if (index < 10) {
                            var $newItem = $('<div class="saiap-wizard__repeater-item">' +
                                '<input type="url" name="example_posts[]" class="saiap-wizard__input saiap-wizard__repeater-input" value="' + url + '" />' +
                                '<button type="button" class="saiap-wizard__repeater-remove" aria-label="Remove">' +
                                '<span class="dashicons dashicons-no-alt"></span>' +
                                '</button>' +
                                '</div>');
                            $exContainer.append($newItem);
                        }
                    });
                }
            }

            // Locations (add as tags)
            if (prefillData.locations && Array.isArray(prefillData.locations)) {
                var $locationsList = $('#saiap-wizard-locations-list');
                var $locationsHidden = $('#saiap-wizard-locations');

                // Only add if no locations exist yet
                if (this.locations.length === 0) {
                    for (var j = 0; j < prefillData.locations.length; j++) {
                        this.addTag(prefillData.locations[j], this.locations, $locationsList, $locationsHidden);
                    }
                }
            }
        },

        /**
         * Hide the wizard modal.
         */
        hide: function() {
            this.$modal.fadeOut(200).attr('aria-hidden', 'true');
            $('body').removeClass('saiap-wizard-open');
            // Reset edit mode flag for next use
            this.editMode = false;
        },

        /**
         * Submit the wizard form.
         */
        submit: function() {
            var self = this;

            if (this.isSubmitting) {
                return;
            }

            // Validate publishing preference (only required for new trials, not edit mode)
            var publishingPreference = $('input[name="review_before_publish"]:checked').val();
            if (!this.editMode && !publishingPreference) {
                alert(saiapWizard.strings.choosePublishing);
                $('input[name="review_before_publish"]').first().focus();
                return;
            }

            // Validate seed topics
            if (this.seedTopics.length < 3) {
                alert(saiapWizard.strings.minTopics);
                $('#saiap-wizard-seed-topics-input').focus();
                return;
            }

            // Gather form data - use different action for edit mode
            var formData = {
                action: this.editMode ? 'saiap_update_wizard_data' : 'saiap_submit_onboarding_wizard',
                nonce: this.editMode ? saiapAdmin.contextNonce : saiapWizard.nonce,
                email: saiapWizard.adminEmail || '',
                site_name: $('#saiap-wizard-site-name').val(),
                site_description: $('#saiap-wizard-site-description').val(),
                niche: $('#saiap-wizard-niche').val(),
                target_audience: $('#saiap-wizard-target-audience').val(),
                seed_topics: this.seedTopics,
                locations: this.locations,
                competitor_urls: [],
                example_posts: [],
                review_before_publish: publishingPreference || ''
            };

            // Collect competitor URLs
            $('input[name="competitor_urls[]"]').each(function() {
                var url = $.trim($(this).val());
                if (url) {
                    formData.competitor_urls.push(url);
                }
            });

            // Collect example post URLs
            $('input[name="example_posts[]"]').each(function() {
                var url = $.trim($(this).val());
                if (url) {
                    formData.example_posts.push(url);
                }
            });

            // Show loading state
            this.isSubmitting = true;
            var originalText = this.$submitBtn.text();
            this.$submitBtn.prop('disabled', true).text(saiapWizard.strings.submitting);

            var isEditMode = this.editMode;

            // Submit via AJAX
            $.ajax({
                url: saiapWizard.ajaxurl,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        if (isEditMode) {
                            // Edit mode: update local data and close modal
                            if (response.data && response.data.wizard_data) {
                                saiapAdmin.wizardData = response.data.wizard_data;
                            }
                            self.hide();
                            self.isSubmitting = false;
                            self.$submitBtn.prop('disabled', false).text(originalText);
                            // Reload context to refresh the Business Info card
                            if (typeof loadSiteContext === 'function') {
                                loadSiteContext();
                            } else {
                                // Fallback: reload the page
                                window.location.reload();
                            }
                        } else {
                            // Initial setup: redirect to dashboard
                            window.location.href = saiapWizard.redirectUrl;
                        }
                    } else {
                        var message = response.data && response.data.message
                            ? response.data.message
                            : saiapWizard.strings.error;
                        alert(message);
                        self.isSubmitting = false;
                        self.$submitBtn.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    alert(saiapWizard.strings.error);
                    self.isSubmitting = false;
                    self.$submitBtn.prop('disabled', false).text(originalText);
                }
            });
        },

        /**
         * Escape HTML entities.
         */
        escapeHtml: function(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        SaiapWizard.init();

        // Expose show method for external triggering
        window.saiapShowOnboardingWizard = function(prefillData) {
            SaiapWizard.show(prefillData);
        };

        // Auto-show wizard for post-checkout flow (license key entered but no wizard data)
        if (typeof saiapAdmin !== 'undefined' && saiapAdmin.needsWizard) {
            // Small delay to ensure page is fully rendered
            setTimeout(function() {
                SaiapWizard.show();
            }, 500);
        }
    });

})(jQuery);
