/**
 * FajaedeSEO AI Settings Admin JavaScript
 */

jQuery(document).ready(function($) {
    const api = {
        testHealth: function() {
            return $.ajax({
                url: fajaedeseAI.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fajaedeseo_test_health',
                    nonce: fajaedeseAI.nonce,
                },
            });
        },
        testTitle: function() {
            return $.ajax({
                url: fajaedeseAI.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fajaedeseo_test_title',
                    nonce: fajaedeseAI.nonce,
                },
            });
        },
        testKeywords: function() {
            return $.ajax({
                url: fajaedeseAI.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fajaedeseo_test_keywords',
                    nonce: fajaedeseAI.nonce,
                },
            });
        },
        clearCache: function() {
            return $.ajax({
                url: fajaedeseAI.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fajaedeseo_clear_cache',
                    nonce: fajaedeseAI.nonce,
                },
            });
        },
    };
    
    function showResult(data, status) {
        const $result = $('#test-result');
        const $content = $('#test-result-content');
        
        const output = JSON.stringify(data, null, 2);
        $content.text(output);
        $result.show();
        $result[0].scrollIntoView({ behavior: 'smooth' });
    }
    
    function showError(xhr, status, error) {
        const $result = $('#test-result');
        const $content = $('#test-result-content');
        
        let errorMsg = 'Unknown error';
        if (xhr.responseJSON && xhr.responseJSON.data) {
            errorMsg = xhr.responseJSON.data;
        } else if (error) {
            errorMsg = error;
        }
        
        $content.text('Error: ' + errorMsg);
        $result.show();
        $result[0].scrollIntoView({ behavior: 'smooth' });
    }
    
    // Test Health
    $('#btn-test-health').on('click', function(e) {
        e.preventDefault();
        $(this).prop('disabled', true).text('Testing...');
        
        api.testHealth()
            .done(function(response) {
                showResult(response.data, response.success);
            })
            .fail(showError)
            .always(function() {
                $('#btn-test-health').prop('disabled', false).text('Test Health');
            });
    });
    
    // Test Title
    $('#btn-test-title').on('click', function(e) {
        e.preventDefault();
        $(this).prop('disabled', true).text('Testing...');
        
        api.testTitle()
            .done(function(response) {
                showResult(response.data, response.success);
            })
            .fail(showError)
            .always(function() {
                $('#btn-test-title').prop('disabled', false).text('Test Title Generation');
            });
    });
    
    // Test Keywords
    $('#btn-test-keywords').on('click', function(e) {
        e.preventDefault();
        $(this).prop('disabled', true).text('Testing...');
        
        api.testKeywords()
            .done(function(response) {
                showResult(response.data, response.success);
            })
            .fail(showError)
            .always(function() {
                $('#btn-test-keywords').prop('disabled', false).text('Test Keywords');
            });
    });
    
    // Clear Cache
    $('#btn-clear-cache').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('Clear all AI cache? This may affect performance temporarily.')) {
            return;
        }
        
        $(this).prop('disabled', true).text('Clearing...');
        
        api.clearCache()
            .done(function(response) {
                showResult(response.data, response.success);
            })
            .fail(showError)
            .always(function() {
                $('#btn-clear-cache').prop('disabled', false).text('Clear AI Cache');
            });
    });

    // Bulk Actions Generation
    $('#btn-bulk-generate-meta').on('click', function() {
        const btn = $(this);
        const resultsDiv = $('#bulk-generation-results');
        
        btn.prop('disabled', true).text('Generating...');
        resultsDiv.html('<p>Starting generation... This may take a moment.</p>').show();

        // Verzamel geselecteerde post ID's van de checkboxes
        const post_ids = [];
        $('#fajaedeseo-bulk-post-selector .fajaedeseo-bulk-post-id:checked').each(function() {
            post_ids.push($(this).val());
        });

        // Verzamel geselecteerde meta types
        const meta_types = [];
        if ($('#fajaedeseo_bulk_meta_title').is(':checked')) meta_types.push('title');
        if ($('#fajaedeseo_bulk_meta_description').is(':checked')) meta_types.push('description');
        if ($('#fajaedeseo_bulk_meta_keywords').is(':checked')) meta_types.push('keywords');

        if (post_ids.length === 0) {
            alert('Please select at least one post.');
            btn.prop('disabled', false).text('Start Bulk Generation');
            resultsDiv.hide();
            return;
        }

        if (meta_types.length === 0) {
            alert('Please select at least one meta type to generate (Title, Description, or Keywords).');
            btn.prop('disabled', false).text('Start Bulk Generation');
            resultsDiv.hide();
            return;
        }

        // Voer de REST API call uit
        $.ajax({
            url: fajaedeseAI.restUrl,
            method: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', fajaedeseAI.restNonce);
            },
            data: JSON.stringify({
                post_ids: post_ids,
                meta_types: meta_types
            }),
            contentType: 'application/json',
            success: function(response) {
                btn.prop('disabled', false).text('Start Bulk Generation');
                let html = '<h4>Generation Complete:</h4><ul>';
                for (const postId in response) {
                    const res = response[postId];
                    html += `<li style="margin-bottom: 8px;"><strong>Post ID ${postId}:</strong> `;
                    if (res.success) {
                        html += '<span style="color:green;">Success!</span>';
                        if (res.title) html += `<br><small><strong>Title:</strong> "${res.title}"</small>`;
                        if (res.description) html += `<br><small><strong>Desc:</strong> "${res.description}"</small>`;
                        if (res.keywords) html += `<br><small><strong>Keywords:</strong> "${res.keywords}"</small>`;
                    } else {
                        html += `<span style="color:red;">Failed:</span> ${res.message || 'Unknown error'}`;
                    }
                    html += '</li>';
                }
                html += '</ul>';
                resultsDiv.html(html);
            },
            error: function(jqXHR) {
                btn.prop('disabled', false).text('Start Bulk Generation');
                const errorMsg = jqXHR.responseJSON && jqXHR.responseJSON.message ? jqXHR.responseJSON.message : 'An unknown AJAX error occurred.';
                resultsDiv.html(`<p style="color:red;"><strong>Error:</strong> ${errorMsg}</p>`);
            }
        });
    });
});
