/**
 * @fileoverview Manages room member management functionality.
 * This file handles:
 * - User selection interface using Select2
 * - Adding new members to a room
 * - Removing existing members
 * - Form submission with member data
 */

/**
 * Initializes member management functionality when the document is ready.
 * Sets up:
 * - Select2 dropdown for user selection
 * - Member removal functionality
 * - Member addition functionality
 * - Form submission handling
 * @function
 */
$(document).ready(function() {
    // Initialize Select2 for user selection
    $('.select2').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });

    /**
     * Handles member removal from the list.
     * Removes the member row from the UI when the remove button is clicked.
     * @event
     */
    $(document).on('click', '.btn-remove-member', function() {
        const memberRow = $(this).closest('.member-row');
        memberRow.remove();
    });

    /**
     * Handles adding a new member to the list.
     * Validates the selection and adds the member if not already present.
     * Creates a new member row with user details and adds it to the list.
     * @event
     */
    $('#addMemberBtn').on('click', function() {
        const select = $('#user_id');
        const selectedOption = select.find('option:selected');
        const selectedValue = select.val();
        
        if (!selectedValue) {
            return;
        }

        const userId = selectedValue;
        const userName = selectedOption.text();
        const userEmail = selectedOption.data('email');
        const userAvatar = selectedOption.data('avatar');

        // Check if user is already in the list
        if ($(`.member-row[data-user-id="${userId}"]`).length > 0) {
            return;
        }

        // Create new member row
        const memberRow = `
            <div class="list-group-item d-flex align-items-center member-row" data-user-id="${userId}">
                <img class="member-avatar" src="${userAvatar}">
                <div class="flex-grow-1">
                    <div class="fw-bold">${userName}</div>
                    <div class="text-muted small">${userEmail}</div>
                </div>
                <button type="button" class="btn btn-remove-member ms-2">
                    <i class="fas fa-user-minus me-1"></i>Remove
                </button>
            </div>
        `;

        // Add to the list
        $('#selectedMembersList').append(memberRow);
        
        // Clear the select and trigger change event
        select.val(null).trigger('change');
    });

    /**
     * Handles form submission.
     * Collects all member IDs and adds them as hidden inputs to the form.
     * @event
     * @param {Event} e - The form submission event
     */
    $('#membersForm').on('submit', function(e) {
        e.preventDefault();
        
        // Collect all member IDs
        const memberIds = [];
        $('.member-row').each(function() {
            memberIds.push($(this).data('user-id'));
        });

        // Remove any existing hidden inputs
        $('input[name="members"]').remove();

        // Add hidden input for each member ID
        memberIds.forEach(function(id) {
            $('#membersForm').append(`<input type="hidden" name="members" value="${id}">`);
        });

        // Submit the form
        this.submit();
    });
}); 