jQuery(document).ready(function($) {

    // Inicializar las pestañas
    $("#easy-gpt-tabs").tabs();
    $("#easy-gpt-image-tabs").tabs();

    // Función para refrescar las pestañas de imágenes
    function refreshImageTabs() {
        var numImages = $('#easy_gpt_num_images').val();
        var imageTabsList = $('#easy-gpt-image-tabs-list');
        var imageTabsContent = $('#easy-gpt-image-tabs');

        // Limpiar pestañas existentes
        imageTabsList.empty();
        imageTabsContent.children('div[id^="image-tab-"]').remove();

        // Generar nuevas pestañas
        for (var i = 1; i <= numImages; i++) {
            imageTabsList.append('<li><a href="#image-tab-' + i + '">Image ' + i + '</a></li>');
            imageTabsContent.append(
                '<div id="image-tab-' + i + '">' +
                    '<div class="easy-gpt-field">' +
                        '<label for="easy_gpt_image_prompt_' + i + '">Image Prompt ' + i + ' (one line per article):</label>' +
                        '<textarea id="easy_gpt_image_prompt_' + i + '" name="easy_gpt_image_prompt_' + i + '" rows="2" cols="50"></textarea>' +
                    '</div>' +
                    '<div class="easy-gpt-inline">' +
                        '<input type="checkbox" id="use_same_easy_gpt_image_prompt_' + i + '" name="use_same_image_prompts[]" class="adjusted-checkbox">' +
                        '<label for="use_same_easy_gpt_image_prompt_' + i + '" class="normal-label">Use same Image ' + i + ' instructions for all articles</label>' +
                    '</div>' +
                '</div>'
            );
        }

        // Refrescar las pestañas
        imageTabsContent.tabs("refresh");
    }

    // Evento para cambios en el número de imágenes
    $('#easy_gpt_num_images').on('change input', function() {
        refreshImageTabs();
    });

    // Refrescar las pestañas de imágenes al cargar
    refreshImageTabs();

    // Función para manejar la lógica de categorías y etiquetas
    function toggleCategoryTagSettings() {
        if ($('#easy_gpt_auto_categories').is(':checked')) {
            console.log('Categories checkbox is checked');
            // Aquí puedes agregar lógica adicional si es necesario
        } else {
            console.log('Categories checkbox is not checked');
            // Aquí puedes agregar lógica adicional si es necesario
        }
        if ($('#easy_gpt_auto_tags').is(':checked')) {
            console.log('Tags checkbox is checked');
            // Aquí puedes agregar lógica adicional si es necesario
        } else {
            console.log('Tags checkbox is not checked');
            // Aquí puedes agregar lógica adicional si es necesario
        }
    }

    // Evento para cambios en categorías y etiquetas
    $('#easy_gpt_auto_categories, #easy_gpt_auto_tags').change(function() {
        toggleCategoryTagSettings();
    });

    // Ejecutar en carga inicial
    toggleCategoryTagSettings();

    var isRequesting = false;

    // Evento para el botón "Generate Articles"
    $('#generate-all').off('click').on('click', function(e) {
        e.preventDefault();

        // Obtener y validar valores del formulario
        var prompt = $('#easy_gpt_prompt').val().trim();
        var keywords = $('#easy_gpt_keywords').val().trim();
        var numArticles = parseInt($('#easy_gpt_number_of_articles').val(), 10);

        console.log('Prompt Value:', prompt);
        console.log('Keywords Value:', keywords);
        console.log('Number of Articles:', numArticles);

        if (prompt === '') {
            console.error('Validation Error: Prompt field is empty.');
            alert('Please enter a Prompt.');
            return;
        }

        if (keywords === '') {
            console.error('Validation Error: Keywords field is empty.');
            alert('Please enter Keywords.');
            return;
        }

        if (isNaN(numArticles) || numArticles < 1) {
            console.error('Validation Error: Number of articles is invalid.');
            alert('The number of articles must be at least 1.');
            return;
        }

		const promptLines = prompt.split('\n').filter(line => line.trim() !== '');
    	const keywordLines = keywords.split('\n').filter(line => line.trim() !== '');
		
		if (promptLines.length !== keywordLines.length) {
			alert('The number of prompts and keywords must be the same. Please ensure each prompt has a corresponding keyword.');
			return;
		}

		if (promptLines.length !== numArticles) {
			alert(`The number of prompts (${promptLines.length}) does not match the number of articles (${numArticles}). Please adjust accordingly.`);
			return;
		}

		if (keywordLines.length !== numArticles) {
			alert(`The number of keywords (${keywordLines.length}) does not match the number of articles (${numArticles}). Please adjust accordingly.`);
			return;
		}

        console.log('All validations passed. Preparing to send AJAX request.');

        if (isRequesting) return;

        isRequesting = true;
        var $button = $(this);
        $button.text('Requesting...');

        console.log("Content Type:", $('#content_type').val());

        var data = {
            'action': 'save_bulk_generation',
            'nonce': $('#easy_gpt_nonce').val(),
            'prompt_article': $('#easy_gpt_prompt').val(),
            'keywords': $('#easy_gpt_keywords').val(),
            'num_articles': $('#easy_gpt_number_of_articles').val(),
            'content_type': $('#content_type').val(),
            'enable_product_prices': $('#enable_product_prices').is(':checked') ? 1 : 0,
            'product_prices': $('#easy_gpt_product_prices').val(),
            'model': $('#easy_gpt_model').val(),
            'temperature': $('#easy_gpt_temperature').val(),
            'language': $('#easy_gpt_default_language').val(),
            'min_words': $('#easy_gpt_min_words').val(),
            'max_words': $('#easy_gpt_max_words').val(),
            'num_subheadings': $('#easy_gpt_num_subheadings').val(),
            'subheading_types': getSubheadingTypes(),
            'format_article': $('#easy_gpt_format_article').is(':checked') ? 1 : 0,
            'include_links': $('#easy_gpt_include_links').is(':checked') ? 1 : 0,
            'include_bibliography': $('#easy_gpt_include_bibliography').is(':checked') ? 1 : 0,
            'auto_categories': $('#easy_gpt_auto_categories').is(':checked') ? 1 : 0,
            'auto_tags': $('#easy_gpt_auto_tags').is(':checked') ? 1 : 0,
            'enable_seo': $('#easy_gpt_auto_seo').is(':checked') ? 1 : 0,
            'writing_style': $('#easy_gpt_writing_style').val(),
            'writing_tone': $('#easy_gpt_writing_tone').val(),
            'include_excerpt': $('#easy_gpt_include_excerpt').is(':checked') ? 1 : 0,
            'image_model': $('#easy_gpt_image_model').val(),
            'auto_images': $('#easy_gpt_auto_images').is(':checked') ? 1 : 0,
            'num_images': $('#easy_gpt_num_images').val(),
            'image_size': $('#easy_gpt_image_size').val(),
            'image_quality': $('#easy_gpt_image_quality').val(),
            'image_style': $('#easy_gpt_image_style').val(),
            'set_featured_image': $('#easy_gpt_set_featured_image').is(':checked') ? 1 : 0,
            'specific_instructions_title': $('#easy_gpt_specific_instructions_title').val(),
            'use_specific_title_instructions': $('#use_specific_title_instructions').is(':checked') ? 1 : 0,
            'use_same_specific_title_instructions': $('#use_same_specific_title_instructions').is(':checked') ? 1 : 0,
            'specific_instructions_outline': $('#easy_gpt_specific_instructions_outline').val(),
            'use_same_specific_outline_instructions': $('#use_same_specific_outline_instructions').is(':checked') ? 1 : 0,
            'specific_instructions_content': $('#easy_gpt_specific_instructions_content').val(),
            'use_same_specific_content_instructions': $('#use_same_specific_content_instructions').is(':checked') ? 1 : 0,
            'specific_instructions_excerpt': $('#easy_gpt_specific_instructions_excerpt').val(),
            'use_same_specific_excerpt_instructions': $('#use_same_specific_excerpt_instructions').is(':checked') ? 1 : 0,
            'publish_action': $('#publish_action').val(),
            'publish_frequency': $('#publish_frequency').val(),
            'start_date': $('#start_date').val(),
            'start_time': $('#start_time').val(),
            'articles_per_interval': $('#articles_per_interval').val(),
            'easy_gpt_include_videos_bulk': $('#easy_gpt_include_videos_bulk').is(':checked') ? 1 : 0,
            'easy_gpt_video_position_bulk': $('#easy_gpt_video_position_bulk').val(),
            'easy_gpt_video_paragraph_bulk': $('#easy_gpt_video_paragraph_bulk').val(),
            'easy_gpt_include_citations_bulk': $('#easy_gpt_include_citations_bulk').is(':checked') ? 1 : 0,
            'easy_gpt_final_review_bulk': $('#easy_gpt_final_review_bulk').is(':checked') ? 1 : 0,
            'minutes_between_articles': $('#minutes_between_articles').val(),
			'just_in_time_generation': $('#just_in_time_generation').is(':checked') ? 1 : 0,
			'text_provider': $('#easy_gpt_text_provider').val(),
            'image_provider': $('#easy_gpt_image_provider').val(),
            'user_id' : $('#easy_gpt_default_author_bulk').val(),
        };
        
        console.log('User ID enviado:', data.user_id);

        console.log(data);

        // Colección de image_prompts y use_same_image_prompts
        var image_prompts = [];
        var use_same_image_prompts = [];
        var numImages = $('#easy_gpt_num_images').val();
        for (var i = 1; i <= numImages; i++) {
            var prompt = $('#easy_gpt_image_prompt_' + i).val().split('\n');
            image_prompts.push(prompt);
            use_same_image_prompts.push($('#use_same_easy_gpt_image_prompt_' + i).is(':checked') ? 1 : 0);
        }
        data['image_prompts'] = JSON.stringify(image_prompts);
        data['use_same_image_prompts'] = JSON.stringify(use_same_image_prompts);

        const maxLengths = {
            'image_style': 250,
        };
        
        for (const field in maxLengths) {
            const value = data[field] || '';
            if (value.length > maxLengths[field]) {
                alert(`The field "${field.replace(/_/g, ' ')}" is too long. Maximum allowed is ${maxLengths[field]} characters.`);
                $button.text('Generate Articles');
                isRequesting = false;
                return;
            }
        }

        $.post(ajaxurl, data, function(response) {
            console.log(response); // Registro para depuración
            if (response.success) {
                alert('Generation saved! ID: ' + response.data.id);
                $button.text('Generating Articles...');
                startArticleGeneration(response.data.id, data.num_articles); // Pasar data.num_articles
            } else {
                alert('Failed to save generation.');
                $button.text('Generate Articles');
                isRequesting = false;
            }
        });
    });

    // Función para iniciar la generación de artículos
    function startArticleGeneration(generationId, numArticles) {
        console.log("Starting generation for ID: " + generationId + " with " + numArticles + " articles.");

        var data = {
            'action': 'easy_gpt_start_generation',
            'nonce': $('#easy_gpt_nonce').val(),
            'generation_id': generationId,
            'num_articles': numArticles
        };

        $.post(ajaxurl, data, function(response) {
            console.log(response); // Registro para depuración
            if (response.success) {
                console.log("Generation started successfully.");
                window.location.href = 'admin.php?page=easy-gpt-bulk-generate-view';
            } else {
                console.error("Failed to start generation: " + response.data.message);
            }
        });
    }

    // Función para obtener tipos de subencabezados
    function getSubheadingTypes() {
        var types = [];
        if ($('#easy_gpt_subheading_type_h3').is(':checked')) types.push('H3');
        if ($('#easy_gpt_subheading_type_h4').is(':checked')) types.push('H4');
        return types.join(',');
    }

    // Manejar la lógica de mostrar/ocultar para Video Position
    $('#easy_gpt_video_position_bulk').on('change', function() {
        console.log("Video Position changed to:", $(this).val()); // Depuración
        if ($(this).val() === 'after_paragraph') {
            $('#easy_gpt_video_paragraph_container_bulk').slideDown();
        } else {
            $('#easy_gpt_video_paragraph_container_bulk').slideUp();
        }
    });

    // Inicializar el estado al cargar la página para Video Position
    if ($('#easy_gpt_video_position_bulk').val() === 'after_paragraph') {
        $('#easy_gpt_video_paragraph_container_bulk').show();
    } else {
        $('#easy_gpt_video_paragraph_container_bulk').hide();
    }

    // Manejar la lógica de mostrar/ocultar para Content Type (Articles/Products)
    $('#content_type_toggle').on('change', function() {
        if ($(this).is(':checked')) {
            $('#content_type').val('product');
            $('.products-label').addClass('active');
            $('.articles-label').removeClass('active');
            $('#price-option-container').slideDown();
        } else {
            $('#content_type').val('article');
            $('.articles-label').addClass('active');
            $('.products-label').removeClass('active');
            $('#price-option-container').slideUp();
            $('#enable_product_prices').prop('checked', false);
            $('#price-input-container').slideUp();
        }
        console.log("Content Type Updated:", $('#content_type').val()); // Depuración
    });

    // Manejar la lógica de mostrar/ocultar para Precios de Productos
    $('#enable_product_prices').on('change', function() {
        if ($(this).is(':checked')) {
            $('#price-input-container').slideDown();
        } else {
            $('#price-input-container').slideUp();
        }
    });

    // Inicializar el estado al cargar la página para Precios de Productos
    if ($('#enable_product_prices').is(':checked')) {
        $('#price-input-container').show();
    } else {
        $('#price-input-container').hide();
    }

});

jQuery(document).ready(function($) {
    $('#articles_per_interval').on('input change', function() {
        const value = parseInt($(this).val(), 10);
        if (value > 1) {
            $('#minutes_between_articles_container').slideDown();
        } else {
            $('#minutes_between_articles_container').slideUp();
        }
    }).trigger('change'); // Ejecutar una vez al cargar la página
});

document.addEventListener('DOMContentLoaded', function() {
    // --- TEXT API PROVIDER & MODEL ---
    const textProviderSelect = document.getElementById('easy_gpt_text_provider');
    const textModelSelect = document.getElementById('easy_gpt_model');

    if (textProviderSelect && textModelSelect) {
        function filterTextModels() {
            const selectedProvider = textProviderSelect.value;
            Array.from(textModelSelect.options).forEach(option => {
                const optionProvider = option.getAttribute('data-api') || 'openai';
                option.style.display = (optionProvider === selectedProvider) ? 'block' : 'none';
            });

            // Si el modelo actualmente seleccionado no pertenece al proveedor, resetear
            const selectedOption = textModelSelect.options[textModelSelect.selectedIndex];
            if (selectedOption && selectedOption.style.display === 'none') {
                const firstVisible = Array.from(textModelSelect.options).find(opt => opt.style.display === 'block');
                if (firstVisible) {
                    firstVisible.selected = true;
                }
            }
        }

        textProviderSelect.addEventListener('change', filterTextModels);
        filterTextModels(); // Ejecutar al cargar
    }

    // --- IMAGE API PROVIDER & MODEL ---
    const imageProviderSelect = document.getElementById('easy_gpt_image_provider');
    const imageModelSelect = document.getElementById('easy_gpt_image_model');

    if (imageProviderSelect && imageModelSelect) {
        function filterImageModels() {
            const selectedProvider = imageProviderSelect.value;
            Array.from(imageModelSelect.options).forEach(option => {
                const optionProvider = option.getAttribute('data-api') || 'openai';
                option.style.display = (optionProvider === selectedProvider) ? 'block' : 'none';
            });

            const selectedOption = imageModelSelect.options[imageModelSelect.selectedIndex];
            if (selectedOption && selectedOption.style.display === 'none') {
                const firstVisible = Array.from(imageModelSelect.options).find(opt => opt.style.display === 'block');
                if (firstVisible) {
                    firstVisible.selected = true;
                }
            }
        }

        imageProviderSelect.addEventListener('change', filterImageModels);
        filterImageModels(); // Ejecutar al cargar
    }
});

