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

define([
    'jquery',
    'ko',
    'uiComponent',
    'WriteTextAI_WriteTextAI/js/model/grid/prompt',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'jquery-ui-modules/spinner',
    'mage/translate'
], function (
    $,
    ko,
    Component,
    prompt,
    textfieldsUtils,
    spinner,
    $t
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            tooltipSelector: '.wtai-bulk-generate-form .admin__field-tooltip-action',
            clusterCount: 4,
            isLoading: true,
            searchIntent: [],
            searchIntents: [
                'transactional',
                'commercial',
                'navigational',
                'informational'
            ],
            autoTextOptimizationSelected: 'flag',
            triggerActionNPositionLow: 1,
            triggerActionNPositionLowMid: 1,
            triggerActionNPositionMid: 1,
            triggerActionNPositionMidHigh: 1,
            triggerActionNDaysLow: 1,
            triggerActionNDaysLowMid: 1,
            triggerActionNDaysMid: 1,
            triggerActionNDaysMidHigh: 1,
            subTitleLow: 'Ranking 1 - 10',
            subTitleLowMid: 'Ranking 1 - 10',
            subTitleMid: 'Ranking 1 - 10',
            subTitleMidHigh: 'Ranking 1 - 10',
            allProductFieldsSelected: false,
            productFields: [],
            allProductFields: [],
            triggerActionChanged: {
                low: ko.observable(false),
                low_mid: ko.observable(false),
                mid: ko.observable(false),
                mid_high: ko.observable(false)
            },
            isAcknowledgedHeadsUp: false,
            messageHeadsUp: '',
            positionHeadsUp: 'top',
            targetElementHeadsUp: null,
            isVisibleHeadsUp: false,
            buttonTextHeadsUp: $t('Yes, I understand'),
            headsupVisibility: {
                'transactional': ko.observable(false),
                'commercial': ko.observable(false),
                'navigational': ko.observable(false),
                'informational': ko.observable(false)
            },
            rules: {},
            maxClusterCount: 0,
            minClusterCount: 0,
            isCronAvailable: false,
            triggerActions: {},
            minTriggerActionNPosition: 0,
            maxTriggerActionNPosition: 0,
            minTriggerActionNDays: 0,
            maxTriggerActionNDays: 0,
            automaticTextOptimizationOptions: [],
            isRestoreGlobalLoading: false,
            isSaveGlobalLoading: false,
        },
        
        isSpinning: false,
        isReopening: false,
        isRestoring: false,
        isSingleSelectedWarningVisible: false,

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

            const el = document.querySelector('.wtai-bulk-keyword-analysis-form-container');
            if (el) {
                $('.wtai-bulk-keyword-analysis-form-container > *').applyBindings(this);
            }

            self = this;

            self.autoTextOptimizationSelected.subscribe(function (autoTextOptimizationSelected) {
                self.savePreferences('automatic_text_optimization', autoTextOptimizationSelected);
            });

            self.searchIntent.subscribe(function (searchIntent) {
                if (!self.isReopening) {
                    self.savePreferences('search_intent', searchIntent.join(','));
                }
            });

            self.clusterCount.subscribe(function (clusterCount) {
                if (!self.isSpinning) {
                    self.savePreferences('cluster_count_category', clusterCount);
                }
            });

            self.getSettings();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'isLoading',
                    'searchIntent',
                    'searchIntents',
                    'clusterCount',
                    'autoTextOptimizationSelected',
                    'triggerActionNPositionLow',
                    'triggerActionNPositionLowMid',
                    'triggerActionNPositionMid',
                    'triggerActionNPositionMidHigh',
                    'triggerActionNDaysLow',
                    'triggerActionNDaysLowMid',
                    'triggerActionNDaysMid',
                    'triggerActionNDaysMidHigh',
                    'subTitleLow',
                    'subTitleLowMid',
                    'subTitleMid',
                    'subTitleMidHigh',
                    'allProductFieldsSelected',
                    'productFields',
                    'isAcknowledgedHeadsUp',
                    'messageHeadsUp',
                    'positionHeadsUp',
                    'targetElementHeadsUp',
                    'isVisibleHeadsUp',
                    'rules',
                    'maxClusterCount',
                    'minClusterCount',
                    'isCronAvailable',
                    'triggerActions',
                    'minTriggerActionNPosition',
                    'maxTriggerActionNPosition',
                    'minTriggerActionNDays',
                    'maxTriggerActionNDays',
                    'allProductFields',
                    'automaticTextOptimizationOptions',
                    'isRestoreGlobalLoading',
                    'isSaveGlobalLoading',
                    'isSingleSelectedWarningVisible'
                ]);

            this.searchIntentCommadSeparated = ko.computed(function () {
                return this.searchIntent().join(', ');
            }, this);

            this.allProductFieldsSelected = ko.computed({
                read: function () {
                    const productFields = this.productFields() || [];
                    const allProductFields = [...this.allProductFields()] || [];
                    return productFields.length === allProductFields.length;
                }.bind(this),
                write: function (value) {
                    const allProductFields = [...this.allProductFields()] || [];
                    const fields = value ? allProductFields : [];
                    this.productFields(fields);
                }.bind(this)
            }, this);

            this.isOffsetRight = ko.computed(function () {
                if (this.headsupVisibility.informational() &&
                    this.searchIntent().length >= 2
                ) {
                    return true;
                }

                return false;
            }, this);

            return this;
        },

        /**
         * Initialize bulk tabs
         */
        initBulkTabs: function () {
            setTimeout(function () {
                $('.wtai-tabs').tabs({
                    active: 0
                });
            }, 100);
        },
        
        /**
         * Show loader
         */
        showLoader: function () {
            self.isLoading(true);
        },

        /**
         * Remove loader
         */
        removeLoader: function () {
            setTimeout(function () {
                self.isLoading(false);
            }, 100);
        },

        /**
         * Get settings
         */
        getSettings: function () {
            self.showLoader();
            $.ajax({
                url: self.getSettingsUrl,
                type: 'GET',
                data: {
                    getTemplateSettings: false
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    } else {
                        console.log(response);

                        self.isReopening = true;
                        self.rules(response.data.rules);
                        self.autoTextOptimizationSelected(response.data.autoTextOptimizationSelected);
                        self.searchIntent(response.data.searchIntent);
                        self.clusterCount(response.data.clusterCount);
                        self.maxClusterCount(response.data.maxClusterCount);
                        self.minClusterCount(response.data.minClusterCount);
                        self.isCronAvailable(response.data.isCronAvailable);
                        self.triggerActions(response.data.triggerActions);
                        self.triggerActionNPositionLow(response.data.triggerActionNPositionLow);
                        self.triggerActionNDaysLow(response.data.triggerActionNDaysLow);
                        self.triggerActionNPositionLowMid(response.data.triggerActionNPositionLowMid);
                        self.triggerActionNDaysLowMid(response.data.triggerActionNDaysLowMid);
                        self.triggerActionNPositionMid(response.data.triggerActionNPositionMid);
                        self.triggerActionNDaysMid(response.data.triggerActionNDaysMid);
                        self.triggerActionNPositionMidHigh(response.data.triggerActionNPositionMidHigh);
                        self.triggerActionNDaysMidHigh(response.data.triggerActionNDaysMidHigh);
                        self.minTriggerActionNPosition(response.data.minTriggerActionNPosition);
                        self.maxTriggerActionNPosition(response.data.maxTriggerActionNPosition);
                        self.minTriggerActionNDays(response.data.minTriggerActionNDays);
                        self.maxTriggerActionNDays(response.data.maxTriggerActionNDays);
                        self.productFields(response.data.categoryFields || response.data.productFields);
                        self.allProductFields(response.data.allCategoryFields || response.data.allProductFields);
                        self.automaticTextOptimizationOptions(response.data.automaticTextOptimizationOptions);
                        self.isReopening = false;

                        self.initBulkTabs();
                        self.initTooltip();
                        self.initSpinner();
                        self.initPreferences();
                        self.initTriggerActionsLabels();
                        self.bindHeadsUpClickOutside();
                        self.bindSingleItemTooltipClickOutside();
                    }
                }
            }).always(function () {
                self.removeLoader();
            });
        },

        /**
         * Initialize preferences
         *
         * Set model values on page load.
         * Model values updates on change.
         * Retain selected fields when reopening the modal.
         */
        initPreferences: function () {
            if (!prompt.keywordAnalysisPromptInitialized()) {
                prompt.keywordAnalysisPromptInitialized(true);
            } else {
                this.isReopening = true;

                /* Reset the tooltip acknowledgement status when reopening the modal */
                this.isAcknowledgedHeadsUp(false);
                this.headsupVisibility.transactional(false);
                this.headsupVisibility.commercial(false);
                this.headsupVisibility.navigational(false);
                this.headsupVisibility.informational(false);
                
                this.isReopening = false;
            }
        },

        /**
         * Show restore global loader
         */
        showRestoreGlobalLoader: function () {
            self.isRestoreGlobalLoading(true);
        },

        
        /**
         * Show save global loader
         */
        showSaveGlobalLoader: function () {
            self.isSaveGlobalLoading(true);
        },

        /**
         * Remove restore global loader
         */
        removeRestoreGlobalLoader: function () {
            setTimeout(function () {
                self.isRestoreGlobalLoading(false);
            }, 100);
        },

        /**
         * Remove save global loader
         */
        removeSaveGlobalLoader: function () {
            setTimeout(function () {
                self.isSaveGlobalLoading(false);
            }, 100);
        },

        /**
         * Get trigger action name
         */
        getTriggerActionName: function (triggerAction) {
            switch (triggerAction) {
                case 'low':
                    return 'LOW - LOW MID';
                case 'low_mid':
                    return 'LOW MID - MID';
                case 'mid':
                    return 'MID - MID HIGH';
                case 'mid_high':
                    return 'MID HIGH - HIGH';
            }
        },

        getTriggerActionLabel: function (triggerAction) {
            return this.getTriggerActionName(triggerAction);
        },

        /**
         * Format trigger action name
         */
        formatTriggerActionName: function (triggerAction) {
            switch (triggerAction) {
                case 'low':
                    return self.subTitleLow();
                case 'low_mid':
                    return self.subTitleLowMid();
                case 'mid':
                    return self.subTitleMid();
                case 'mid_high':
                    return self.subTitleMidHigh();
            }
        },

        /**
         * Save user preferences
         *
         * @param {String} field
         * @param {String} selected
         *
         * @return {void}
         */
        savePreferences: function (field, selected) {
            var value = selected;
            
            if (value === null || value.length <= 0) {
                value = '';
            }

            if (self.isRestoring || self.isReopening) {
                return;
            }

            $.ajax({
                url: self.saveUrl,
                type: 'POST',
                data: {
                    [field]: value,
                    entity_type: 'category',
                    scope: 'grid'
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Save current prompt values as global settings
         */
        save: function () {
            self.showSaveGlobalLoader();

            var category_fields = self.productFields();
            if (category_fields.length <= 0) {
                category_fields = '';
            }

            $.ajax({
                url: self.saveConfigUrl,
                type: 'POST',
                data: {
                    trigger_action_low: $('input[name="trigger_action_low"]:checked').val(),
                    trigger_action_low_mid: $('input[name="trigger_action_low_mid"]:checked').val(),
                    trigger_action_mid: $('input[name="trigger_action_mid"]:checked').val(),
                    trigger_action_mid_high: $('input[name="trigger_action_mid_high"]:checked').val(),
                    trigger_action_n_position_low: self.triggerActionNPositionLow(),
                    trigger_action_n_position_low_mid: self.triggerActionNPositionLowMid(),
                    trigger_action_n_position_mid: self.triggerActionNPositionMid(),
                    trigger_action_n_position_mid_high: self.triggerActionNPositionMidHigh(),
                    trigger_action_n_days_low: self.triggerActionNDaysLow(),
                    trigger_action_n_days_low_mid: self.triggerActionNDaysLowMid(),
                    trigger_action_n_days_mid: self.triggerActionNDaysMid(),
                    trigger_action_n_days_mid_high: self.triggerActionNDaysMidHigh(),
                    auto_text_optimization: self.autoTextOptimizationSelected(),
                    cluster_based_pipelines_count_category: self.clusterCount(),
                    category_fields: category_fields,
                    ko_optimization_only: true,
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            }).always(function () {
                self.removeSaveGlobalLoader();
            });
        },
        /**
         * Restore user preferences
         */
        restore: function () {
            this.showRestoreGlobalLoader();

            $.ajax({
                url: this.restoreUrl,
                type: 'GET',
                data: {
                    from_ko: true,
                    entity_type: 'category'
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    } else {
                        console.log(response);
                        self.isRestoring = true;
                        self.autoTextOptimizationSelected(response.data.automatic_text_optimization);
                        self.searchIntent([...response.data.search_intent]);
                        self.clusterCount(response.data.cluster_count_category || response.data.cluster_count);
                        self.triggerActions(response.data.triggerActions);
                        self.triggerActionNPositionLow(self.triggerActions().low.trigger_action_n_position);
                        self.triggerActionNPositionLowMid(self.triggerActions().low_mid.trigger_action_n_position);
                        self.triggerActionNPositionMid(self.triggerActions().mid.trigger_action_n_position);
                        self.triggerActionNPositionMidHigh(self.triggerActions().mid_high.trigger_action_n_position);
                        self.triggerActionNDaysLow(self.triggerActions().low.trigger_action_n_days);
                        self.triggerActionNDaysLowMid(self.triggerActions().low_mid.trigger_action_n_days);
                        self.triggerActionNDaysMid(self.triggerActions().mid.trigger_action_n_days);
                        self.triggerActionNDaysMidHigh(self.triggerActions().mid_high.trigger_action_n_days);
                        self.productFields([...(response.data.category_fields || response.data.product_fields || [])]);
                        
                        /**
                         * Select default trigger action for each position and restore nPosition/nDays values
                         */
                        ['low', 'low_mid', 'mid', 'mid_high'].forEach(function (position) {
                            var defaultAction = self.triggerActions()[position].trigger_action;
                            var radioSelector = 'input[name="trigger_action_' + position + '"][value="' + defaultAction + '"]';
                            $(radioSelector).prop('checked', true).trigger('change');

                            /**
                             * Restore nPosition value
                             */
                            var nPositionInput = $('.wtai-trigger-action-n-position-' + position);
                            if (nPositionInput.length) {
                                nPositionInput.val(self.triggerActions()[position].trigger_action_n_position).trigger('change');
                            }

                            /**
                             * Restore nDays value
                             */
                            var nDaysInput = $('.wtai-trigger-action-after-n-days-' + position);
                            if (nDaysInput.length) {
                                nDaysInput.val(self.triggerActions()[position].trigger_action_n_days).trigger('change');
                            }
                        });

                        self.initTriggerActionsLabels();
                        self.isRestoring = false;
                    }
                }
            }).always(function () {
                self.removeRestoreGlobalLoader();
            });
        },

        /**
         * Initialize spinner
         */
        initSpinner: function () {
            setTimeout(
                function () {
                    $('.wtai-bulk-keyword-analysis-popup .wtai-cluster-count').spinner({
                        numberFormat: 'n',
                        min: this.minClusterCount(),
                        max: this.maxClusterCount(),
                        spin: function (event, ui) {
                            self.isSpinning = true;
                            self.clusterCount(ui.value);
                            self.isSpinning = false;
                        },
                        change: function (event) {
                            self.clusterCount(event.target.value);
                        }
                    });

                    var mapping = {
                        trigger_action_n_position_low: self.triggerActionNPositionLow,
                        trigger_action_n_position_low_mid: self.triggerActionNPositionLowMid,
                        trigger_action_n_position_mid: self.triggerActionNPositionMid,
                        trigger_action_n_position_mid_high: self.triggerActionNPositionMidHigh,
                        trigger_action_n_days_low: self.triggerActionNDaysLow,
                        trigger_action_n_days_low_mid: self.triggerActionNDaysLowMid,
                        trigger_action_n_days_mid: self.triggerActionNDaysMid,
                        trigger_action_n_days_mid_high: self.triggerActionNDaysMidHigh,
                    };

                    var syncTriggerSubtitle = function (inputName) {
                        var match = String(inputName || '').match(/^trigger_action_n_(position|days)_(low|low_mid|mid|mid_high)$/);
                        if (!match) {
                            return;
                        }

                        var group = match[2];
                        var selected = $(
                            'input[name="trigger_action_' + group + '"]:checked'
                        ).val();

                        if (!selected) {
                            selected = match[1] === 'position'
                                ? self.triggerActionPageIsRankingValue
                                : self.triggerActionAfterNDaysValue;
                        }

                        self.selectTriggerAction(group, selected);
                    };

                    $('.wtai-bulk-keyword-analysis-popup .wtai-input-number').each(function () {
                        var $input = $(this);
                        var name = $input.attr('name');
                        var min = Number($input.attr('min'));
                        var max = Number($input.attr('max'));

                        $input.spinner({
                            numberFormat: 'n',
                            min: isNaN(min) ? null : min,
                            max: isNaN(max) ? null : max,
                            spin: function (event, ui) {
                                var func = mapping[name];
                                self.isSpinning = true;
                                if (typeof func === 'function') {
                                    func(ui.value);
                                }
                                syncTriggerSubtitle(name);
                                self.isSpinning = false;
                            },
                            change: function (event) {
                                var func = mapping[event.target.name];
                                self.isSpinning = true;
                                if (typeof func === 'function') {
                                    func(event.target.value);
                                }
                                syncTriggerSubtitle(event.target.name);
                                self.isSpinning = false;
                            }
                        });
                    });
                }.bind(this),
                100
            );
        },

        /**
         * Initialize tooltip
         */
        initTooltip: function () {
            $(self.tooltipSelector).dropdown({
                parent: '.admin__field-tooltip',
                autoclose: true
            });
        },

        /**
         * Initialize trigger actions labels
         */
        initTriggerActionsLabels: function () {
            this.triggerActionChanged.low(false);
            this.triggerActionChanged.low_mid(false);
            this.triggerActionChanged.mid(false);
            this.triggerActionChanged.mid_high(false);
            this.selectTriggerAction('low', this.triggerActions().low.trigger_action);
            this.selectTriggerAction('low_mid', this.triggerActions().low_mid.trigger_action);
            this.selectTriggerAction('mid', this.triggerActions().mid.trigger_action);
            this.selectTriggerAction('mid_high', this.triggerActions().mid_high.trigger_action);
        },

        /**
         * Is intent selected
         */
        isIntentSelected: function (intent) {
            return this.searchIntent().indexOf(intent) !== -1;
        },

        /**
         * Get tooltip text search intent
         *
         * @param {String} intent
         * @return {String}
         */
        getTooltipTextSearchIntent: function (intent) {
            switch (intent) {
                case 'transactional':
                    return $t('Users aim to complete a transaction, such as making a purchase or signing up for a service.');
                case 'commercial':
                    return $t('Users are researching products or services with the intention of making a purchase decision soon.');
                case 'informational':
                    return $t('Users seek information on a specific topic, intending to learn something.');
                case 'navigational':
                    return $t('Users have a specific website or web page in mind and are using search engines to navigate there directly.');
                default:
                    return '';
            }
        },

        /**
         * Select search intent
         *
         * @param {String} intent
         * @return {void}
         */
        selectIntent: function (intent) {
            var searchIntent = this.searchIntent();

            this.isSingleSelectedWarningVisible(false);

            if (searchIntent.length <= 1 &&
                searchIntent.indexOf(intent) !== -1
            ) {
                this.headsupVisibility.transactional(false);
                this.headsupVisibility.commercial(false);
                this.headsupVisibility.navigational(false);
                this.headsupVisibility.informational(false);
                this.isSingleSelectedWarningVisible(true);
                return;
            }

            if (searchIntent.indexOf(intent) === -1) {
                searchIntent.push(intent);
            } else {
                searchIntent = searchIntent.filter(function (x) {
                    return x !== intent;
                });
            }

            this.searchIntent(searchIntent);
        },

        /**
         * Validate min and max fields.
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {void}
         */
        validateMinMax: function (data, event) {
            var target = event.target,
                value = Number(target.value),
                min = Number(target.min),
                max = Number(target.max),
                name = target.name;

            const mapping = {
                cluster_count: self.clusterCount,
                trigger_action_n_position_low: self.triggerActionNPositionLow,
                trigger_action_n_position_low_mid: self.triggerActionNPositionLowMid,
                trigger_action_n_position_mid: self.triggerActionNPositionMid,
                trigger_action_n_position_mid_high: self.triggerActionNPositionMidHigh,
                trigger_action_n_days_low: self.triggerActionNDaysLow,
                trigger_action_n_days_low_mid: self.triggerActionNDaysLowMid,
                trigger_action_n_days_mid: self.triggerActionNDaysMid,
                trigger_action_n_days_mid_high: self.triggerActionNDaysMidHigh,
            };

            if (value < min || value > max) {
                const func = mapping[name],
                    val = value < min ? min : max;

                $(target).val(val);
                func(val);
            }
        },

        /**
         * Validate number.
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {Boolean}
         */
        ensureNumerical: function (data, event) {
            return textfieldsUtils.ensureNumerical(event.key);
        },

        /**
         * Select trigger action
         *
         * @param {String} triggerAction
         * @param {String} value
         *
         * @return {void}
         */
        selectTriggerAction: function (triggerAction, value) {
            const actionMap = {
                low: {
                    position: this.triggerActionNPositionLow(),
                    days: this.triggerActionNDaysLow(),
                    subtitle: this.subTitleLow
                },
                low_mid: {
                    position: this.triggerActionNPositionLowMid(),
                    days: this.triggerActionNDaysLowMid(),
                    subtitle: this.subTitleLowMid
                },
                mid: {
                    position: this.triggerActionNPositionMid(),
                    days: this.triggerActionNDaysMid(),
                    subtitle: this.subTitleMid
                },
                mid_high: {
                    position: this.triggerActionNPositionMidHigh(),
                    days: this.triggerActionNDaysMidHigh(),
                    subtitle: this.subTitleMidHigh
                }
            };

            const action = actionMap[triggerAction];
            if (!action) {
                return;
            }

            const { position, days, subtitle } = action;

            /* Get the initial value from triggerActions */
            const initialValue = this.triggerActions()[triggerAction].trigger_action;
            const initialPosition = this.triggerActions()[triggerAction].trigger_action_n_position || 2;
            const initialDays = this.triggerActions()[triggerAction].trigger_action_n_days || 1;
            
            /* Update the changed state */
            if (value !== initialValue ||
                (value === self.triggerActionPageIsRankingValue && parseInt(position) !== parseInt(initialPosition)) ||
                (value === self.triggerActionAfterNDaysValue && parseInt(days) !== parseInt(initialDays))) {
                this.triggerActionChanged[triggerAction](true);
            } else {
                this.triggerActionChanged[triggerAction](false);
            }

            if (value === self.triggerActionPageIsRankingValue) {
                subtitle($t('Ranking 1 - %1').replace('%1', position));
            } else if (value === self.triggerActionAfterNDaysValue) {
                subtitle($t('After %1 day/s').replace('%1', days));
            } else {
                subtitle($t('None'));
            }
        },

        /**
         * Show educational tooltip for non-transactional intent selection
         *
         * @param {String} intent
         * @return {void}
         */
        showEducationalTooltipForIntent: function (intent) {
            if (self.isAcknowledgedHeadsUp()) {
                return;
            }

            var searchIntent = self.searchIntent();
            if (searchIntent.length > 0 && searchIntent.indexOf(intent) !== -1) {
                self.selectIntent(intent);
                return;
            }

            var message = $t('<p>Heads up! Category pages are generally best suited for <strong>commercial</strong> search intent—users comparing options and researching before making a purchase.</p><p>Using other intent types might not align well unless your category content is specifically designed for that purpose. Be sure it supports your broader SEO and user journey strategy.</p>');

            /** Only show tooltip for non-commercial intents */
            if (intent === 'commercial') {
                return;
            }
            

            /** Find the target element for the selected intent */
            const targetSelector = '.wtai-search-intent-option:contains("' + intent + '")';
            const $targetElement = $(targetSelector);

            if ($targetElement.length > 0) {
                this.showHeadsUp(
                    message,
                    'top',
                    intent,
                    $targetElement
                );
            }
        },

        /**
         * Show the tooltip
         *
         * @param {string} message - The message to display
         * @param {string} position - Position of the tooltip
         * @param {jQuery|string} targetElement - Target element or selector
         * @returns {void}
         */
        showHeadsUp: function (message, position = 'top', intent = 'transactional', targetElement = null) {
            this.headsupVisibility.transactional(false);
            this.headsupVisibility.commercial(false);
            this.headsupVisibility.navigational(false);
            this.headsupVisibility.informational(false);

            this.isSingleSelectedWarningVisible(false);

            if (this.isAcknowledgedHeadsUp()) {
                return;
            }

            this.messageHeadsUp(message);
            this.positionHeadsUp(position);
            this.targetElementHeadsUp = targetElement;
            this.headsupVisibility[intent](true);
        },

        /**
         * Acknowledge the heads up
         *
         * @param {string} intent - The intent to select
         * @returns {void}
         */
        acknowledgeHeadsUp: function (intent) {
            self.headsupVisibility.transactional(false);
            self.headsupVisibility.commercial(false);
            self.headsupVisibility.navigational(false);
            self.headsupVisibility.informational(false);
            self.selectIntent(intent);
        },

        /**
         * Bind click-outside handler for heads-up popup.
         */
        bindHeadsUpClickOutside: function () {
            $(document).off('click.wtaiKeywordAnalysisHeadsUp');
            $(document).on('click.wtaiKeywordAnalysisHeadsUp', function (event) {
                if ($(event.target).closest('.wtai-search-intent-option').length) {
                    return;
                }

                var isAnyHeadsUpVisible = self.headsupVisibility.transactional() ||
                                        self.headsupVisibility.commercial() ||
                                        self.headsupVisibility.navigational() ||
                                        self.headsupVisibility.informational();

                if (isAnyHeadsUpVisible && !$(event.target).closest('.wtai-educational-tooltip').length) {
                    self.headsupVisibility.transactional(false);
                    self.headsupVisibility.commercial(false);
                    self.headsupVisibility.navigational(false);
                    self.headsupVisibility.informational(false);
                }
            });
        },

        /**
         * Bind click-outside handler for single item tooltip.
         */
        bindSingleItemTooltipClickOutside: function () {
            $(document).off('click.wtaiKeywordAnalysisSingleItemTooltip');
            $(document).on('click.wtaiKeywordAnalysisSingleItemTooltip', function (event) {
                if ($(event.target).closest('.wtai-search-intent-option').length) {
                    return;
                }

                self.isSingleSelectedWarningVisible(false);
            });
        }
    });
});
