/**
 * SCPWOO Admin — WordPress native UI
 *
 * Uses WP native notices, nav-tab-wrapper, buttons.
 */
jQuery(function ($) {
  'use strict';

  var params = scpwoo_admin_params;
  var loadedRegions = {};
  var rzSearchTimer;
  var hasUnsavedChanges = false;
  var skipUnsavedCheck = false;

  // =========================================================================
  // AJAX Tab Navigation
  // =========================================================================

  var $tabContent = $('#scpwoo-tab-content');
  var isLoadingTab = false;

  $(document).on('click', '.scpwoo-tabs .nav-tab', function (e) {
    var $link = $(this);
    if ($link.hasClass('nav-tab-active') || isLoadingTab) {
      e.preventDefault();
      return;
    }

    if (hasUnsavedChanges && !skipUnsavedCheck) {
      e.preventDefault();
      var $pending = $link;
      showConfirm(
        params.i18n.unsaved_changes || 'You have unsaved changes. Leave this tab and discard them?',
        function () {
          hasUnsavedChanges = false;
          skipUnsavedCheck = true;
          $pending.trigger('click');
          skipUnsavedCheck = false;
        },
        { confirmText: params.i18n.leave || 'Leave', danger: true }
      );
      return;
    }

    var href = $link.attr('href');
    var match = href.match(/[?&]tab=([^&]+)/);
    var tab = match ? match[1] : 'dashboard';

    e.preventDefault();
    isLoadingTab = true;

    $('.scpwoo-tabs .nav-tab').removeClass('nav-tab-active');
    $link.addClass('nav-tab-active');
    $tabContent.addClass('scpwoo-loading');

    $.post(params.ajax_url, {
      action: 'scpwoo_load_tab',
      nonce: params.nonce,
      tab: tab
    }, function (response) {
      isLoadingTab = false;
      if (response.success) {
        hasUnsavedChanges = false;
        $tabContent.html(response.data.html).removeClass('scpwoo-loading');
        loadedRegions = {};
        clearTimeout(rzSearchTimer);
        initCountryFilters();
        $('.scpwoo-tabs [role="tab"]').attr('aria-selected', 'false');
        $link.attr('aria-selected', 'true');
        $tabContent.attr('aria-labelledby', $link.attr('id'));
        if (window.history.pushState) {
          window.history.pushState({ tab: tab }, '', href);
        }
      } else {
        $tabContent.removeClass('scpwoo-loading');
        showNotice(params.i18n.error, 'error');
      }
    }).fail(function () {
      isLoadingTab = false;
      $tabContent.removeClass('scpwoo-loading');
      window.location.href = href;
    });
  });

  $(window).on('popstate', function (e) {
    var state = e.originalEvent.state;
    if (state && state.tab) {
      var $link = $('.scpwoo-tabs .nav-tab[data-tab="' + state.tab + '"]');
      if ($link.length) {
        $('.scpwoo-tabs .nav-tab').removeClass('nav-tab-active');
        $link.addClass('nav-tab-active');
        $('.scpwoo-tabs [role="tab"]').attr('aria-selected', 'false');
        $link.attr('aria-selected', 'true');
        $tabContent.attr('aria-labelledby', $link.attr('id'));
        $tabContent.addClass('scpwoo-loading');
        $.post(params.ajax_url, {
          action: 'scpwoo_load_tab',
          nonce: params.nonce,
          tab: state.tab
        }, function (response) {
          if (response.success) {
            $tabContent.html(response.data.html).removeClass('scpwoo-loading');
            loadedRegions = {};
            initCountryFilters();
          }
        });
      }
    }
  });

  if (window.history.replaceState) {
    var initMatch = window.location.search.match(/[?&]tab=([^&]+)/);
    window.history.replaceState({ tab: initMatch ? initMatch[1] : 'dashboard' }, '', window.location.href);
  }

  // Keyboard navigation for tabs (arrow keys)
  $(document).on('keydown', '.scpwoo-tabs [role="tab"]', function(e) {
    var $tabs = $('.scpwoo-tabs [role="tab"]');
    var idx = $tabs.index(this);
    var newIdx = -1;

    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
      newIdx = (idx + 1) % $tabs.length;
    } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
      newIdx = (idx - 1 + $tabs.length) % $tabs.length;
    } else if (e.key === 'Home') {
      newIdx = 0;
    } else if (e.key === 'End') {
      newIdx = $tabs.length - 1;
    }

    if (newIdx >= 0) {
      e.preventDefault();
      $tabs.eq(newIdx).focus().trigger('click');
    }
  });

  // Track unsaved changes in settings and restrictions forms
  $(document).on('change input', '#scpwoo-tab-content input, #scpwoo-tab-content select, #scpwoo-tab-content textarea', function () {
    var tab = $('.scpwoo-tabs .nav-tab-active').data('tab');
    if (tab === 'settings' || tab === 'restrictions') {
      hasUnsavedChanges = true;
    }
  });

  // =========================================================================
  // Setup Guide — Dismiss
  // =========================================================================

  $(document).on('click', '#scpwoo-dismiss-guide', function () {
    $(this).closest('.scpwoo-guide').slideUp(300, function () { $(this).remove(); });
    $.post(params.ajax_url, { action: 'scpwoo_dismiss_guide', nonce: params.nonce });
  });

  // =========================================================================
  // Notices — WordPress native (replaces custom toast)
  // =========================================================================

  function showNotice(message, type) {
    type = type || 'success';
    var wpClass = type === 'error' ? 'notice-error' : (type === 'warning' ? 'notice-warning' : 'notice-success');
    var $notice = $(
      '<div class="notice ' + wpClass + ' is-dismissible"><p>' +
      $('<span>').text(message).html() +
      '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>'
    );
    var $target = $tabContent.length ? $tabContent : $('.scpwoo-wrap h1');
    $target.before($notice);
    $notice.find('.notice-dismiss').on('click', function () { $notice.fadeOut(200, function () { $(this).remove(); }); });
    setTimeout(function () { $notice.fadeOut(200, function () { $(this).remove(); }); }, 5000);
  }

  // Expose globally for shipping inline JS
  window.scpwooToast = showNotice;

  // =========================================================================
  // Confirm modal — replaces native confirm() for better UX
  // =========================================================================

  function showConfirm(message, onConfirm, options) {
    options = options || {};
    var title = options.title || '';
    var confirmText = options.confirmText || 'OK';
    var cancelText = options.cancelText || params.i18n.cancel || 'Cancel';
    var danger = options.danger !== false;

    var $overlay = $(
      '<div class="scpwoo-modal-overlay">' +
      '<div class="scpwoo-modal" role="alertdialog" aria-modal="true" aria-label="' + escapeAttr(title || message) + '">' +
      (title ? '<h3 class="scpwoo-modal-title">' + escapeHtml(title) + '</h3>' : '') +
      '<p class="scpwoo-modal-message">' + escapeHtml(message) + '</p>' +
      '<div class="scpwoo-modal-actions">' +
      '<button type="button" class="button scpwoo-modal-cancel">' + escapeHtml(cancelText) + '</button>' +
      '<button type="button" class="button ' + (danger ? 'button-danger' : 'button-primary') + ' scpwoo-modal-confirm">' + escapeHtml(confirmText) + '</button>' +
      '</div>' +
      '</div>' +
      '</div>'
    );

    $('body').append($overlay);
    $overlay.find('.scpwoo-modal-confirm').focus();

    // Close on cancel or overlay click
    $overlay.on('click', '.scpwoo-modal-cancel', function () { $overlay.remove(); });
    $overlay.on('click', function (e) {
      if ($(e.target).hasClass('scpwoo-modal-overlay')) $overlay.remove();
    });

    // Close on Escape
    $(document).on('keydown.scpwoo-modal', function (e) {
      if (e.key === 'Escape') { $overlay.remove(); $(document).off('keydown.scpwoo-modal'); }
    });

    // Confirm
    $overlay.on('click', '.scpwoo-modal-confirm', function () {
      $overlay.remove();
      $(document).off('keydown.scpwoo-modal');
      if (typeof onConfirm === 'function') onConfirm();
    });
  }

  // =========================================================================
  // Accordion: Regions
  // =========================================================================

  $(document).on('click', '.scpwoo-region-header', function () {
    var $header = $(this);
    var $region = $header.closest('.scpwoo-region');
    var $body = $region.find('.scpwoo-region-body');
    var $icon = $header.find('.scpwoo-toggle-icon');
    var regionCode = $region.data('region');

    if ($body.is(':visible')) {
      $body.slideUp(200);
      $icon.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-right-alt2');
      $header.attr('aria-expanded', 'false');
    } else {
      $body.removeClass('scpwoo-hidden').slideDown(200);
      $icon.removeClass('dashicons-arrow-right-alt2').addClass('dashicons-arrow-down-alt2');
      $header.attr('aria-expanded', 'true');

      var countryCode = $region.data('country') || '';
      var cacheKey = countryCode + ':' + regionCode;
      if (!loadedRegions[cacheKey]) {
        loadRegionData(regionCode, countryCode, $body);
      }
    }
  });

  // Keyboard support for accordions (Enter/Space)
  $(document).on('keydown', '.scpwoo-region-header, .scpwoo-rz-region-header', function(e) {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      $(this).trigger('click');
    }
  });

  // =========================================================================
  // Accordion: Cities (neighborhoods)
  // =========================================================================

  $(document).on('click', '.scpwoo-city-header', function (e) {
    if ($(e.target).hasClass('scpwoo-delete-city') || $(e.target).closest('.scpwoo-delete-city').length) {
      return; // Don't toggle if clicking delete
    }
    var $city = $(this).closest('.scpwoo-city');
    var $neighborhoods = $city.find('.scpwoo-neighborhoods');
    var $icon = $(this).find('.scpwoo-toggle-icon');

    if ($neighborhoods.is(':visible')) {
      $neighborhoods.slideUp(150);
      $icon.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-right-alt2');
    } else {
      $neighborhoods.removeClass('scpwoo-hidden').slideDown(150);
      $icon.removeClass('dashicons-arrow-right-alt2').addClass('dashicons-arrow-down-alt2');
    }
  });

  // =========================================================================
  // Load region data via AJAX
  // =========================================================================

  function loadRegionData(regionCode, countryCode, $body) {
    $body.html(
        '<div class="scpwoo-skeleton scpwoo-skeleton-line-full"></div>' +
        '<div class="scpwoo-skeleton scpwoo-skeleton-line"></div>' +
        '<div class="scpwoo-skeleton scpwoo-skeleton-line-short"></div>' +
        '<div class="scpwoo-skeleton scpwoo-skeleton-line"></div>'
    );

    $.post(params.ajax_url, {
      action: 'scpwoo_get_region_data',
      nonce: params.nonce,
      region_code: regionCode,
      country_code: countryCode
    }, function (response) {
      if (response.success) {
        loadedRegions[countryCode + ':' + regionCode] = true;
        renderRegionBody(regionCode, countryCode, response.data.cities, $body);
      } else {
        $body.html('<p class="scpwoo-error">' + params.i18n.error + '</p>');
      }
    }).fail(function () {
      $body.html('<p class="scpwoo-error">' + params.i18n.error + '</p>');
    });
  }

  // =========================================================================
  // Render region content
  // =========================================================================

  function renderRegionBody(regionCode, countryCode, cities, $body) {
    var html = '';

    html += '<div class="scpwoo-add-form">';
    html += '<input type="text" class="scpwoo-new-city regular-text" placeholder="' + escapeAttr(params.i18n.city_name_placeholder || 'City name') + '" />';
    html += '<button class="button button-primary button-small scpwoo-add-city-btn" data-region="' + regionCode + '" data-country="' + escapeAttr(countryCode) + '">' + escapeHtml(params.i18n.add_city_btn || '+ Add a city') + '</button>';
    html += '</div>';

    html += '<div class="scpwoo-cities-list">';
    for (var i = 0; i < cities.length; i++) {
      html += renderCity(regionCode, countryCode, cities[i]);
    }
    html += '</div>';

    $body.html(html);
  }

  function renderCity(regionCode, countryCode, city) {
    var badgeClass = city.source === 'custom' ? 'scpwoo-badge-custom' : 'scpwoo-badge-default';
    var badgeText = city.source === 'custom' ? (params.i18n.badge_custom || 'custom') : (params.i18n.badge_default || 'default');
    var hoodCount = city.neighborhoods ? city.neighborhoods.length : 0;

    var html = '<div class="scpwoo-city" data-city="' + escapeAttr(city.name) + '" data-region="' + regionCode + '" data-country="' + escapeAttr(countryCode) + '">';
    html += '<div class="scpwoo-city-header">';
    html += '<span class="dashicons dashicons-arrow-right-alt2 scpwoo-toggle-icon"></span>';
    html += '<strong>' + escapeHtml(city.name) + '</strong>';
    html += '<span class="scpwoo-badge ' + badgeClass + '">' + badgeText + '</span>';
    html += '<span class="scpwoo-hood-count">(' + hoodCount + ' ' + escapeHtml(params.i18n.neighborhoods_count || 'neighborhoods') + ')</span>';
    html += '<button class="button-link-delete scpwoo-delete-city" aria-label="' + escapeAttr((params.i18n.delete || 'Delete') + ' ' + city.name) + '">&times;</button>';
    html += '</div>';

    html += '<div class="scpwoo-neighborhoods scpwoo-hidden">';
    html += '<div class="scpwoo-add-form scpwoo-add-form-sm">';
    html += '<input type="text" class="scpwoo-new-neighborhood" placeholder="' + escapeAttr(params.i18n.neighborhood_placeholder || 'Neighborhood name') + '" />';
    html += '<button class="button button-small scpwoo-add-neighborhood-btn" data-city="' + escapeAttr(city.name) + '" data-country="' + escapeAttr(countryCode) + '">' + escapeHtml(params.i18n.add_neighborhood_btn || '+ Add') + '</button>';
    html += '</div>';

    html += '<ul class="scpwoo-neighborhoods-list">';
    if (city.neighborhoods) {
      for (var j = 0; j < city.neighborhoods.length; j++) {
        html += renderNeighborhood(city.name, city.neighborhoods[j]);
      }
    }
    html += '</ul>';
    html += '</div>';

    html += '</div>';
    return html;
  }

  function renderNeighborhood(cityName, hood) {
    var badgeClass = hood.source === 'custom' ? 'scpwoo-badge-custom' : 'scpwoo-badge-default';
    var badgeText = hood.source === 'custom' ? (params.i18n.badge_custom || 'custom') : (params.i18n.badge_default || 'default');

    var html = '<li data-neighborhood="' + escapeAttr(hood.name) + '" data-city="' + escapeAttr(cityName) + '">';
    html += '<span class="scpwoo-hood-name">' + escapeHtml(hood.name) + '</span>';
    html += '<span class="scpwoo-badge ' + badgeClass + '">' + badgeText + '</span>';
    html += '<button class="button-link-delete scpwoo-delete-neighborhood" aria-label="' + escapeAttr((params.i18n.delete || 'Delete') + ' ' + hood.name) + '">&times;</button>';
    html += '</li>';
    return html;
  }

  // =========================================================================
  // Add a city
  // =========================================================================

  $(document).on('click', '.scpwoo-add-city-btn', function () {
    var $btn = $(this);
    var regionCode = $btn.data('region');
    var countryCode = $btn.data('country') || $btn.closest('.scpwoo-region').data('country') || '';
    var $input = $btn.siblings('.scpwoo-new-city');
    var cityName = $.trim($input.val());

    if (!cityName) {
      showNotice(params.i18n.empty_name, 'error');
      return;
    }

    $btn.prop('disabled', true).addClass('updating-message');

    $.post(params.ajax_url, {
      action: 'scpwoo_add_city',
      nonce: params.nonce_write,
      region_code: regionCode,
      country_code: countryCode,
      city_name: cityName
    }, function (response) {
      $btn.prop('disabled', false).removeClass('updating-message');
      if (response.success) {
        showNotice(params.i18n.city_added, 'success');
        $input.val('');
        var cacheKey = countryCode + ':' + regionCode;
        loadedRegions[cacheKey] = false;
        var $body = $btn.closest('.scpwoo-region-body');
        loadRegionData(regionCode, countryCode, $body);
        updateRegionCount(regionCode, countryCode, 1);
      } else {
        showNotice(response.data.message || params.i18n.error, 'error');
      }
    }).fail(function () {
      $btn.prop('disabled', false).removeClass('updating-message');
      showNotice(params.i18n.error, 'error');
    });
  });

  // Enter key to add a city
  $(document).on('keypress', '.scpwoo-new-city', function (e) {
    if (e.which === 13) {
      e.preventDefault();
      $(this).siblings('.scpwoo-add-city-btn').click();
    }
  });

  // =========================================================================
  // Delete a city
  // =========================================================================

  $(document).on('click', '.scpwoo-delete-city', function (e) {
    e.stopPropagation();
    var $city = $(this).closest('.scpwoo-city');
    var cityName = $city.data('city');
    var regionCode = $city.data('region');
    var countryCode = $city.data('country') || $city.closest('.scpwoo-region').data('country') || '';

    showConfirm(params.i18n.confirm_delete_city, function () {
      $.post(params.ajax_url, {
        action: 'scpwoo_delete_city',
        nonce: params.nonce_write,
        region_code: regionCode,
        country_code: countryCode,
        city_name: cityName
      }, function (response) {
        if (response.success) {
          showNotice(params.i18n.city_deleted, 'success');
          $city.fadeOut(200, function () { $(this).remove(); });
          updateRegionCount(regionCode, countryCode, -1);
        } else {
          showNotice(response.data.message || params.i18n.error, 'error');
        }
      }).fail(function () {
        showNotice(params.i18n.error, 'error');
      });
    }, { title: cityName });
  });

  // =========================================================================
  // Add a neighborhood
  // =========================================================================

  $(document).on('click', '.scpwoo-add-neighborhood-btn', function () {
    var $btn = $(this);
    var cityName = $btn.data('city');
    var $input = $btn.siblings('.scpwoo-new-neighborhood');
    var neighborhoodName = $.trim($input.val());

    if (!neighborhoodName) {
      showNotice(params.i18n.empty_name, 'error');
      return;
    }

    $btn.prop('disabled', true).addClass('updating-message');

    var countryCode = $btn.data('country') || $btn.closest('.scpwoo-city').data('country') || '';

    $.post(params.ajax_url, {
      action: 'scpwoo_add_neighborhood',
      nonce: params.nonce_write,
      city_name: cityName,
      country_code: countryCode,
      neighborhood_name: neighborhoodName
    }, function (response) {
      $btn.prop('disabled', false).removeClass('updating-message');
      if (response.success) {
        showNotice(params.i18n.neighborhood_added, 'success');
        $input.val('');
        var $list = $btn.closest('.scpwoo-neighborhoods').find('.scpwoo-neighborhoods-list');
        var hood = { name: neighborhoodName, source: response.data.source || 'custom' };
        $list.append(renderNeighborhood(cityName, hood));
        var $city = $btn.closest('.scpwoo-city');
        var $count = $city.find('.scpwoo-hood-count');
        var current = parseInt($count.text().match(/\d+/)) || 0;
        $count.text('(' + (current + 1) + ' ' + (params.i18n.neighborhoods_count || 'neighborhoods') + ')');
      } else {
        showNotice(response.data.message || params.i18n.error, 'error');
      }
    }).fail(function () {
      $btn.prop('disabled', false).removeClass('updating-message');
      showNotice(params.i18n.error, 'error');
    });
  });

  // Enter key to add a neighborhood
  $(document).on('keypress', '.scpwoo-new-neighborhood', function (e) {
    if (e.which === 13) {
      e.preventDefault();
      $(this).siblings('.scpwoo-add-neighborhood-btn').click();
    }
  });

  // =========================================================================
  // Delete a neighborhood
  // =========================================================================

  $(document).on('click', '.scpwoo-delete-neighborhood', function (e) {
    e.stopPropagation();
    var $li = $(this).closest('li');
    var neighborhoodName = $li.data('neighborhood');
    var cityName = $li.data('city');
    var countryCode = $li.closest('.scpwoo-city').data('country') || '';

    showConfirm(params.i18n.confirm_delete_neighborhood, function () {
      $.post(params.ajax_url, {
        action: 'scpwoo_delete_neighborhood',
        nonce: params.nonce_write,
        city_name: cityName,
        country_code: countryCode,
        neighborhood_name: neighborhoodName
      }, function (response) {
        if (response.success) {
          showNotice(params.i18n.neighborhood_deleted, 'success');
          var $city = $li.closest('.scpwoo-city');
          var $count = $city.find('.scpwoo-hood-count');
          var current = parseInt($count.text().match(/\d+/)) || 0;
          $count.text('(' + Math.max(0, current - 1) + ' ' + (params.i18n.neighborhoods_count || 'neighborhoods') + ')');
          $li.fadeOut(200, function () { $(this).remove(); });
        } else {
          showNotice(response.data.message || params.i18n.error, 'error');
        }
      }).fail(function () {
        showNotice(params.i18n.error, 'error');
      });
    }, { title: neighborhoodName });
  });

  // =========================================================================
  // Helpers
  // =========================================================================

  function updateRegionCount(regionCode, countryCode, delta) {
    var selector = '.scpwoo-region[data-region="' + regionCode + '"]';
    if (countryCode) {
      selector += '[data-country="' + countryCode + '"]';
    }
    var $region = $(selector);
    var $count = $region.find('.scpwoo-count');
    var current = parseInt($count.text()) || 0;
    var newCount = Math.max(0, current + delta);
    $count.text(newCount + ' ' + (params.i18n.cities_count || 'cities'));
  }

  // =========================================================================
  // Save settings (delegated for AJAX tab loading)
  // =========================================================================

  $(document).on('click', '#scpwoo-save-settings', function () {
    var $btn = $(this);
    $btn.prop('disabled', true).addClass('updating-message');

    $.post(params.ajax_url, {
      action: 'scpwoo_save_settings',
      nonce: params.nonce_write,
      address_validation_enabled: $('#scpwoo-address_validation_enabled').is(':checked') ? 'yes' : 'no',
      landmark_enabled: $('#scpwoo-landmark_enabled').is(':checked') ? 'yes' : 'no',
      smart_search_enabled: $('#scpwoo-smart_search_enabled').is(':checked') ? 'yes' : 'no',
      smart_search_accent: $('#scpwoo-smart_search_accent').val(),
      smart_search_bg: $('#scpwoo-smart_search_bg').val(),
      smart_search_border: $('#scpwoo-smart_search_border').val(),
      api_enabled: $('#scpwoo-api_enabled').is(':checked') ? 'yes' : 'no'
    }, function (response) {
      $btn.prop('disabled', false).removeClass('updating-message');
      if (response.success) {
        hasUnsavedChanges = false;
        showNotice(response.data.message, 'success');
      } else {
        showNotice(params.i18n.error, 'error');
      }
    }).fail(function () {
      $btn.prop('disabled', false).removeClass('updating-message');
      showNotice(params.i18n.error, 'error');
    });
  });

  // =========================================================================
  // Smart Search color picker — live hex preview + reset
  // =========================================================================

  $(document).on('input change', '.scpwoo-color-picker', function () {
    $(this).closest('.scpwoo-settings-row').find('.scpwoo-settings-row-desc code').text($(this).val());
  });

  $(document).on('click', '#scpwoo-reset-colors', function () {
    $('#scpwoo-smart_search_accent').val('#4a90d9').trigger('change');
    $('#scpwoo-smart_search_bg').val('#f0f7ff').trigger('change');
    $('#scpwoo-smart_search_border').val('#d0e3f0').trigger('change');
  });

  // =========================================================================
  // Save zone restrictions (delegated)
  // =========================================================================

  $(document).on('click', '#scpwoo-save-restrictions', function () {
    var $btn = $(this);
    $btn.prop('disabled', true).addClass('updating-message');

    var restrictedRegions = [];
    $('input[name="restricted_regions[]"]:checked').each(function () {
      restrictedRegions.push($(this).val());
    });

    var restrictedCities = [];
    $('input[name="restricted_cities[]"]:checked').each(function () {
      restrictedCities.push($(this).val());
    });

    $.post(params.ajax_url, {
      action: 'scpwoo_save_restrictions',
      nonce: params.nonce_write,
      enabled: $('#scpwoo-restrictions-enabled').is(':checked') ? 'yes' : 'no',
      message: $('#scpwoo-restriction-message').val(),
      restricted_regions: restrictedRegions,
      restricted_cities: restrictedCities
    }, function (response) {
      $btn.prop('disabled', false).removeClass('updating-message');
      if (response.success) {
        hasUnsavedChanges = false;
        showNotice(response.data.message, 'success');
      } else {
        showNotice(params.i18n.error, 'error');
      }
    }).fail(function () {
      $btn.prop('disabled', false).removeClass('updating-message');
      showNotice(params.i18n.error, 'error');
    });
  });

  // =========================================================================
  // Restrictions — Accordion, cascade, search, badges
  // (moved from inline <script> in class-page-restrictions.php)
  // =========================================================================

  // Accordion toggle
  $(document).on('click', '.scpwoo-rz-region-header', function (e) {
    if ($(e.target).is('input')) return;
    var $region = $(this).closest('.scpwoo-rz-region');
    var $cities = $region.find('.scpwoo-rz-cities');
    var isOpen = $region.hasClass('open');
    $region.toggleClass('open', !isOpen);
    $region.find('.scpwoo-rz-region-header').attr('aria-expanded', !isOpen ? 'true' : 'false');
    $cities.removeClass('scpwoo-hidden').slideToggle(150);
  });

  // Region checkbox → cascade to cities
  $(document).on('change', 'input[name="restricted_regions[]"]', function () {
    var $region = $(this).closest('.scpwoo-rz-region');
    var checked = $(this).is(':checked');

    $region.toggleClass('scpwoo-rz-blocked', checked);
    $region.find('.scpwoo-rz-cities-grid').css({ opacity: checked ? 0.5 : 1, pointerEvents: checked ? 'none' : 'auto' });
    $region.find('input[name="restricted_cities[]"]').prop('checked', checked).prop('disabled', checked);

    var $msg = $region.find('.scpwoo-rz-blocked-msg');
    if (checked && !$msg.length) {
      $region.find('.scpwoo-rz-cities').prepend('<p class="scpwoo-rz-blocked-msg">' + escapeHtml(params.i18n.entire_region_blocked) + '</p>');
    } else if (!checked) {
      $msg.remove();
    }

    updateRZBadge($region);
  });

  // City checkbox change → update badge
  $(document).on('change', 'input[name="restricted_cities[]"]', function () {
    updateRZBadge($(this).closest('.scpwoo-rz-region'));
  });

  function updateRZBadge($region) {
    var isRegionBlocked = $region.find('input[name="restricted_regions[]"]').is(':checked');
    var totalCities = $region.find('input[name="restricted_cities[]"]').length;
    var checkedCities = $region.find('input[name="restricted_cities[]"]:checked').length;
    var $badge = $region.find('.scpwoo-badge');

    if (isRegionBlocked) {
      $badge.attr('class', 'scpwoo-badge scpwoo-badge-error').text(params.i18n.blocked);
    } else if (checkedCities > 0) {
      $badge.attr('class', 'scpwoo-badge scpwoo-badge-warning').text(checkedCities + ' / ' + totalCities);
    } else {
      $badge.attr('class', 'scpwoo-badge scpwoo-badge-default').text('0 / ' + totalCities);
    }
  }

  // Search restrictions
  $(document).on('input', '#scpwoo-rz-search', function () {
    clearTimeout(rzSearchTimer);
    var query = $(this).val().toLowerCase().trim();
    rzSearchTimer = setTimeout(function () {
      if (!query) {
        $('.scpwoo-rz-region').show();
        $('.scpwoo-rz-city').show().removeClass('scpwoo-rz-highlight');
        $('.scpwoo-rz-country-group').show();
        return;
      }
      $('.scpwoo-rz-region').each(function () {
        var $r = $(this);
        var regionName = $r.find('strong').text().toLowerCase();
        var regionMatch = regionName.indexOf(query) !== -1;
        var cityMatch = false;

        $r.find('.scpwoo-rz-city').each(function () {
          var cn = $(this).data('city');
          if (cn && cn.indexOf(query) !== -1) {
            $(this).show().addClass('scpwoo-rz-highlight');
            cityMatch = true;
          } else {
            $(this).show().removeClass('scpwoo-rz-highlight');
          }
        });

        if (regionMatch || cityMatch) {
          $r.show();
          if (cityMatch && !$r.hasClass('open')) {
            $r.addClass('open').find('.scpwoo-rz-cities').removeClass('scpwoo-hidden').show();
          }
        } else {
          $r.hide();
        }
      });
    }, 200);
  });

  // =========================================================================
  // Geodata search — filter regions by name
  // =========================================================================

  var geodataSearchTimer;
  $(document).on('input', '#scpwoo-geodata-search', function () {
      clearTimeout(geodataSearchTimer);
      var query = $(this).val().toLowerCase().trim();
      geodataSearchTimer = setTimeout(function () {
          if (!query) {
              $('.scpwoo-region').show();
              $('.scpwoo-country-group').show();
              return;
          }
          $('.scpwoo-region').each(function () {
              var $r = $(this);
              var regionName = $r.find('.scpwoo-region-header strong').text().toLowerCase();
              var regionCode = $r.data('region').toString().toLowerCase();
              $r.toggle(regionName.indexOf(query) !== -1 || regionCode.indexOf(query) !== -1);
          });
          // Show/hide country groups that have visible regions
          $('.scpwoo-country-group').each(function () {
              var hasVisible = $(this).find('.scpwoo-region:visible').length > 0;
              $(this).toggle(hasVisible);
          });
      }, 200);
  });

  // =========================================================================
  // Country filter (generic — used by Geodata & Restrictions)
  // (moved from inline <script> blocks)
  // =========================================================================

  function initCountryFilters() {
    $('.scpwoo-country-filter').each(function () {
      var $filter = $(this);
      var $select = $filter.find('.scpwoo-country-select');
      if (!$select.length) return;

      var storageKey = $filter.data('storage-key');
      var targetSelector = $filter.data('target');
      var matchMode = $filter.data('match'); // "data-country" or "heading"

      if (!storageKey || !targetSelector) return;

      // Restore saved value
      var saved = localStorage.getItem(storageKey) || '';
      if (saved) $select.val(saved);

      function doFilter() {
        var cc = $select.val();
        localStorage.setItem(storageKey, cc);

        if (!cc) {
          $(targetSelector).show();
          return;
        }

        $(targetSelector).each(function () {
          var $group = $(this);
          var match;
          if (matchMode === 'heading') {
            var heading = $group.find('.scpwoo-rz-country-heading').text().trim();
            var selectedName = $select.find('option:selected').text().trim();
            match = heading === selectedName;
          } else {
            match = $group.find('.scpwoo-region[data-country="' + cc + '"]').length > 0;
          }
          $group.toggle(match);
        });
      }

      $select.on('change', doFilter);
      doFilter();
    });
  }

  initCountryFilters();

  // =========================================================================
  // Stats leaderboard — accordion, search, sort, show more
  // =========================================================================

  $(document).on('click', '.scpwoo-lb-region', function (e) {
    if ($(e.target).is('input, a, button')) return;
    var $row = $(this);
    var isOpen = $row.hasClass('scpwoo-lb-open');
    var $toggle = $row.find('.scpwoo-lb-toggle');
    $row.toggleClass('scpwoo-lb-open', !isOpen);
    $row.nextUntil('.scpwoo-lb-region').filter('.scpwoo-city-row').toggleClass('scpwoo-lb-collapsed', isOpen);
    $toggle.attr('aria-expanded', !isOpen ? 'true' : 'false');
  });

  $(document).on('keydown', '.scpwoo-lb-toggle', function (e) {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      e.stopPropagation();
      $(this).closest('.scpwoo-lb-region').trigger('click');
    }
  });

  // Search — filter regions and cities (handles overflow correctly)
  var lbSearchTimer;
  $(document).on('input', '#scpwoo-lb-search', function () {
    clearTimeout(lbSearchTimer);
    var query = $(this).val().toLowerCase().trim();
    lbSearchTimer = setTimeout(function () {
      var $table = $('#scpwoo-stats-table');
      if (!$table.length) return;
      var $regions = $table.find('.scpwoo-lb-region');
      var $cities  = $table.find('.scpwoo-city-row');

      if (!query) {
        // Reset: show regions, collapse cities, respect overflow
        $regions.show().removeClass('scpwoo-lb-open');
        $cities.addClass('scpwoo-lb-collapsed');
        // Restore overflow visibility
        if (!$('#scpwoo-leaderboard').hasClass('scpwoo-lb-show-all-visible')) {
          $regions.filter('.scpwoo-lb-overflow').hide();
          $cities.filter('.scpwoo-lb-overflow').hide();
        }
        return;
      }

      // During search, temporarily show all rows (ignore overflow limit)
      $regions.each(function () {
        var $region = $(this);
        var regionName = $region.data('name') || '';
        var regionMatch = regionName.indexOf(query) !== -1;
        var cityMatch = false;

        $region.nextUntil('.scpwoo-lb-region').filter('.scpwoo-city-row').each(function () {
          var cn = $(this).data('name') || '';
          if (cn.indexOf(query) !== -1) {
            $(this).removeClass('scpwoo-lb-collapsed');
            cityMatch = true;
          } else {
            $(this).addClass('scpwoo-lb-collapsed');
          }
        });

        if (regionMatch || cityMatch) {
          $region.show();
          if (cityMatch) $region.addClass('scpwoo-lb-open');
          else $region.removeClass('scpwoo-lb-open');
        } else {
          $region.hide();
          $region.nextUntil('.scpwoo-lb-region').filter('.scpwoo-city-row').addClass('scpwoo-lb-collapsed');
        }
      });
    }, 200);
  });

  $(document).on('keydown', '.scpwoo-sortable', function (e) {
    if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $(this).trigger('click'); }
  });

  $(document).on('click', '.scpwoo-sortable', function () {
    var $th = $(this);
    var sortKey = $th.data('sort');
    var $table = $th.closest('table');
    var $tbody = $table.find('tbody');
    var isAsc = $th.hasClass('scpwoo-sort-asc');

    $table.find('.scpwoo-sortable').removeClass('scpwoo-sort-active scpwoo-sort-asc scpwoo-sort-desc').attr('aria-sort', 'none');
    $th.addClass('scpwoo-sort-active ' + (isAsc ? 'scpwoo-sort-desc' : 'scpwoo-sort-asc'))
       .attr('aria-sort', isAsc ? 'descending' : 'ascending');

    // Collect region groups
    var groups = [];
    $tbody.find('.scpwoo-lb-region').each(function () {
      var $region = $(this);
      var $cities = $region.nextUntil('.scpwoo-lb-region').filter('.scpwoo-city-row');
      groups.push({ $region: $region, $cities: $cities, val: parseFloat($region.data(sortKey)) || 0 });
    });

    groups.sort(function (a, b) {
      return isAsc ? a.val - b.val : b.val - a.val;
    });

    // Re-append in order, update ranks and medals
    var rank = 0;
    var medals = ['', 'scpwoo-medal-gold', 'scpwoo-medal-silver', 'scpwoo-medal-bronze'];
    groups.forEach(function (g) {
      rank++;
      $tbody.append(g.$region);
      $tbody.append(g.$cities);
      var $rankCell = g.$region.find('.scpwoo-rank-cell');
      if (rank <= 3) {
        $rankCell.html('<span class="scpwoo-medal ' + medals[rank] + '">' + rank + '</span>');
      } else {
        $rankCell.html('<span class="scpwoo-rank">' + rank + '</span>');
      }
    });
  });

  // Show all — toggle overflow rows (not remove)
  $(document).on('click', '#scpwoo-lb-show-all', function () {
    var $lb = $('#scpwoo-leaderboard');
    var isVisible = $lb.hasClass('scpwoo-lb-show-all-visible');
    $lb.toggleClass('scpwoo-lb-show-all-visible', !isVisible);
    $(this).text(isVisible ? $(this).data('label-show') : $(this).data('label-hide'));
  });

  // =========================================================================
  // CSV export (moved from inline <script> in class-page-stats.php)
  // =========================================================================

  $(document).on('click', '#scpwoo-export-csv', function () {
    var rows = [], sep = ',';
    var $table = $('#scpwoo-stats-table');
    if (!$table.length) return;
    var header = [];
    $table.find('thead th').each(function () { header.push('"' + $(this).text().trim() + '"'); });
    rows.push(header.join(sep));
    $table.find('tbody tr').each(function () {
      var cols = [];
      $(this).find('td').each(function () {
        var txt = $(this).text().trim().replace(/"/g, '""');
        cols.push('"' + txt + '"');
      });
      rows.push(cols.join(sep));
    });
    var csv = '\uFEFF' + rows.join('\n');
    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'afriregions-stats-' + new Date().toISOString().slice(0, 10) + '.csv';
    a.click();
    URL.revokeObjectURL(url);
  });

  // =========================================================================
  // Import CSV (delegated)
  // =========================================================================

  $(document).on('change', '#scpwoo-import-file', function () {
    $('#scpwoo-import-btn').prop('disabled', !this.files.length);
  });

  $(document).on('click', '#scpwoo-import-btn', function () {
    var $btn = $(this);
    var fileInput = $('#scpwoo-import-file')[0];

    if (!fileInput.files.length) return;

    var formData = new FormData();
    formData.append('action', 'scpwoo_import_csv');
    formData.append('nonce', params.nonce_write);
    formData.append('csv_file', fileInput.files[0]);

    $btn.prop('disabled', true).addClass('updating-message');
    $('#scpwoo-import-progress').show();
    $('#scpwoo-import-results').hide().empty();

    $.ajax({
      url: params.ajax_url,
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function (response) {
        $btn.prop('disabled', false).removeClass('updating-message');
        $('#scpwoo-import-progress').hide();

        if (response.success) {
          showNotice(response.data.message, 'success');

          if (response.data.errors && response.data.errors.length > 0) {
            var errHtml = '<div class="scpwoo-card scpwoo-card-warning"><div class="scpwoo-card-body"><strong>Warnings:</strong><ul>';
            for (var i = 0; i < response.data.errors.length; i++) {
              errHtml += '<li>' + escapeHtml(response.data.errors[i]) + '</li>';
            }
            errHtml += '</ul></div></div>';
            $('#scpwoo-import-results').html(errHtml).show();
          }

          fileInput.value = '';
          $btn.prop('disabled', true);
        } else {
          showNotice(response.data.message || params.i18n.error, 'error');
        }
      },
      error: function () {
        $btn.prop('disabled', false).removeClass('updating-message');
        $('#scpwoo-import-progress').hide();
        showNotice(params.i18n.error, 'error');
      }
    });
  });

  // =========================================================================
  // Purge audit log
  // =========================================================================

  $(document).on('click', '#scpwoo-purge-audit-log', function () {
    var $btn = $(this);
    showConfirm(params.i18n.confirm_purge_log || 'Clear all activity history? This cannot be undone.', function () {
      $btn.prop('disabled', true).addClass('updating-message');
      $.post(params.ajax_url, {
        action: 'scpwoo_purge_audit_log',
        nonce: params.nonce_write
      }, function (response) {
        $btn.prop('disabled', false).removeClass('updating-message');
        if (response.success) {
          showNotice(response.data.message, 'success');
          var $tab = $('.scpwoo-tabs .nav-tab-active');
          if ($tab.length) $tab.trigger('click');
        } else {
          showNotice(params.i18n.error, 'error');
        }
      }).fail(function () {
        $btn.prop('disabled', false).removeClass('updating-message');
        showNotice(params.i18n.error, 'error');
      });
    });
  });

  // =========================================================================
  // Helpers
  // =========================================================================

  function escapeHtml(str) {
    if (!str) return '';
    return $('<span>').text(str).html();
  }

  function escapeAttr(str) {
    if (!str) return '';
    return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
});
