/**
 * User Profile Select2 Member Management
 * 
 * Handles the Select2 dropdown for linking/unlinking members to WordPress users.
 *
 * @since 1.0.0
 */

// Import Select2 if not already available globally
import 'select2';
import 'select2/dist/css/select2.min.css';

jQuery(document).ready(function($) {
    'use strict';

    // Check if we're on a user profile page and have the select element
    const $memberSelect = $('.rewardswp-member-select');
    if (!$memberSelect.length || typeof rewardswpUserProfile === 'undefined') {
        return;
    }

    // Initialize Select2
    $memberSelect.select2({
        ajax: {
            url: rewardswpUserProfile.ajaxUrl,
            dataType: 'json',
            delay: 300,
            data: function(params) {
                return {
                    action: 'rewardswp_search_available_members',
                    search: params.term,
                    user_id: $memberSelect.data('user-id'),
                    nonce: rewardswpUserProfile.nonce,
                    page: params.page || 1
                };
            },
            processResults: function(data) {
                if (data.success) {
                    // Add "No member linked" option at the top if not already present
                    const results = data.data.results || [];
                    const hasEmptyOption = results.some(item => item.id === '');
                    
                    if (!hasEmptyOption) {
                        results.unshift({
                            id: '',
                            text: rewardswpUserProfile.strings.noMemberLinked
                        });
                    }
                    
                    return {
                        results: results
                    };
                } else {
                    console.error('RewardsWP: Error loading members:', data.data?.message);
                    return {
                        results: []
                    };
                }
            },
            cache: true
        },
        placeholder: rewardswpUserProfile.strings.searchMembers,
        allowClear: true,
        minimumInputLength: 0,
        language: {
            searching: function() {
                return rewardswpUserProfile.strings.loadingMembers;
            },
            noResults: function() {
                return rewardswpUserProfile.strings.noMembersFound;
            }
        }
    });

    // Handle welcome email checkbox visibility (only exists on user-new.php)
    const $welcomeEmailCheckbox = $('#rewardswp_send_welcome_email');
    
    if ($welcomeEmailCheckbox.length) {
        const $welcomeEmailWrapper = $welcomeEmailCheckbox.parent().find('br, #rewardswp_send_welcome_email, label[for="rewardswp_send_welcome_email"]');
        
        $memberSelect.on('change', function() {
            const selectedValue = $(this).val();
            
            // Show/hide welcome email option based on whether a member is being linked
            if (selectedValue && selectedValue !== '') {
                // Member being linked - hide welcome email option (they're already a member)
                $welcomeEmailWrapper.hide();
            } else {
                // No member linked - show welcome email option for new member creation
                $welcomeEmailWrapper.show();
            }
        });
    }

    // Trigger change on load to set initial state
    $memberSelect.trigger('change');

    // Styling is handled via CSS

    // Form submission handling (confirmation removed per user request)
});
