jQuery(document).ready(function($) {
    // 1. Confirm delete action
    $(document).on('click', '.aisbw-confirm-delete', function(e) {
        if (!confirm('Usunąć ten temat?')) {
            e.preventDefault();
        }
    });

    // 2. Toggle password visibility (show/hide API keys)
    $(document).on('click', '.aisbw-toggle-password', function() {
        const $btn = $(this);
        const $input = $btn.siblings('input');
        const $icon = $btn.find('i');

        if ($input.attr('type') === 'password') {
            $input.attr('type', 'text');
            $icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            $input.attr('type', 'password');
            $icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });

    // 3. Dynamic display of fields based on the selected AI Provider
    const $providerSelect = $('#aisbw-ai-provider');
    if ($providerSelect.length) {
        function toggleProviderFields() {
            const provider = $providerSelect.val();

            // Select elements to group
            const groups = {
                openai: [
                    '#aisbw-openai-api-key',
                    '#aisbw-openai-model',
                    '#aisbw-openai-quality-model'
                ],
                
            };

            // Hide all rows initially
            Object.keys(groups).forEach(function(key) {
                groups[key].forEach(function(selector) {
                    $(selector).closest('tr').hide();
                });
            });

            // Show selected provider rows
            if (groups[provider]) {
                groups[provider].forEach(function(selector) {
                    $(selector).closest('tr').show();
                });
            }
        }

        // Run on load and on change
        $providerSelect.on('change', toggleProviderFields);
        toggleProviderFields();
    }
});
