(function () {
  "use strict";

  function findFirewallForm(field) {
    if (field.closest) {
      return field.closest(".pdt-firewall-form");
    }

    var node = field.parentNode;
    while (node) {
      if (node.className && String(node.className).indexOf("pdt-firewall-form") !== -1) {
        return node;
      }
      node = node.parentNode;
    }

    return null;
  }

  function getFirewallKey(field) {
    if (!field || !field.name) {
      return "";
    }

    var match = field.name.match(/^pdt_firewall\[([^\]]+)\]/);
    return match ? match[1] : "";
  }

  function hasTouchedInput(form, key) {
    var inputs = form.querySelectorAll('input[name="pdt_firewall_touched[]"]');
    var index;

    for (index = 0; index < inputs.length; index += 1) {
      if (inputs[index].value === key) {
        return true;
      }
    }

    return false;
  }

  function markTouched(event) {
    var field = event.target;
    var key = getFirewallKey(field);
    var form;
    var hidden;

    if (!key || key === "mode") {
      return;
    }

    form = findFirewallForm(field);
    if (!form || hasTouchedInput(form, key)) {
      return;
    }

    hidden = document.createElement("input");
    hidden.type = "hidden";
    hidden.name = "pdt_firewall_touched[]";
    hidden.value = key;
    form.appendChild(hidden);
  }

  document.addEventListener("change", markTouched, true);
  document.addEventListener("input", markTouched, true);

  function getModeProfiles() {
    if (!window.PDTFirewallAdmin || !window.PDTFirewallAdmin.modeProfiles) {
      return {};
    }

    return window.PDTFirewallAdmin.modeProfiles;
  }

  function setFieldValue(field, value) {
    if (!field) {
      return;
    }

    if (field.type === "checkbox") {
      field.checked = !!value;
      return;
    }

    if (field.type === "radio") {
      field.checked = field.value === String(value);
      return;
    }

    field.value = value === null || typeof value === "undefined" ? "" : String(value);
  }

  function applyModeProfile(form, mode) {
    var profiles = getModeProfiles();
    var profile = profiles[mode];
    var key;
    var fields;
    var index;

    if (!form || !profile) {
      return;
    }

    for (key in profile) {
      if (!Object.prototype.hasOwnProperty.call(profile, key) || hasTouchedInput(form, key)) {
        continue;
      }

      fields = form.querySelectorAll('[name="pdt_firewall[' + key + ']"]');
      for (index = 0; index < fields.length; index += 1) {
        setFieldValue(fields[index], profile[key]);
      }
    }
  }

  function handleModeChange(event) {
    var field = event.target;
    var form;

    if (getFirewallKey(field) !== "mode" || !field.checked) {
      return;
    }

    form = findFirewallForm(field);
    applyModeProfile(form, field.value);
  }

  document.addEventListener("change", handleModeChange, true);

  function openModal(modal) {
    var firstField;

    if (!modal) {
      return;
    }

    modal.hidden = false;
    document.documentElement.classList.add("pdt-firewall-modal-open");

    firstField = modal.querySelector("input, button, select, textarea, a[href]");
    if (firstField && firstField.focus) {
      firstField.focus();
    }
  }

  function closeModal(modal) {
    if (!modal) {
      return;
    }

    modal.hidden = true;
    document.documentElement.classList.remove("pdt-firewall-modal-open");
  }

  document.addEventListener("click", function (event) {
    var opener = event.target.closest("[data-pdt-firewall-modal-open]");
    var closer = event.target.closest("[data-pdt-firewall-modal-close]");
    var modal;

    if (opener) {
      modal = document.getElementById(opener.getAttribute("data-pdt-firewall-modal-open"));
      openModal(modal);
      event.preventDefault();
      return;
    }

    if (closer) {
      modal = closer.closest(".pdt-firewall-modal");
      closeModal(modal);
      event.preventDefault();
    }
  });

  document.addEventListener("keydown", function (event) {
    var modal;

    if (event.key !== "Escape") {
      return;
    }

    modal = document.querySelector(".pdt-firewall-modal:not([hidden])");
    closeModal(modal);
  });

  function updateLoadMoreButton(button) {
    var card = button.closest(".pdt-firewall-events");
    var hiddenRows = card ? card.querySelectorAll(".pdt-firewall-event-row.is-hidden") : [];
    var doneLabel = button.getAttribute("data-label-done") || "No more events";

    if (!hiddenRows.length) {
      button.disabled = true;
      button.textContent = doneLabel;
    }
  }

  document.addEventListener("click", function (event) {
    var button = event.target.closest(".pdt-firewall-load-more");
    var card;
    var hiddenRows;
    var batchSize;
    var index;

    if (!button) {
      return;
    }

    card = button.closest(".pdt-firewall-events");
    hiddenRows = card ? card.querySelectorAll(".pdt-firewall-event-row.is-hidden") : [];
    batchSize = parseInt(button.getAttribute("data-batch-size"), 10) || 20;

    for (index = 0; index < hiddenRows.length && index < batchSize; index += 1) {
      hiddenRows[index].classList.remove("is-hidden");
    }

    updateLoadMoreButton(button);
    event.preventDefault();
  });

  document.querySelectorAll(".pdt-firewall-load-more").forEach(updateLoadMoreButton);
}());
