(function () {
  'use strict';

  var cfg = window.CUSTAUSU_ADMIN_CLEAN_REFERER || {};

  function cleanSettingsReferer() {
    var form = document.querySelector('form[action="options.php"]');
    if (!form) return;

    var ref = form.querySelector('input[name="_wp_http_referer"]');
    if (!ref) return;

    var clean = cfg.clean_url || '';
    if (!clean) return;

    ref.value = clean;
    ref.defaultValue = clean;
  }

  document.addEventListener('submit', function (ev) {
    var form = ev.target;
    if (!form || !form.matches || !form.matches('form[action="options.php"]')) return;
    cleanSettingsReferer();
  }, true);

  document.addEventListener('click', function (ev) {
    var btn = ev.target && ev.target.closest
      ? ev.target.closest('.custausu-save-settings-btn--floating')
      : null;

    if (!btn) return;
    cleanSettingsReferer();
  }, true);
})();