(function($) {
    $(document).ready(function() {
        // Обработчик для значков помощи (кнопок с "?")
        $('.aiw-help-icon').on('click', function() {
            var modalId = $(this).attr('onclick').match(/'([^']+)'/)[1]; // Извлекаем modalId из onclick
            openModal(modalId);
        });

        $('.aiw-tab-button').on('click', function() {
            $('.aiw-tab-button').removeClass('active');
            $('.aiw-tab-content').removeClass('active');
            $(this).addClass('active');
            var tab = $(this).data('tab');
            $('#' + tab).addClass('active');
        });

        function toggleTextProviders(provider) {
            $('#openai_key_block, #anthropic_key_block, #deepseek_key_block').hide();
            $('#openai_models_container, #anthropic_models_container, #deepseek_models_container, #fine_tuned_container').hide();
            if (provider === 'openai') {
                $('#openai_key_block').show();
                $('#openai_models_container').show();
                $('#fine_tuned_container').show();
            } else if (provider === 'anthropic') {
                $('#anthropic_key_block').show();
                $('#anthropic_models_container').show();
            } else if (provider === 'deepseek') {
                $('#deepseek_key_block').show();
                $('#deepseek_models_container').show();
            }
        }
        $('input[name="text_provider"]').on('change', function() {
            toggleTextProviders($(this).val());
            if ($('#interactive-hint').is(':visible')) {
                currentSubStep++;
                if (currentSubStep < subSteps.length) {
                    updateHint(currentSubStep);
                } else {
                    hideHints();
                }
            }
        });
        var initialTextProvider = $('input[name="text_provider"]:checked').val();
        if (initialTextProvider) {
            toggleTextProviders(initialTextProvider);
        }

        function toggleImageProviders(provider) {
            $('#dalle_key_block, #deepai_key_block, #stablediffusion_key_block, #ideogram_key_block').hide();
            $('#dalle_models_container, #deepai_models_container, #stablediffusion_models_container, #ideogram_models_container').hide();
            if (provider === 'dalle') {
                $('#dalle_key_block').show();
                $('#dalle_models_container').show();
            } else if (provider === 'deepai') {
                $('#deepai_key_block').show();
                $('#deepai_models_container').show();
            } else if (provider === 'stablediffusion') {
                $('#stablediffusion_key_block').show();
                $('#stablediffusion_models_container').show();
            } else if (provider === 'ideogram') {
                $('#ideogram_key_block').show();
                $('#ideogram_models_container').show();
            }
        }
        $('input[name="image_provider"]').on('change', function() {
            toggleImageProviders($(this).val());
            if ($('#interactive-hint').is(':visible')) {
                currentSubStep++;
                if (currentSubStep < subSteps.length) {
                    updateHint(currentSubStep);
                } else {
                    hideHints();
                }
            }
        });
        var initialImageProvider = $('input[name="image_provider"]:checked').val();
        if (initialImageProvider) {
            toggleImageProviders(initialImageProvider);
        }

        $('input[type="text"], input[type="email"]').on('input', function() {
            if ($(this).val().length > 0 && $('#interactive-hint').is(':visible') && 
                (currentSubStep === 1 || currentSubStep === 4)) {
                currentSubStep++;
                if (currentSubStep < subSteps.length) {
                    updateHint(currentSubStep);
                } else {
                    hideHints();
                }
            }
        });

        $('input[name^="text_model"], input[name^="image_model"]').on('change', function() {
            if ($('#interactive-hint').is(':visible') && (currentSubStep === 2 || currentSubStep === 5)) {
                currentSubStep++;
                if (currentSubStep < subSteps.length) {
                    updateHint(currentSubStep);
                } else {
                    hideHints();
                }
            }
        });

        $('#toggle-floating-status').on('click', function() {
            var content = $('.aiw-floating-status-content');
            if (content.is(':visible')) {
                content.hide();
                $(this).html('+');
            } else {
                content.show();
                $(this).html('−');
                $('#aiw-floating-status-header').removeClass('pulsate');
            }
        });

        $('.ai-help-modal-close, .ai-content-wizard-close').on('click', closeModal);

        $(document).on('click', function(e) {
            var $target = $(e.target);
            if ($target.hasClass('ai-help-modal') && !$target.closest('.ai-help-modal-content').length) {
                closeModal();
            }
            if ($target.hasClass('ai-content-wizard-modal') && !$target.closest('.ai-content-wizard-modal-content').length) {
                closeModal();
            }
        });

        var currentSubStep = 0;
        var subSteps = [];

        var textProviderSubSteps = [
            {
                getElement: function() { return document.querySelector('#api-settings-text-models .aiw-radio-group'); },
                hintId: 'hint-text-1'
            },
            {
                getElement: function() {
                    var provider = $('input[name="text_provider"]:checked').val();
                    if (provider === 'openai') return document.getElementById('openai_key_block');
                    else if (provider === 'anthropic') return document.getElementById('anthropic_key_block');
                    else if (provider === 'deepseek') return document.getElementById('deepseek_key_block');
                },
                hintId: 'hint-text-2'
            },
            {
                getElement: function() {
                    var provider = $('input[name="text_provider"]:checked').val();
                    if (provider === 'openai') return document.getElementById('text-models-radio-group');
                    else if (provider === 'anthropic') return document.getElementById('anthropic_models_container');
                    else if (provider === 'deepseek') return document.getElementById('deepseek_models_container');
                },
                hintId: 'hint-text-3'
            }
        ];

        var imageProviderSubSteps = [
            {
                getElement: function() { return document.querySelector('#api-settings-image-models .aiw-radio-group'); },
                hintId: 'hint-text-4'
            },
            {
                getElement: function() {
                    var provider = $('input[name="image_provider"]:checked').val();
                    if (provider === 'dalle') return document.getElementById('dalle_key_block');
                    else if (provider === 'deepai') return document.getElementById('deepai_key_block');
                    else if (provider === 'stablediffusion') return document.getElementById('stablediffusion_key_block');
                    else if (provider === 'ideogram') return document.getElementById('ideogram_key_block');
                },
                hintId: 'hint-text-5'
            },
            {
                getElement: function() {
                    var provider = $('input[name="image_provider"]:checked').val();
                    if (provider === 'dalle') return document.getElementById('dalle_models_container');
                    else if (provider === 'deepai') return document.getElementById('deepai_models_container');
                    else if (provider === 'stablediffusion') return document.getElementById('stablediffusion_models_container');
                    else if (provider === 'ideogram') return document.getElementById('ideogram_models_container');
                },
                hintId: 'hint-text-6'
            }
        ];

        var currentStep = $('input[name="ai_content_wizard_wizard_step"]').val();
        if (currentStep === 'text_provider') {
            subSteps = textProviderSubSteps;
            activateHints();
        } else if (currentStep === 'image_provider') {
            subSteps = imageProviderSubSteps;
            activateHints();
        }

        function activateHints() {
            $('#hint-overlays').show();
            $('#interactive-hint').css({ opacity: 0, transform: 'scale(0.9)' }).show().animate({ opacity: 1, transform: 'scale(1)' }, 300);
            $('body').css('overflow', 'hidden');
            updateHint(currentSubStep);
            var initialElement = subSteps[currentSubStep].getElement();
            if (initialElement) {
                scrollToElement(initialElement);
            }

            $('#hint-next').on('click', function() {
                currentSubStep++;
                if (currentSubStep < subSteps.length) {
                    var nextElement = subSteps[currentSubStep].getElement();
                    if (nextElement) scrollToElement(nextElement);
                    updateHint(currentSubStep);
                } else {
                    hideHints();
                }
            });

            $('#hint-skip').on('click', hideHints);

            $('.hint-prev').on('click', function(e) {
                e.preventDefault();
                if (currentSubStep > 0) {
                    currentSubStep--;
                    var prevElement = subSteps[currentSubStep].getElement();
                    if (prevElement) scrollToElement(prevElement);
                    updateHint(currentSubStep);
                }
            });

            // Скрываем кнопку "Back" на первом шаге (индекс 0)
            function toggleBackButton() {
                if (currentSubStep === 0) {
                    $('.hint-prev').hide();
                } else {
                    $('.hint-prev').show();
                }
            }
            toggleBackButton();

            // Обновляем видимость кнопки "Back" при каждом изменении шага
            $('#hint-next, #hint-skip').on('click', toggleBackButton);
            $('.hint-prev').on('click', toggleBackButton);

            $('#hint-next').hover(
                function() { $(this).css({ 'background': '#43A047', 'transform': 'scale(1.05)' }); },
                function() { $(this).css({ 'background': '#4CAF50', 'transform': 'scale(1)' }); }
            ).on('mousedown', function() {
                $(this).css('transform', 'scale(0.95)');
            }).on('mouseup mouseout', function() {
                $(this).css('transform', 'scale(1)');
            });

            $('#hint-skip').hover(
                function() { $(this).css({ 'background': '#ced4da', 'transform': 'scale(1.05)' }); },
                function() { $(this).css({ 'background': '#e9ecef', 'transform': 'scale(1)' }); }
            ).on('mousedown', function() {
                $(this).css('transform', 'scale(0.95)');
            }).on('mouseup mouseout', function() {
                $(this).css('transform', 'scale(1)');
            });
        }

        function updateHint(index) {
            var subStep = subSteps[index];
            var element = subStep.getElement();
            if (!element) {
                $('#hint-text-1, #hint-text-2, #hint-text-3, #hint-text-4, #hint-text-5, #hint-text-6').hide();
                $('#hint-text-1').text('<?php _e( "Please complete the previous step first.", "ai-content-wizard" ); ?>').show();
                $('#hint-next').prop('disabled', true);
                return;
            }
            $('#hint-next').prop('disabled', false);
            highlightElement(element);
            var hintId = subStep.hintId;
            $('#hint-text-1, #hint-text-2, #hint-text-3, #hint-text-4, #hint-text-5, #hint-text-6').hide();
            $('#' + hintId).show();
            // Позиционирование подсказки выполняется после прокрутки в scrollToElement
        }

        function highlightElement(element) {
            $('.highlight').removeClass('highlight');
            $(element).addClass('highlight');
        }

        function positionHintAboveElement(element) {
            var $element = $(element);
            var offset = $element.offset();
            var width = $element.outerWidth();
            var height = $element.outerHeight();
            var hint = $('#interactive-hint');
            var hintHeight = hint.outerHeight();
            var hintWidth = hint.outerWidth();
            var adminBarHeight = $('#wpadminbar').outerHeight() || 0;
            var sidebarWidth = $('#adminmenuwrap').outerWidth() || 0;
            var windowHeight = $(window).height();
            var windowWidth = $(window).width();
            var scrollTop = $(window).scrollTop();

            var elementTop = offset.top - scrollTop; // Позиция элемента относительно области видимости
            var spaceAbove = elementTop - adminBarHeight;
            var topPosition;
            if (spaceAbove >= hintHeight + 15) {
                topPosition = elementTop - hintHeight - 15; // Подсказка на 15px выше элемента
            } else {
                topPosition = elementTop + height + 15; // Если места сверху нет, размещаем снизу
            }

            var leftPosition = offset.left + (width / 2) - (hintWidth / 2);
            if (leftPosition < sidebarWidth) {
                leftPosition = sidebarWidth + 10;
            } else if (leftPosition + hintWidth > windowWidth) {
                leftPosition = windowWidth - hintWidth - 10;
            }

            hint.css({
                position: 'fixed',
                top: topPosition,
                left: leftPosition
            });
        }

        function scrollToElement(element) {
            var $element = $(element);
            var offset = $element.offset();
            var adminBarHeight = $('#wpadminbar').outerHeight() || 0;
            var hint = $('#interactive-hint');
            var hintHeight = hint.outerHeight();
            var desiredScrollTop = offset.top - hintHeight - 15 - adminBarHeight;
            var scrollTop = Math.max(0, desiredScrollTop); // Не допускаем прокрутку выше начала страницы
            $('html, body').animate({
                scrollTop: scrollTop
            }, 400, function() {
                if ($('#interactive-hint').is(':visible')) {
                    positionHintAboveElement(element);
                }
            });
        }

        function hideHints() {
            $('#hint-overlays').hide();
            $('#interactive-hint').animate({ opacity: 0, transform: 'scale(0.9)' }, 300, function() {
                $(this).hide();
            });
            $('.highlight').removeClass('highlight');
            $('body').css('overflow', 'auto');
        }

        $(window).on('scroll resize', function() {
            if ($('#interactive-hint').is(':visible')) {
                var element = $('.highlight')[0];
                if (element) {
                    positionHintAboveElement(element);
                }
            }
        });
    });

    // Восстанавливаем старый подход к открытию модальных окон
    window.openModal = function(modalId) {
        var modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'flex';
        } else {
            console.error('Modal with ID ' + modalId + ' not found');
        }
    };

    window.closeModal = function() {
        $('.ai-help-modal, .ai-content-wizard-modal').hide();
    };

    window.showSuccessModal = function() {
        var modal = document.getElementById("successModal");
        if (modal) modal.style.display = "flex";
    };

    window.showGenericErrorModal = function() {
        var modal = document.getElementById("genericErrorModal");
        if (modal) modal.style.display = "flex";
    };

    window.showOpenAIErrorModal = function() {
        var modal = document.getElementById("openAIErrorModal");
        if (modal) modal.style.display = "flex";
    };

    window.showAnthropicErrorModal = function() {
        var modal = document.getElementById("anthropicErrorModal");
        if (modal) modal.style.display = "flex";
    };

    window.showDeepSeekErrorModal = function() {
        var modal = document.getElementById("deepseekErrorModal");
        if (modal) modal.style.display = "flex";
    };

    window.showOpenAIModelsSuccess = function() {
        var modal = document.getElementById("openaiModelsSuccessModal");
        if (modal) modal.style.display = "flex";
    };

    window.showOpenAIModelsError = function() {
        var modal = document.getElementById("openaiModelsErrorModal");
        if (modal) modal.style.display = "flex";
    };
})(jQuery);