/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'ko',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/settings',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/transfer/settings',
    'WriteTextAI_WriteTextAI/js/model/edit/review-status',
    'WriteTextAI_WriteTextAI/js/model/edit/mark-reviewed',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/category',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/invalid-image',
    'WriteTextAI_WriteTextAI/js/model/edit/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/edit/additional-prompt',
    'WriteTextAI_WriteTextAI/js/model/edit/audience',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/settings',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/representative-products',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/model/edit/preferences',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/image',
    'WriteTextAI_WriteTextAI/js/utils/edit/generate',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/edit/select-template',
    'Magento_Ui/js/modal/alert',
    'WriteTextAI_WriteTextAI/js/model/grid/popups/image-upload-progressbar',
    'Magento_Ui/js/modal/confirm',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/currently-generating',
    'WriteTextAI_WriteTextAI/js/model/edit/custom-tone-style',
    'mage/translate'
], function (
    $,
    ko,
    Component,
    _,
    editData,
    settings,
    textfields,
    errorMessagesModel,
    transferSettings,
    reviewStatus,
    markReviewed,
    textfieldsUtils,
    keywordAnalysisData,
    product,
    category,
    invalidImageModel,
    invalidImagePopupModel,
    additionalPrompt,
    audience,
    generateSettings,
    representativeProducts,
    genKeywordAnalysis,
    keywordsData,
    preferences,
    categoryImageModel,
    generateUtils,
    signalRModel,
    categoriesSignalRModel,
    selectTemplateModel,
    alert,
    imageUploadProgressbarModel,
    confirm,
    currentlyGeneratingModel,
    customToneStyle,
    $t
) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    /**
     * @var {Component} self2
     */
    var self2 = {
        targetFieldId: null,
        targetFieldClass: null,
        generatedFieldId: null,
        generatedFieldIdSecondary: null,
        generatedOpenGraphEditor: null,
        generatedImageContainer: null,
        customPageTitle: null,
        customPageDescription: null,
        customProductDescription: null,
        customShortDescription: null,
        bulkGenerateImageContainer: null,
        baseUrl: null,
        activeGenerateRequest: null,  /** Track active generate request */
        activeUploadRequest: null,   /** Track active upload request */
        pendingRetryData: null       /** Store data for retry */
    };

    return Component.extend({
        defaults: {
            previewButtonSelector: '.wtai-preview-button',
            defaultStoreId: 0,
            error: '',
            templateHasImageUrl: ''
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            self = this;
            
            self.initAjaxRetryHandler();

            signalRModel.isConnected.subscribe(function (isConnected) {
                if (editData.opened() && isConnected) {
                    var recordId = editData.currentCategory().categoryId;
                    var storeId = editData.currentCategory().storeId;
                    var entityType = 'Category';
                    var identifier = entityType + '_'+ recordId + '_' + storeId;
                    var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
                    if (currentlyGeneratingRecordIdentifiers.includes(identifier)) {
                        self.getGenerated(textfields.selectedFields(), false);
                    }
                }
            }, this);

            editData.opened.subscribe(function (opened) {
                if (opened && !self.eventsInitialized) {
                    self.bindPreviewButton();
                    self.eventsInitialized = true;
                }
            });
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'error'
            ]);

            this.isNotAllStoreView = ko.computed(function () {
                return parseInt(editData.currentCategory().storeId) !== this.defaultStoreId;
            }, this);

            this.guideSteps = ko.computed(function () {
                return settings.guideSteps();
            });

            this.canSave = ko.computed(function () {
                var fields = [{
                    original: textfields.originalPageTitle(),
                    edited: textfields.pageTitle()
                }, {
                    original: textfields.originalPageDescription(),
                    edited: textfields.pageDescription()
                }, {
                    original: textfields.originalCategoryDescription(),
                    edited: textfields.categoryDescription()
                }];
                return fields.some(function (field) {
                    return field.original !== field.edited;
                });
            }, this);

            this.canTransfer = ko.computed(function () {
                var statusMapping = {
                    page_title: textfields.statuses().pageTitleGenerateStatus,
                    page_description: textfields.statuses().pageDescriptionGenerateStatus,
                    category_description: textfields.statuses().categoryDescriptionGenerateStatus
                },
                    canTransferText = textfields.selectedFields().length > 0 &&
                        textfields.selectedFields().some(function (field) {
                            return statusMapping[field];
                        }),
                    isOptimizing = keywordAnalysisData.statuses().find(function (status) {
                        return Number(status.storeId) === Number(editData.currentCategory().storeId) &&
                            status.recordId === editData.currentCategory().categoryId &&
                            status.status === 'Running';
                    }),
                    isCatOptimizing =
                        Number(keywordAnalysisData.optimizingId()) === Number(editData.currentCategory().categoryId) &&
                        Number(keywordAnalysisData.optimizingStoreId()) === Number(editData.currentCategory().storeId),
                    keywordAnalysisOngoing = (keywordAnalysisData.optimizing() ||
                    keywordAnalysisData.isUploading()) &&
                        !keywordAnalysisData.optimized() &&
                        !keywordAnalysisData.optimizationFailed() &&
                        !keywordAnalysisData.imageUploadFailed();

                if (
                    (keywordAnalysisData.refreshingData && keywordAnalysisData.refreshingData()) ||
                    isOptimizing ||
                    (keywordAnalysisOngoing && isCatOptimizing)
                ) {
                    return false;
                }

                return canTransferText;
            }, this);

            this.canGenerate = ko.computed(function () {
                var isProductOptimizing = Number(keywordAnalysisData.optimizingId()) === Number(editData.currentCategory().categoryId) &&
                        Number(keywordAnalysisData.optimizingStoreId()) === Number(editData.currentCategory().storeId),
                    keywordAnalysisOngoing = (keywordAnalysisData.optimizing() ||
                        keywordAnalysisData.isUploading()) &&
                        !keywordAnalysisData.optimized() &&
                        !keywordAnalysisData.optimizationFailed() &&
                        !keywordAnalysisData.imageUploadFailed();

                if (keywordAnalysisData.refreshingData && keywordAnalysisData.refreshingData()) {
                    return false;
                }

                if (keywordAnalysisOngoing && isProductOptimizing) {
                    return false;
                }
                
                return textfields.selectedFields() ? textfields.selectedFields().length > 0 : false;
            }, this);

            this.useAiModel = ko.computed(function () {
                return settings.useAiModel();
            }, this);

            this.selectedAiModel = ko.computed(function () {
                return settings.selectedAiModel();
            }, this);

            this.keywords = ko.computed(function () {
                var optimizingKeywords = keywordAnalysisData.optimizationData().allOptimizingKeywords || [];
                
                if (optimizingKeywords && optimizingKeywords.length > 0) {
                    return optimizingKeywords;
                } else {
                    return keywordsData.selectedKeywords();
                }
            }, this);

            return this;
        },

        /**
         * Initialize AJAX retry handler for _generate function only
         */
        initAjaxRetryHandler: function () {
            /** Listen for admin-idle.js events */
            $(document).on('wtai:user-return', function () {
                console.log('WriteText.ai: User returned, checking for interrupted generation');
                self.checkAndRetryGenerate();
            });
            
            /** Also use Page Visibility API as backup */
            document.addEventListener('visibilitychange', function () {
                if (!document.hidden) {
                    console.log('WriteText.ai: Page became visible');
                    setTimeout(function () {
                        self.checkAndRetryGenerate();
                    }, 500);
                }
            });
            
            /** Handle focus event for additional reliability on tablets */
            window.addEventListener('focus', function () {
                setTimeout(function () {
                    self.checkAndRetryGenerate();
                }, 500);
            });
        },
        
        /**
         * Check for interrupted generate and upload requests and retry
         */
        checkAndRetryGenerate: function () {
            /** Check if we have pending retry data */
            if (self2.pendingRetryData) {
                console.log('WriteText.ai: Retrying interrupted request');
                var retryData = self2.pendingRetryData;
                self2.pendingRetryData = null;
                
                if (retryData.type === 'category_upload') {
                    /** Check if upload is still needed */
                    if (imageUploadProgressbarModel && imageUploadProgressbarModel.visible()) {
                        console.log('WriteText.ai: Retrying category upload');
                        self.uploadImages(retryData.rewrite, retryData.keywordAnalysis);
                    } else {
                        console.log('WriteText.ai: Category upload no longer active, skipping retry');
                        imageUploadProgressbarModel.visible(false);
                        keywordAnalysisData.customProgressText($t('Preparing for keyword analysis...'));
                        keywordAnalysisData.isUploading(false);
                    }
                } else {
                    self._generate(false, retryData.keyword_analysis ?? false);
                }
            }
            
            /** Check if generate request is stuck */
            if (self2.activeGenerateRequest) {
                var now = Date.now();
                var duration = now - self2.activeGenerateRequest.startTime;
                
                /** If request has been running for more than 60 seconds, retry */
                if (duration > 60000) {
                    console.log('WriteText.ai: Generate request appears stuck, retrying');
                    
                    /** Abort if possible */
                    if (self2.activeGenerateRequest.jqXHR && self2.activeGenerateRequest.jqXHR.abort) {
                        self2.activeGenerateRequest.jqXHR.abort();
                    }
                    
                    /** Store for retry */
                    self2.pendingRetryData = {
                        type: 'generate',
                        url: self2.activeGenerateRequest.url,
                        data: self2.activeGenerateRequest.data
                    };
                    
                    self2.activeGenerateRequest = null;
                    
                    /** Retry */
                    self.checkAndRetryGenerate();
                }
            }
            
            /** Check if upload request is stuck */
            if (self2.activeUploadRequest) {
                var now = Date.now();
                var duration = now - self2.activeUploadRequest.startTime;
                
                /** If request has been running for more than 60 seconds, retry */
                if (duration > 60000) {
                    console.log('WriteText.ai: Category upload request appears stuck, retrying');
                    
                    /** Abort if possible */
                    if (self2.activeUploadRequest.jqXHR && self2.activeUploadRequest.jqXHR.abort) {
                        self2.activeUploadRequest.jqXHR.abort();
                    }
                    
                    /** Store for retry */
                    self2.pendingRetryData = {
                        type: 'category_upload',
                        rewrite: self2.activeUploadRequest.rewrite,
                        keywordAnalysis: self2.activeUploadRequest.keywordAnalysis
                    };
                    
                    self2.activeUploadRequest = null;
                    
                    /** Retry */
                    self.checkAndRetryGenerate();
                }
            }
        },

        /**
         * Generate validations.
         *
         * @param {boolean} rewrite
         * @param {boolean} keywordAnalysis
         *
         * @returns {void}
         */
        generate: function (rewrite = false, keywordAnalysis = false) {
            if ((textfields.selectedFields().includes('page_title') &&
                textfields.originalPageTitle() !== textfields.pageTitle()
            ) || (textfields.selectedFields().includes('page_description') &&
                textfields.originalPageDescription() !== textfields.pageDescription()
            ) || (textfields.selectedFields().includes('category_description') &&
                textfields.originalCategoryDescription() !== textfields.categoryDescription())
            ) {
                confirm({
                    content: $t('You have unsaved changes. Are you sure you want to regenerate and replace text?'),
                    buttons: [{
                        text: $t('Cancel'),
                        class: 'action-secondary action-dismiss',
                        click: function (event) {
                            keywordsData.showProgress(false);
                            keywordAnalysisData.isUploading(false);
                            keywordAnalysisData.optimizing(false);
                            this.closeModal(event);
                        }
                    }, {
                        text: $t('Ok'),
                        class: 'action-primary action-accept',
                        click: function (event) {
                            this.closeModal(event, true);
                            self.generateAction(rewrite, keywordAnalysis);
                        }
                    }]
                });
            } else {
                self.generateAction(rewrite, keywordAnalysis);
            }
        },

        /**
         * Generate action.
         *
         * @param {boolean} rewrite
         * @param {boolean} keywordAnalysis
         *
         * @returns {void}
         */
        generateAction: function (rewrite = false, keywordAnalysis = false) {
            /** Check for AI model availability first */
            /* if (this.hasAiModels && this.selectedAiModel() === '') {
                confirm({
                    content: $t('An AI model is available. Do you want to proceed without using it?'),
                    buttons: [{
                        text: $t('Cancel'),
                        class: 'action-secondary action-dismiss',
                        click: function (event) {
                            keywordsData.showProgress(false);
                            keywordAnalysisData.isUploading(false);
                            keywordAnalysisData.optimizing(false);
                            this.closeModal(event);
                        }
                    }, {
                        text: $t('Proceed'),
                        class: 'action-primary action-accept',
                        click: function (event) {
                            this.closeModal(event, true);
                            self.continueGeneration(rewrite, keywordAnalysis);
                        }
                    }]
                });
                return;
            } */
            this.continueGeneration(rewrite, keywordAnalysis);
        },

        /**
         * Continue generation after AI model confirmation
         *
         * @param {boolean} rewrite
         * @param {boolean} keywordAnalysis
         */
        continueGeneration: function (rewrite = false, keywordAnalysis = false) {
            if (!this.isCheckboxesValid()) {
                keywordsData.showProgress(false);
                keywordAnalysisData.isUploading(false);
                keywordAnalysisData.optimizing(false);
                alert({
                    content: this.error()
                });
                return;
            }

            let categoryImageValid = (categoryImageModel.categoryImageSelected()
                    || textfields.selectedFields().includes('category_description')) && category.image(),
                representativeProductsSelected = representativeProducts.selected().length > 0,
                representativeProductsHaveImages = representativeProducts.selected().some(product => product.image_id),
                representativeProductsValid = representativeProductsSelected && representativeProductsHaveImages;
            
            invalidImageModel.invalidImages([]);
            invalidImageModel.invalid([]);
            invalidImageModel.notSupported([]);
            invalidImageModel.downloadFailed([]);
            invalidImageModel.general([]);
            invalidImageModel.errorMessages([]);

            if (categoryImageValid || representativeProductsValid || keywordAnalysis) {
                if (keywordAnalysis) {
                    this.uploadImages(rewrite, keywordAnalysis);
                    return;
                }

                this.shouldUploadImages(function (shouldUpload) {
                    if (shouldUpload && (categoryImageValid || representativeProductsValid)) {
                        self.uploadImages(rewrite, keywordAnalysis);
                    } else {
                        self._generate(rewrite, keywordAnalysis);
                    }
                });
            } else {
                this._generate(rewrite, keywordAnalysis);
            }
        },

        /**
         * Determine if the selected templates require images.
         * If we cannot determine it, we default to uploading (safe behavior).
         *
         * @param {Function} callback
         */
        shouldUploadImages: function (callback) {
            var templateIds = [];
            try {
                var templates = selectTemplateModel.selectedTemplates;
                var selectedFields = (textfields.selectedFields && typeof textfields.selectedFields === 'function')
                    ? (textfields.selectedFields() || [])
                    : [];

                var allowedTemplateKeys = [];
                if (selectedFields.indexOf('page_title') !== -1) {
                    allowedTemplateKeys.push('category_page_title');
                    allowedTemplateKeys.push('page_title');
                }
                if (selectedFields.indexOf('page_description') !== -1) {
                    allowedTemplateKeys.push('category_page_description');
                    allowedTemplateKeys.push('page_description');
                }
                if (selectedFields.indexOf('category_description') !== -1) {
                    allowedTemplateKeys.push('category_description');
                }

                if (templates) {
                    Object.keys(templates).forEach(function (key) {
                        if (allowedTemplateKeys.length && allowedTemplateKeys.indexOf(key) === -1) {
                            return;
                        }
                        var observableOrValue = templates[key];
                        var value = typeof observableOrValue === 'function' ? observableOrValue() : observableOrValue;
                        if (value) {
                            templateIds.push(String(value));
                        }
                    });
                }
            } catch (e) {
                callback(true);
                return;
            }


            if (!this.templateHasImageUrl || templateIds.length === 0) {
                callback(true);
                return;
            }

            $.ajax({
                url: this.templateHasImageUrl,
                type: 'POST',
                data: { template_ids: templateIds, form_key: window.FORM_KEY },
                dataType: 'json',
                showLoader: false
            }).done(function (response) {
                if (!response || !response.success || !response.data) {
                    callback(true);
                    return;
                }

                var requiresImages = templateIds.some(function (id) {
                    return !!response.data[id];
                });
                callback(requiresImages);
            }).fail(function () {
                callback(true);
            });
        },

        /**
         * Upload images.
         *
         * @param {boolean} rewrite
         * @param {boolean} keywordAnalysis
         * @param {number} attempt
         *
         * @returns {void}
         */
        uploadImages: function (rewrite = false, keywordAnalysis = false, attempt = 1) {
            let data = {
                category_id: editData.currentCategory().categoryId,
                store_id: editData.currentCategory().storeId,
                products: representativeProducts.selected()
            };
            
            keywordAnalysisData.imageUploadFailed(false);

            if (category.image() && (categoryImageModel.categoryImageSelected() ||
                textfields.selectedFields().includes('category_description'))) {
                data.category_image = category.image();
            }

            if (!keywordAnalysis) {
                imageUploadProgressbarModel.visible(true);
                imageUploadProgressbarModel.toCancel(false);
                imageUploadProgressbarModel.progress(0);

                let total = data.products.filter(function (product) {
                    return product.image_id;
                }).length;
                if (data.category_image) {
                    total += 1;
                }

                imageUploadProgressbarModel.total(total);
            }

            /** Track active upload request for retry mechanism */
            self2.activeUploadRequest = {
                url: this.uploadUrl,
                data: data,
                rewrite: rewrite,
                keywordAnalysis: keywordAnalysis,
                startTime: Date.now()
            };

            var uploadErrorMessages = invalidImageModel.errorMessages();
            var ajaxRequest = $.ajax({
                url: this.uploadUrl,
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function (response) {
                    /* Clear active upload request */
                    self2.activeUploadRequest = null;
                    
                    if (response.success) {
                        invalidImageModel.categoryImage(response.category_image);
                        if (!response.category_image) {
                            invalidImageModel.invalidImages.push(data.category_image);
                        }
                        if (response.products.failed.length > 0) {
                            response.products.failed.forEach(product => {
                                invalidImageModel.invalidImages.push(product.image);
                            });
                        }
                        if (!response.category_image || response.products.failed.length > 0) {
                            invalidImageModel.errorMessages({...uploadErrorMessages, ...response.error_messages});
                            invalidImageModel.invalid.push(...response.invalid);
                            invalidImageModel.notSupported.push(...response.not_supported);
                            invalidImageModel.downloadFailed.push(...response.download_failed);
                            invalidImageModel.general.push(...response.general);
                            
                            invalidImageModel.products(response.products);
                            if (data.category_image) {
                                invalidImageModel.categoryImage(response.category_image);
                            }
                            invalidImageModel.keywordAnalysis(keywordAnalysis);
                            invalidImageModel.isRewrite(rewrite);
                            if (keywordAnalysis) {
                                keywordAnalysisData.imageUploadFailed(true);
                            }
                            keywordsData.showProgress(false);

                            if (!!invalidImagePopupModel.doNotShowAgain() || !!window.wtaiInvalidImagePopupDoNotShowAgain) {
                                if (keywordAnalysis) {
                                    keywordAnalysisData.imageUploadFailed(false);
                                }
                                self._generate(rewrite, keywordAnalysis);
                            } else {
                                $('.wtai-categories-invalid-image-popup').modal('openModal');
                            }
                        } else {
                            self._generate(rewrite, keywordAnalysis);
                        }
                    }
                    imageUploadProgressbarModel.visible(false);
                    keywordAnalysisData.customProgressText($t('Queued for keyword analysis'));
                    keywordAnalysisData.isUploading(false);
                },
                error: function (xhr, status, error) {
                    /* Clear active upload request */
                    self2.activeUploadRequest = null;
                    
                    /* Check if this was due to page being backgrounded */
                    if (status === 'abort' || (xhr && xhr.readyState === 0)) {
                        console.log('WriteText.ai: Category upload request interrupted, will retry on page focus');
                        /* Store for retry */
                        self2.pendingRetryData = {
                            type: 'category_upload',
                            data: data,
                            rewrite: rewrite,
                            keywordAnalysis: keywordAnalysis
                        };
                    } else {
                        var isNetworkIssue = status === 'timeout' || (xhr && xhr.readyState === 0);
                        var isTransientServerIssue = xhr && [502, 503, 504].includes(Number(xhr.status));
                        var isRetryableIssue = isNetworkIssue || isTransientServerIssue;

                        if (isRetryableIssue && attempt < 3) {
                            window.setTimeout(function () {
                                self.uploadImages(rewrite, keywordAnalysis, attempt + 1);
                            }, 5000);
                            return;
                        }

                        if (isRetryableIssue) {
                            var message = '';
                            try {
                                if (xhr && xhr.responseJSON && xhr.responseJSON.message) {
                                    message = xhr.responseJSON.message;
                                } else if (xhr && xhr.responseText) {
                                    message = xhr.responseText;
                                }
                            } catch (e) {
                                message = '';
                            }

                            $('body').notification('clear');
                            message = $t('Please check your internet connection and try again after reloading the page. If the issue persists, please contact our support team at support@writetext.ai.');

                            keywordAnalysisData.imageUploadFailed(true);
                            try {
                                errorMessagesModel.messages([message]);
                            } catch (e) {
                                // no-op
                            }
                            imageUploadProgressbarModel.visible(false);
                            return;
                        }

                        /* Normal error handling */
                        keywordAnalysisData.imageUploadFailed(true);
                        errorMessagesModel.messages.push($t('Image upload failed. Please try again.'));
                    }
                }
            });
            
            /* Store the jqXHR object for potential abort */
            if (self2.activeUploadRequest) {
                self2.activeUploadRequest.jqXHR = ajaxRequest;
            }
        },

        /**
         * Generate request.
         *
         * @param {boolean} rewrite
         * @param {boolean} keywordAnalysis
         *
         * @returns {void}
         */
        _generate: function (rewrite = false, keywordAnalysis = false) {
            /**clear error */
            $('body').notification('clear');

            /* remove error messages */
            errorMessagesModel.messages([]);

            if (keywordAnalysis) {
                keywordsData.showProgress(true);
            }

            /* empty text fields */
            generateUtils.clearCategoryFields(textfields.selectedFields(), rewrite);

            let failedImageIds = [];
            let failedProducts = invalidImageModel.products() ? (invalidImageModel.products().failed ?? []) : [];
            let failedImageUrlById = {};
            failedProducts.forEach(product => {
                failedImageIds.push(product.image_id);
                if (product.image_id && product.image) {
                    failedImageUrlById[product.image_id] = product.image;
                }
            });
            
            let products = [];
            representativeProducts.selected().forEach(product => {
                let representativeProduct = {...product};
                if (failedImageIds.includes(representativeProduct.image_id)) {
                    if (failedImageUrlById[representativeProduct.image_id]) {
                        representativeProduct.image_url = failedImageUrlById[representativeProduct.image_id];
                    }
                    representativeProduct.image_id = '';
                }
                products.push(representativeProduct);
            });
            var data = {
                category_id: editData.currentCategory().categoryId,
                store_id: editData.currentCategory().storeId,
                products: products,
                category_image: invalidImageModel.categoryImage() ? category.image() : '',
                category_image_selected: categoryImageModel.categoryImageSelected(),
                featured_image_url: (categoryImageModel.categoryImageSelected() || textfields.selectedFields().includes('category_description'))
                    ? (category.image() || '')
                    : '',
                name: category.categoryName(),
                tones: preferences.tonesSelected(),
                style: preferences.stylesSelected(),
                audience: preferences.audienceSelected(),
                custom_tone: customToneStyle.customTone(),
                custom_style: customToneStyle.customStyle(),
                additional_prompt: additionalPrompt.promptValue(),
                custom_audience: audience.selectedAudience(),
                selected_fields: textfields.selectedFields(),
                current_values: {
                    page_title: textfields.mgPageTitle(),
                    page_description: textfields.mgPageDescription(),
                    category_description: textfields.mgCategoryDescription()
                },
                min_words: generateSettings.descMin(),
                max_words: generateSettings.descMax(),
                other_details_checked: representativeProducts.otherDetailsChecked(),
                other_details: representativeProducts.otherDetails(),
                rewrite: rewrite,
                keyword_analysis_views: genKeywordAnalysis.views(),
                keywords: self.keywords(),
                search_intent_selected: keywordsData.searchIntentSelected(),
                keyword_analysis: keywordAnalysis,
                product_research_data: representativeProducts.productResearchData(),
                templates_used: selectTemplateModel.selectedTemplates,
                url: product.productUrl(),
                use_ai_model: self.useAiModel(),
                selected_ai_model: self.selectedAiModel()
            };

            data.failed_images = invalidImageModel.invalidImages();
            
            /** Track active generate request for retry mechanism */
            self2.activeGenerateRequest = {
                url: self.generateUrl,
                data: data,
                startTime: Date.now()
            };

            if (!keywordAnalysis) {
                categoriesSignalRModel.editTitleStatusText($t('Preparing for text generation...'));
            }
            

            var ajaxRequest = $.ajax({
                url: self.generateUrl,
                type: 'POST',
                data: data,
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: textfields.selectedFields().includes('page_title'),
                showPageDescriptionLoader: textfields.selectedFields().includes('page_description'),
                showCategoryDescriptionLoader: textfields.selectedFields().includes('category_description'),
                success: function (response) {
                    /* Clear active request */
                    self2.activeGenerateRequest = null;
                    
                    if (response.success) {
                        markReviewed.reviewed(response.reviewed);
                        genKeywordAnalysis.views(0);
                    } else {
                        keywordAnalysisData.optimizationFailed(true);
                        keywordAnalysisData.optimizing(false);
                        keywordsData.showProgress(false);
                        self.getGenerated(textfields.selectedFields(), rewrite);
                        if (response.message) {
                            errorMessagesModel.messages.push(response.message);
                        }
                        signalRModel.generating(false);
                        
                        generateUtils.removeIdentifierFromCurrentlyGeneratingRecordIdentifiers('Category');
                        if (response.unauthorized) {
                            window.location.href = response.login_url;
                        }
                    }
                },
                error: function (xhr, status, error) {

                    /** Clear active request */
                    self2.activeGenerateRequest = null;
                    
                    /** Check if this was due to page being backgrounded */
                    if (status === 'abort' || (xhr && xhr.readyState === 0)) {
                        console.log('WriteText.ai: Generate request interrupted, will retry on page focus');
                        /** Store for retry */
                        self2.pendingRetryData = {
                            url: self.generateUrl,
                            data: data
                        };
                    } else {
                        /** Normal error handling */
                        errorMessagesModel.messages.push($t('An error occurred while generating content. Please try again.'));
                        signalRModel.generating(false);
                        generateUtils.removeIdentifierFromCurrentlyGeneratingRecordIdentifiers('Category');
                    }
                }
            });
            
            /* Store the jqXHR object for potential abort */
            if (self2.activeGenerateRequest) {
                self2.activeGenerateRequest.jqXHR = ajaxRequest;
            }
        },

        /**
         * Get generated texts.
         *
         * @param {array} selectedFields
         * @param {boolean} rewrite
         *
         * @returns {void}
         */
        getGenerated: function (selectedFields, rewrite) {
            errorMessagesModel.messages([]);

            $.ajax({
                url: self.getGeneratedUrl,
                type: 'POST',
                data: {
                    category_id: editData.currentCategory().categoryId,
                    store_id: editData.currentCategory().storeId,
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: selectedFields.includes('page_title'),
                showPageDescriptionLoader: selectedFields.includes('page_description'),
                showCategoryDescriptionLoader: selectedFields.includes('category_description'),
                success: function (response) {
                    if (response.success) {
                        if (selectedFields.includes('page_title')) {
                            if (!rewrite || (rewrite && textfields.mgPageTitle() !== '')) {
                                textfields.pageTitle(response.generated_texts.page_title);
                                textfields.originalPageTitle(response.generated_texts.page_title);
                            }
                        }
                        if (selectedFields.includes('page_description')) {
                            if (!rewrite || (rewrite && textfields.mgPageDescription() !== '')) {
                                textfields.pageDescription(response.generated_texts.page_description);
                                textfields.originalPageDescription(response.generated_texts.page_description);
                            }
                        }
                        if (selectedFields.includes('category_description')) {
                            if (!rewrite || (rewrite && textfields.mgCategoryDescription() !== '')) {
                                textfields.categoryDescription(response.generated_texts.category_description);
                                textfields.originalCategoryDescription(response.generated_texts.category_description);
                            }
                        }
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                }
            });
        },

        /**
         * Check if checkboxes are valid.
         */
        isCheckboxesValid: function () {
            var tonesSelectedCount = preferences.tonesSelected() ? preferences.tonesSelected().length : 0;

            var selectedAiModel = this.selectedAiModel();

            if (this.useAiModel() && (!selectedAiModel || String(selectedAiModel).trim() === '')) {
                this.error($t('Please select a brand voice.'));
                return false;
            }

            if (this.useAiModel()) {
                return true;
            }
            if (tonesSelectedCount === 0) {
                this.error($t('Please select at least one tone.'));
                return false;
            } else if (
                tonesSelectedCount === 1 &&
                preferences.tonesSelected()[0] === 'custom' &&
                 String(preferences.customTone() || '').trim() === ''
            ) {
                this.error($t('Write your specific tone...'));
                return false;
            }

            var selectedStyle = String(preferences.stylesSelected() || '').trim();

            if (!selectedStyle) {
                this.error($t('Please select a style.'));
                return false;
            } else if (
                selectedStyle === 'custom' &&
                String(preferences.customStyle() || '').trim() === ''
            ) {
                this.error($t('Write your specific style...'));
                return false;
            }

            return true;
        },

        /**
         * Bind preview button.
         */
        bindPreviewButton: function () {
            $(this.previewButtonSelector).on('click', function () {
                var previewUrl = $(this).data('link');

                window.open(previewUrl, '_blank');
            });
        },

        /**
         * Save text to api.
         */
        save: function () {
            var url = self.saveUrl,
                changedFields = {},
                statuses = textfields.statuses();

            if (textfields.pageTitle() !== textfields.originalPageTitle() &&
                textfields.pageTitle() !== ''
            ) {
                changedFields.page_title = textfields.pageTitle();
                statuses.pageTitleTransferStatus = false;
            }
            if (textfields.pageDescription() !== textfields.originalPageDescription() &&
                textfields.pageDescription() !== ''
            ) {
                changedFields.page_description = textfields.pageDescription();
                statuses.pageDescriptionTransferStatus = false
            }
            if (textfields.categoryDescription() !== textfields.originalCategoryDescription() &&
                textfields.categoryDescription() !== ''
            ) {
                changedFields.category_description = textfields.categoryDescription();
                statuses.categoryDescriptionTransferStatus = false
            }

            errorMessagesModel.messages([]);

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    category_id: editData.currentCategory().categoryId,
                    store_id: editData.currentCategory().storeId,
                    selected_fields: changedFields
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: true,
                showPageDescriptionLoader: true,
                showCategoryDescriptionLoader: true,
                success: function (response) {
                    if (response.success) {
                        markReviewed.reviewed(false);
                        textfields.originalPageTitle(textfields.pageTitle());
                        textfields.originalPageDescription(textfields.pageDescription());
                        textfields.originalCategoryDescription(textfields.categoryDescription());
                        textfields.statuses(statuses);
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                }
            });
        },

        /**
         * Transfer text to Magento.
         */
        transfer: function () {
            confirm({
                title: $.mage.__('Transfer selected to Magento'),
                content: self.confirmContent,
                modalClass: 'wtai-modal wtai-bulk-transfer-popup wtai-transfer wtai-edit',
                actions: {
                    confirm: function () {
                        self._transfer();
                    }
                },
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function (event) {
                        this.closeModal(event);
                    }
                }, {
                    text: $t('OK'),
                    class: 'action-primary action-accept',
                    click: function (event) {
                        if (
                            $('#wtaiEditTransferForm').data('validator') &&
                            $('#wtaiEditTransferForm').validation() &&
                            $('#wtaiEditTransferForm').validation('isValid')
                        ) {
                            this.closeModal(event, true);
                        }
                    }
                }]
            });
        },

        /**
         * Transfer text to Magento.
         */
        _transfer: function () {
            var url = self.transferUrl,
                selectedFields = {},
                mapping = {
                    page_title: textfields.pageTitle(),
                    page_description: textfields.pageDescription(),
                    category_description: textfields.categoryDescription()
            };

            errorMessagesModel.messages([]);

            textfields.selectedFields().forEach(function (field) {
                selectedFields[field] = mapping[field];
            });

            categoriesSignalRModel.editTitleStatusText($t('Transferring...'));

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    category_id: editData.currentCategory().categoryId,
                    store_id: editData.currentCategory().storeId,
                    selected_fields: selectedFields,
                    selected_stores: transferSettings.selectedStores()
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: textfields.selectedFields().includes('page_title'),
                showPageDescriptionLoader: textfields.selectedFields().includes('page_description'),
                showCategoryDescriptionLoader: textfields.selectedFields().includes('category_description'),
                success: function (response) {
                    if (response.success) {
                        var fields = response.fields;
                        if (response.use_default) {
                            textfields.useDefault({
                                pageTitle: textfields.selectedFields().includes('page_title') ?
                                    response.use_default.page_title : textfields.useDefault().pageTitle,
                                pageDescription: textfields.selectedFields().includes('page_description') ?
                                    response.use_default.page_description : textfields.useDefault().pageDescription,
                                categoryDescription: textfields.selectedFields().includes('category_description') ?
                                    response.use_default.category_description : textfields.useDefault().categoryDescription
                            });
                        }
                        markReviewed.reviewed(response.reviewed);
                        if (transferSettings.selectedStores().map(String).includes(String(editData.currentCategory().storeId))) {
                            textfieldsUtils.updateCategoryCurrentFields(fields, textfields.selectedFields(), {
                                'page_title': textfields.pageTitle(),
                                'page_description': textfields.pageDescription(),
                                'category_description': textfields.categoryDescription()
                            });
                        }
                        reviewStatus.reviewStatus(response.updatedReview);
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                    categoriesSignalRModel.editTitleStatusText('');
                },
                error: function () {
                    categoriesSignalRModel.editTitleStatusText('');
                }
            });
        }
    });
});
