/**
 * Members Module JavaScript
 */
(function() {
    'use strict';

    // Initialize member search Select2 (used by other modules too)
    window.initMemberSearch = function(selector, options) {
        $(selector).select2(Object.assign({
            theme: 'bootstrap-5',
            width: '100%',
            ajax: {
                url: '/api/members/search',
                dataType: 'json',
                delay: 300,
                data: function(params) {
                    return { q: params.term, page: params.page || 1 };
                },
                processResults: function(data) {
                    return {
                        results: data.results || [],
                        pagination: data.pagination || { more: false }
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            placeholder: 'Search member...',
            templateResult: function(item) {
                if (item.loading) return item.text;
                return $('<div>').html(
                    '<strong>' + (item.membership_number || '') + '</strong> — ' +
                    (item.name_en || item.text) +
                    (item.phone ? '<br><small class="text-muted">' + item.phone + '</small>' : '')
                );
            },
            templateSelection: function(item) {
                return item.text || item.membership_number;
            }
        }, options || {}));
    };

    // Auto-init any member search fields on page
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.member-search').forEach(function(el) {
            initMemberSearch(el);
        });
    });
})();