/**
 * Master Trainers Overview JavaScript
 * Handles AJAX loading of trainer data and filtering
 */

(function($) {
    'use strict';

    // Wait for DOM and dependencies
    $(document).ready(function() {
        console.log('[HVAC] Master Trainers Overview: Initializing...');

        // Check if we're on the trainers page
        if ($('#hvac-master-trainers-overview').length === 0) {
            console.log('[HVAC] Master Trainers Overview: Not on trainers page, skipping initialization');
            return;
        }

        console.log('[HVAC] Master Trainers Overview: Found trainers container, loading data...');

        // Load initial stats
        loadTrainerStats();

        // Load initial trainers list
        loadTrainersList();

        // Handle filter changes
        $('#hvac-trainers-filters').on('submit', function(e) {
            e.preventDefault();
            loadTrainersList();
        });

        // Handle filter changes on select/input
        $('#filter-status, #filter-region, #filter-search').on('change keyup', debounce(function() {
            loadTrainersList();
        }, 500));
    });

    /**
     * Load trainer statistics
     */
    function loadTrainerStats() {
        console.log('[HVAC] Loading trainer stats...');

        $.ajax({
            url: hvac_master_trainers_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_master_trainers_stats',
                nonce: hvac_master_trainers_ajax.nonce
            },
            success: function(response) {
                console.log('[HVAC] Stats loaded successfully', response);

                if (response.success && response.data.html) {
                    $('#hvac-stats-tiles').html(response.data.html).show();
                    $('#hvac-stats-loading').hide();
                } else {
                    console.error('[HVAC] Stats load failed:', response);
                    $('#hvac-stats-loading').html('<p class="hvac-error">Failed to load statistics.</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('[HVAC] Stats AJAX error:', status, error);
                $('#hvac-stats-loading').html('<p class="hvac-error">Error loading statistics.</p>');
            }
        });
    }

    /**
     * Load trainers list with current filters
     */
    function loadTrainersList() {
        console.log('[HVAC] Loading trainers list...');

        // Show loading state
        $('#hvac-trainers-loading').show();
        $('#hvac-trainers-table-container').hide();

        // Get filter values
        var filters = {
            action: 'hvac_master_trainers_filter',
            nonce: hvac_master_trainers_ajax.nonce,
            status: $('#filter-status').val() || 'all',
            region: $('#filter-region').val() || '',
            search: $('#filter-search').val() || ''
        };

        console.log('[HVAC] Filter values:', filters);

        $.ajax({
            url: hvac_master_trainers_ajax.ajax_url,
            type: 'POST',
            data: filters,
            success: function(response) {
                console.log('[HVAC] Trainers loaded successfully', response);

                if (response.success && response.data.html) {
                    $('#hvac-trainers-table-container').html(response.data.html).show();
                    $('#hvac-trainers-loading').hide();

                    // Initialize any interactive elements in the table
                    initializeTrainerActions();
                } else {
                    console.error('[HVAC] Trainers load failed:', response);
                    $('#hvac-trainers-loading').html('<p class="hvac-error">Failed to load trainers.</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('[HVAC] Trainers AJAX error:', status, error);
                $('#hvac-trainers-loading').html('<p class="hvac-error">Error loading trainers.</p>');
            }
        });
    }

    /**
     * Initialize trainer action buttons
     */
    function initializeTrainerActions() {
        console.log('[HVAC] Initializing trainer actions...');

        // Handle view profile buttons
        $('.hvac-view-trainer').on('click', function(e) {
            e.preventDefault();
            var trainerId = $(this).data('trainer-id');
            console.log('[HVAC] View trainer:', trainerId);
            // Navigate to trainer profile
            window.location.href = $(this).attr('href');
        });

        // Handle edit buttons
        $('.hvac-edit-trainer').on('click', function(e) {
            e.preventDefault();
            var trainerId = $(this).data('trainer-id');
            console.log('[HVAC] Edit trainer:', trainerId);
            window.location.href = $(this).attr('href');
        });

        // Any other interactive elements...
    }

    /**
     * Debounce function for search input
     */
    function debounce(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                func.apply(context, args);
            }, wait);
        };
    }

})(jQuery);
