// Объявляем глобальные переменные, чтобы они гарантированно существовали
if (typeof window.globalSettings === 'undefined') {
    window.globalSettings = {};
}
if (typeof window.initialSettings === 'undefined') {
    window.initialSettings = {};
}
if (typeof window.longreadSettings === 'undefined') {
    window.longreadSettings = {};
}

jQuery(document).ready(function($) {
    var $form = $('#ai_content_wizard_form'),
        $preload = $('#preload'),
        $preloadLongread = $('#preload-longread'),
        $postGenerationButtons = $('#post_generation_buttons'),
        $postGenerationButtonsLongread = $('#post_generation_buttons_longread'),
        $contentLoader = $('#generating_content_text, #tips, .ai-loader'),
        $viewPost = $('#view_post'),
        $viewPostLongread = $('#view_post_longread'),
        $generateAnotherPost = $('#generate_another_post'),
        $generateAnotherPostLongread = $('#generate_another_post_longread');

    var tipsInterval,
        longreadTipsInterval,
        progressInterval,
        // Определяем порядок этапов генерации (ожидаемые маркеры от сервера)
        progressMarkers = [
            'keyword_generation',
            'content_creation',
            'additional_images',
            'featured_image',
            'seo_optimization',
            'alt_texts',
            'done'
        ];


	$generateAnotherPost.on('click', function(e) {
		e.preventDefault();
		location.reload();
	});

    function cycleTips() {
        var $tips = $('#tips');
        if (!Array.isArray(window.tips) || window.tips.length === 0) {
            return;
        }

        function getRandomTipIndex(prevIndex) {
            if (window.tips.length === 1) {
                return 0;
            }
            var nextIndex;
            do {
                nextIndex = Math.floor(Math.random() * window.tips.length);
            } while (nextIndex === prevIndex);
            return nextIndex;
        }

        var previousIndex = typeof window.lastTipIndex === 'number' ? window.lastTipIndex : -1;
        var currentIndex = getRandomTipIndex(previousIndex);
        $tips.text(window.tips[currentIndex]);
        window.lastTipIndex = currentIndex;

        tipsInterval = setInterval(function() {
            currentIndex = getRandomTipIndex(window.lastTipIndex);
            $tips.fadeOut(180, function() {
                $(this).text(window.tips[currentIndex]).fadeIn(180);
            });
            window.lastTipIndex = currentIndex;
        }, 5000);
    }

    function cycleTipsForLongread() {
        var $tipsLong = $('#tips_longread');
        if (!Array.isArray(window.tips) || window.tips.length === 0 || !$tipsLong.length) {
            return;
        }

        function getRandomTipIndex(prevIndex) {
            if (window.tips.length === 1) {
                return 0;
            }
            var nextIndex;
            do {
                nextIndex = Math.floor(Math.random() * window.tips.length);
            } while (nextIndex === prevIndex);
            return nextIndex;
        }

        var previousIndex = typeof window.longreadLastTipIndex === 'number' ? window.longreadLastTipIndex : -1;
        var currentIndex = getRandomTipIndex(previousIndex);
        $tipsLong.text(window.tips[currentIndex]);
        window.longreadLastTipIndex = currentIndex;

        longreadTipsInterval = setInterval(function() {
            currentIndex = getRandomTipIndex(window.longreadLastTipIndex);
            $tipsLong.fadeOut(180, function() {
                $(this).text(window.tips[currentIndex]).fadeIn(180);
            });
            window.longreadLastTipIndex = currentIndex;
        }, 5000);
    }

    // Функция обновления прогресс-бара по маркеру, полученному от сервера
    function updateProgressBar(currentMarker) {
        // Определяем контейнер в зависимости от режима
        var container = $('#post_mode_toggle').is(':checked') ? $preloadLongread : $preload;
        var currentIndex = progressMarkers.indexOf(currentMarker);
        // Если сервер не передал ожидаемый маркер, оставляем текст как есть
        var localizedText = container.find('#progress_bar .stage').eq(currentIndex).attr('data-tooltip') || currentMarker;
        container.find('#current_stage_text').text('Current Stage: ' + localizedText);
        
        container.find('#progress_bar .stage').each(function(index) {
            if (index < currentIndex) {
                $(this).removeClass('pending current').addClass('completed');
            } else if (index === currentIndex) {
                $(this).removeClass('pending completed').addClass('current');
            } else {
                $(this).removeClass('completed current').addClass('pending');
            }
        });
    }

    // Функция для опроса сервера о текущем статусе генерации
    function startProgressPolling() {
        progressInterval = setInterval(function() {
            $.ajax({
                type: 'POST',
                url: ajaxurl,
                data: {
                    action: 'get_generation_progress',
                    progress_uid: window.progressUID || ''
                },
                dataType: 'json',
                success: function(response) {
                    if (response && response.success && response.data && response.data.marker) {
                        var marker = response.data.marker;
                        updateProgressBar(marker);
                        if (marker === 'done') {
                            clearInterval(progressInterval);
                        }
                    } else {
                        console.warn("Progress not received properly:", response);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("Error retrieving generation progress: " + textStatus + " : " + errorThrown);
                }
            });
        }, 2000);
    }

    function stopProgressPolling() {
        if (progressInterval) {
            clearInterval(progressInterval);
        }
    }

    // Функция показа прелоадера (с учетом режима)
    function showLoader() {
        clearInterval(tipsInterval);
        clearInterval(longreadTipsInterval);
        $preload.removeClass('generation-complete');
        $preloadLongread.removeClass('generation-complete');
        if ($('#post_mode_toggle').is(':checked')) {
            $preload.hide();
            $preloadLongread.show();
            cycleTipsForLongread();
            startProgressPolling();
        } else {
            $preloadLongread.hide();
            $preload.show();
            cycleTips();
            startProgressPolling();
        }
    }

    function hideLoader() {
        $contentLoader.hide();
        $preload.hide();
        $preloadLongread.hide();
        stopProgressPolling();
    }

    function updateUIAfterSuccess(postTitle, postUrl) {
        clearInterval(tipsInterval);
        clearInterval(longreadTipsInterval);
        stopProgressPolling();
        
        var container = $('#post_mode_toggle').is(':checked') ? $preloadLongread : $preload;
        container.find('.ai-loader, #current_stage_text').hide();
        container.addClass('generation-complete');
        
        if ($('#post_mode_toggle').is(':checked')) {
            container.find('#generating_longread_text').text(postTitle || 'Article Generated');
        } else {
            container.find('#generating_content_text').text(postTitle || 'Article Generated');
        }
        
        if ($('#post_mode_toggle').is(':checked')) {
            $viewPostLongread.attr('href', postUrl);
            $postGenerationButtonsLongread.show();
        } else {
            $viewPost.attr('href', postUrl);
            $postGenerationButtons.show();
        }
        
        localStorage.removeItem('ai_content_wizard_progress_uid');
    }

    // Таймер (без изменений)
    window.startTimer = function() {
        window.generationStartTime = new Date().getTime();
        window.timerInterval = setInterval(function() {
            var now = new Date().getTime();
            var elapsedSec = Math.floor((now - window.generationStartTime) / 1000);
            var minutes = Math.floor(elapsedSec / 60);
            var seconds = elapsedSec % 60;
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            $('#timer_display').text(minutes + ':' + seconds);
        }, 1000);
    };

    window.stopTimer = function() {
        clearInterval(window.timerInterval);
    };

    // Обработка отправки формы
    $form.on('submit', function(e) {
        e.preventDefault();
        
        // Генерируем progressUID и сохраняем его
        var progressUID = 'uid_' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
        localStorage.setItem('ai_content_wizard_progress_uid', progressUID);
        if ($form.find('input[name="progress_uid"]').length === 0) {
            $form.append('<input type="hidden" name="progress_uid" value="' + progressUID + '">');
        }
        window.progressUID = progressUID;
        
        showLoader();
        startTimer();
    
        var action = $('#post_mode_toggle').is(':checked') ? 'generate_expert_post' : 'generate_single_post';
        var formData = $form.serialize() + '&action=' + action;
    
        $.ajax({
            type: 'POST',
            url: ajaxurl,
            data: formData,
            success: function(response) {
                if (response.success && response.data && response.data.post_url) {
                    updateUIAfterSuccess(response.data.post_title, response.data.post_url);
                    stopTimer();
                } else if (response.data && response.data.post_url) {
                    updateUIAfterSuccess(response.data.post_title, response.data.post_url);
                    alert('The article was generated, but there were some issues: ' + response.data.message);
                    stopTimer();
                } else {
                    alert(response.data.message || 'Unknown error occurred.');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("AJAX error: " + textStatus + ' : ' + errorThrown);
                var errorMsg = 'An error occurred while processing your request.';
                if (jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
                    errorMsg += "\nDetails: " + jqXHR.responseJSON.data.message;
                }
                alert(errorMsg);
                hideLoader();
                stopTimer();
            }
        });
    });
    
    // Если есть сохранённый progressUID, удаляем его
    localStorage.removeItem('ai_content_wizard_progress_uid');
    
    // Валидация формы
    var $submitButton = $('button[name="ai_content_wizard_generate_post"]');
    var $categorySelect = $('#category');
    var $postTopicInput = $('#post_topic');
    
    function checkFormValidity() {
        var isCategorySelected = $categorySelect.val() !== '';
        var postTopicValue = $postTopicInput.val() || '';
        var isTopicEntered = postTopicValue.trim() !== '';
        var isValid = isCategorySelected && isTopicEntered;
    
        $submitButton.prop('disabled', !isValid);
        $submitButton.toggleClass('disabled-state', !isValid);
    }
    
    $categorySelect.add($postTopicInput).on('change keyup', checkFormValidity);
    checkFormValidity();
    
    // Обновление блока Global Settings
	function updateSettingsDisplay(settings) {
		$('.settings-display').empty();
		$.each(settings, function(key, value) {
			var badge = '';
			// Если настройка должна отображаться с бейджем (Pro), добавляем его
			if(key.toLowerCase() === 'additional images' || key.toLowerCase() === 'region'){
			   badge = ' <span class="pro-badge" style="font-size:12px; background:#0073aa; color:#fff; padding:2px 4px; border-radius:3px; margin-left:5px;">PRO</span>';
			}
			$('.settings-display').append(
				'<div class="setting-item"><span class="setting-name"><strong>' +
				key + ':</strong> ' + value + badge +
				'</span><a href="/wp-admin/admin.php?page=ai_content_wizard_settings" class="edit-setting-link">Edit</a></div>'
			);
		});
	}

    
    window.updateSettingsDisplay = updateSettingsDisplay;
    updateSettingsDisplay(globalSettings);
    
    // Обновление оценки стоимости генерации
    function getSettingValue(key) {
        var value = '';
        $('.settings-display .setting-item').each(function() {
            var text = $(this).find('.setting-name').text().trim();
            var parts = text.split(':');
            if (parts.length > 1 && parts[0].trim().toLowerCase() === key.toLowerCase()) {
                value = parts[1].trim();
            }
        });
        return value;
    }
    
    function updateEstimatedCost() {
        var textLength = parseInt(getSettingValue("Text Length")) || parseInt(initialSettings.textLength);
        var enableImage = ((getSettingValue("Enable Image Generation") === "1") || (initialSettings.enableImageGeneration == 1)) ? 1 : 0;
        var postType = initialSettings.post_mode || "Single";
        var textModel = initialSettings.textModel;
        var imageModel = initialSettings.imageModel || 'dall-e-3';
        var imageQuality = initialSettings.imageQuality || 'standard';
        var imageResolution = initialSettings.imageResolution || '1024x1024';
        var additionalImages = 0;
        
        $.post(ajaxurl, {
            action: 'get_estimated_cost',
            text_model: textModel,
            text_length: textLength,
            post_type: postType,
            enable_image: enableImage,
            enable_additional_images: 0,
            image_model: imageModel,
            image_quality: imageQuality,
            image_resolution: imageResolution,
            additional_images: additionalImages
        }, function(response) {
            if (response.success) {
                $('#estimated_cost_value').text(response.data.estimated_cost);
            }
        });
    }
    
    $('.ai-content-wizard-form input, .ai-content-wizard-form select, .ai-content-wizard-form textarea')
        .on('change input keyup click', function() {
            updateEstimatedCost();
        });
    
    $('.edit-setting-link').on('click', function() {
       updateEstimatedCost();
    });
    
    updateEstimatedCost();
    
    var settingsDisplay = document.querySelector('.settings-display');
    if (settingsDisplay) {
        var observer = new MutationObserver(function(mutationsList, observer) {
            updateEstimatedCost();
        });
        observer.observe(settingsDisplay, { childList: true, subtree: true, characterData: true });
    }
});
