(function(){
  console.log('foo bar in new')
    $(document).on('keydown', function(e){
      if (e.key === '/' && !$(e.target).is('input, textarea')) {
        e.preventDefault();
        $('#globalSearch').focus().select();
      }
    });

    // quick loading of district/regional/national rows
    function updateCounts(){
      // $('#count-district').text($('#districtBody .user-row:visible').length);
      // $('#count-regional').text($('#regionalBody .user-row:visible').length);
      // $('#count-national').text($('#nationalBody .user-row:visible').length);
    }

    function getVisibleRowsInActiveTab(){
      const activePane = $('.tab-pane.active');
      return activePane.find('.user-row:visible');
    }

    // Select all visible in active tab
    $('#globalSelect').on('change', function(){
      const checked = $(this).is(':checked');
      getVisibleRowsInActiveTab().find('.row-select').prop('checked', checked).trigger('change');
    });

    // Row checkbox toggles bulk buttons
    $(document).on('change', '.row-select', function(){
      const anyChecked = $('.tab-pane.active .row-select:checked').length > 0;
      $('#bulkMoveBtn, #bulkDeactivate').prop('disabled', !anyChecked);
      // sync header select state
      const total = getVisibleRowsInActiveTab().find('.row-select').length;
      const checked = getVisibleRowsInActiveTab().find('.row-select:checked').length;
      $('#globalSelect').prop('checked', total>0 && total===checked);
    });

    let searchTimer;

    $('#globalSearch').on('keyup', function() {
        clearTimeout(searchTimer);
        let query = $(this).val();

        // Optional: Slightly fade the tables to show it is loading
        $('#districtBody, #regionalBody, #nationalBody').css('opacity', '0.5');

        // Wait 500ms after the user stops typing
        searchTimer = setTimeout(function() {
            
            $.ajax({
                url: window.location.pathname, // Request the same page
                type: "GET",
                data: { search: query },
                success: function(response) {
                    // Turn the returned text into a searchable DOM object
                    let html = $(response);

                    // 1. Swap the Table Bodies
                    $('#districtBody').html(html.find('#districtBody').html());
                    $('#regionalBody').html(html.find('#regionalBody').html());
                    $('#nationalBody').html(html.find('#nationalBody').html());

                    // 2. Swap the Tab Counts
                    $('#count-district').text(html.find('#count-district').text());
                    $('#count-regional').text(html.find('#count-regional').text());
                    $('#count-national').text(html.find('#count-national').text());

                    // 3. Swap the Pagination links
                    $('#district-pagination').html(html.find('#district-pagination').html());
                    $('#regional-pagination').html(html.find('#regional-pagination').html());
                    $('#national-pagination').html(html.find('#national-pagination').html());

                    // Remove the fade effect
                    $('#districtBody, #regionalBody, #nationalBody').css('opacity', '1');
                },
                error: function() {
                    console.error("Live search failed");
                    $('#districtBody, #regionalBody, #nationalBody').css('opacity', '1');
                }
            });

        }, 500); // 500ms delay
    });

    // $('#globalSearch').on('input', applyFilters);
    // $('.filter-status').on('change', applyFilters);

    // Activate tab event -> clear globalSelect and bulk buttons
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(){
      $('#globalSelect').prop('checked', false);
      $('#bulkMoveBtn, #bulkDeactivate').prop('disabled', true);
    });

    // Edit button opens modal and populates fields
    let lastTrigger = null;
    $(document).on('click', '.editBtnXX', function(){
      lastTrigger = this;
      const row = $(this).closest('.user-row');
      $('#editId').val(row.data('id'));
      $('#editName').val(row.data('name'));
      $('#editEmail').val(row.data('email'));
      $('#editCategory').val(row.data('category'));
    });

    

    // Bulk move: gather selected rows and show count
    $('#bulkMoveBtn').on('click', function(){
      const selected = $('.tab-pane.active .row-select:checked');
      $('#moveCount').text(selected.length);
      // focus first control in modal for accessibility
      $('#moveModal').on('shown.bs.modal', function(){ $('#moveTarget').focus(); });
    });

    // Remember trigger to restore focus after move modal
    $('#moveModal').on('hidden.bs.modal', function(){ $('.tab-pane.active').find('.row-select:checked').first().closest('tr').find('.row-select').focus(); });

    // Execute move
    $('#moveForm').on('submit', function(e){
      e.preventDefault();
      const target = $('#moveTarget').val();
      const selected = $('.tab-pane.active .row-select:checked').closest('.user-row');
      selected.each(function(){
        const $r = $(this);
        $r.data('category', target);
        $r.find('.category-badge').removeClass('badge-district badge-regional badge-national');
        if (target === 'District') $r.find('.category-badge').addClass('badge-district').text('District');
        if (target === 'Regional') $r.find('.category-badge').addClass('badge-regional').text('Regional');
        if (target === 'National') $r.find('.category-badge').addClass('badge-national').text('National');
        const targetBody = target === 'District' ? '#districtBody' : (target === 'Regional' ? '#regionalBody' : '#nationalBody');
        $r.appendTo($(targetBody));
        $r.find('.row-select').prop('checked', false);
      });
      $('#moveModal').modal('hide');
      $('#globalSelect').prop('checked', false);
      $('#bulkMoveBtn, #bulkDeactivate').prop('disabled', true);
      updateCounts();
    });

    // Bulk deactivate demo (toggles status)
    $('#bulkDeactivate').on('click', function(){
      const selected = $('.tab-pane.active .row-select:checked').closest('.user-row');
      selected.each(function(){
        const $r = $(this);
        $r.data('status', 'Suspended');
        // add visual cue
        $r.addClass('table-danger');
        setTimeout(()=> $r.removeClass('table-danger'), 1200);
        $r.find('.row-select').prop('checked', false);
      });
      $('#bulkMoveBtn, #bulkDeactivate').prop('disabled', true);
    });


    // ensure focus is moved first.
    // Update counts initially
    updateCounts();

    // Demo: focus first edit button when pressing 'e' (example of keyboard shortcut)
    $(document).on('keydown', function(e){
      if (e.key === 'e' && !$(e.target).is('input, textarea')) {
        e.preventDefault();
        $('.editBtn').first().focus();
      }
    });
    $('#editRegionID').change(function(){
        console.log('change is coming');
        var options = $('#editDistrictID');
        var region_id = $('#editRegionID').val();       
        $.ajax({
        url: base_url + '/admin/districts/' + region_id,
        type: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'crossDomain': false
        },
        success: function(data) {
            $.each(data['districts'], function(id, row) {
                $('#editDistrictID').append($("<option />").val(row.districtid).text(row.district_name));
            });
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
        }
    });
  });
  })();