(function($) {
    'use strict';

    // Provider switching — toggle help text and model options
    $('#wpsc_ai_provider').on('change', function() {
        var provider = $(this).val();

        // Hide all help texts
        $('.wpsc-help-groq, .wpsc-help-gemini, .wpsc-help-openai').hide();

        // Show relevant help and auto-select model
        if (provider === 'groq') {
            $('.wpsc-help-groq').show();
            $('#wpsc_ai_model').val('llama-3.3-70b-versatile');
        } else if (provider === 'gemini') {
            $('.wpsc-help-gemini').show();
            $('#wpsc_ai_model').val('gemini-2.0-flash');
        } else {
            $('.wpsc-help-openai').show();
            $('#wpsc_ai_model').val('gpt-4o-mini');
        }
    });

    // Re-index content
    $('#wpsc-reindex-btn').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var $status = $('#wpsc-reindex-status');

        $btn.prop('disabled', true).text('Indexing...');
        $status.text('');

        $.ajax({
            url: wpscAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wpsc_reindex',
                nonce: wpscAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    $status.text(response.data.message);
                    $('#wpsc-chunk-count').text(response.data.count);
                } else {
                    $status.text('Error: ' + response.data);
                }
            },
            error: function() {
                $status.text('Connection error. Please try again.');
            },
            complete: function() {
                $btn.prop('disabled', false).text('Re-index Content Now');
            }
        });
    });

    // Clear chat history
    $('#wpsc-clear-history').on('click', function(e) {
        e.preventDefault();

        if (!confirm('Are you sure you want to clear all chat history? This cannot be undone.')) {
            return;
        }

        $.ajax({
            url: wpscAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'wpsc_clear_history',
                nonce: wpscAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                }
            }
        });
    });

})(jQuery);
