(function ($) {
  "use strict";

  var state = {
    selectingType: "",
    lastSelector: null,
    lastTargetLabel: "",
    panelOpen: false
  };

  function getData() {
    return window.polangerShieldBuilder || {};
  }

  function getI18n(key, fallback) {
    var data = getData();
    if (data.i18n && data.i18n[key]) {
      return data.i18n[key];
    }
    return fallback;
  }

  function renderUserCheckboxes(name) {
    var data = getData();
    var users = data.users || [];
    if (!users.length) {
      return "<p>" + getI18n("selectUsers", "Select users") + "</p>";
    }

    return users.map(function (user) {
      return (
        '<label class="polanger-shield-user-item">' +
        '<input type="checkbox" name="' + name + '" value="' + user.id + '" /> ' +
        $("<div>").text(user.label).html() +
        "</label>"
      );
    }).join("");
  }

  function getTargetLabel(el, selectorData) {
    if (!el) {
      return (selectorData && selectorData.selector) ? selectorData.selector : "";
    }

    var rawText = ($(el).text() || "").replace(/\s+/g, " ").trim();
    if (rawText.length > 70) {
      rawText = rawText.slice(0, 70) + "...";
    }

    var ariaLabel = ($(el).attr("aria-label") || $(el).attr("title") || $(el).attr("name") || "").trim();
    var id = ($(el).attr("id") || "").trim();
    var tag = (el.tagName || "").toLowerCase();
    var className = "";
    if (el.classList && el.classList.length) {
      className = "." + el.classList[0];
    }

    if (ariaLabel) {
      return ariaLabel;
    }
    if (rawText) {
      return rawText;
    }
    if (id) {
      return tag ? (tag + " #" + id) : ("#" + id);
    }
    if (tag) {
      return className ? (tag + " " + className) : tag;
    }
    return (selectorData && selectorData.selector) ? selectorData.selector : "";
  }

  function selectorSummaryHtml(selectorData, targetLabel) {
    if (!selectorData || !selectorData.selector) {
      return "";
    }

    return (
      '<div class="polanger-shield-selector-summary">' +
      '<p class="polanger-shield-target-title"><strong>' + $("<div>").text(getI18n("selectedArea", "Selected area")).html() + ":</strong> " + $("<div>").text(targetLabel || selectorData.selector).html() + "</p>" +
      '<p class="polanger-shield-target-raw"><span>' + $("<div>").text(getI18n("technicalSelector", "Technical selector")).html() + ":</span> <code>" + $("<div>").text(selectorData.selector).html() + "</code></p>" +
      "</div>"
    );
  }

  function setPanelState(isOpen) {
    state.panelOpen = !!isOpen;
    $("#polanger-shield-panel")
      .prop("hidden", !state.panelOpen)
      .toggleClass("is-open", state.panelOpen);
    $("#polanger-shield-trigger").attr("aria-expanded", state.panelOpen ? "true" : "false");
  }

  function closePanel() {
    setPanelState(false);
  }

  function togglePanel() {
    setPanelState(!state.panelOpen);
  }

  function closeModal() {
    $(".polanger-shield-modal-wrap").remove();
    stopSelectorMode();
  }

  function buildModal(title, bodyHtml) {
    closeModal();
    closePanel();
    var modal =
      '<div class="polanger-shield-modal-wrap">' +
      '<div class="polanger-shield-modal-backdrop"></div>' +
      '<div class="polanger-shield-modal" role="dialog" aria-modal="true">' +
      '<div class="polanger-shield-modal-header">' +
      "<h3>" + $("<div>").text(title).html() + "</h3>" +
      '<button type="button" class="polanger-shield-modal-close" aria-label="' + getI18n("cancel", "Cancel") + '">&times;</button>' +
      "</div>" +
      '<div class="polanger-shield-modal-body">' + bodyHtml + "</div>" +
      "</div>" +
      "</div>";
    $("body").append(modal);
  }

  function parseCheckedValues(container, fieldName) {
    var values = [];
    $(container).find('input[name="' + fieldName + '"]:checked').each(function () {
      values.push(parseInt($(this).val(), 10));
    });
    return values.filter(function (value) { return !isNaN(value) && value > 0; });
  }

  function saveRule(payload) {
    var data = getData();

    return $.post(data.ajaxUrl, $.extend({}, payload, {
      action: "polanger_shield_save_rule",
      nonce: data.nonce
    }));
  }

  function showToast(message, isError) {
    var toast = $('<div class="polanger-shield-toast" />').text(message);
    if (isError) {
      toast.addClass("is-error");
    }
    $("body").append(toast);
    setTimeout(function () {
      toast.addClass("is-visible");
    }, 10);
    setTimeout(function () {
      toast.removeClass("is-visible");
      setTimeout(function () {
        toast.remove();
      }, 200);
    }, 2500);
  }

  function openPageBlockModal() {
    var bodyHtml =
      '<p class="polanger-shield-help-text">' + getI18n("pageBlockHelp", "Selected users will not be able to open this page. If URL blocking is enabled, direct URL access is also denied.") + "</p>" +
      '<p class="polanger-shield-users-title"><strong>' + getI18n("selectedUsersLabel", "Affected users") + "</strong></p>" +
      '<p>' + getI18n("hideThisPage", "Hide this page for selected users") + "</p>" +
      '<div class="polanger-shield-user-list">' + renderUserCheckboxes("target_user_ids") + "</div>" +
      '<label class="polanger-shield-check">' +
      '<input type="checkbox" name="block_url" checked /> ' + getI18n("blockUrlAccess", "Block direct URL access") +
      "</label>" +
      '<div class="polanger-shield-modal-actions">' +
      '<button type="button" class="button button-secondary polanger-shield-cancel">' + getI18n("cancel", "Cancel") + "</button>" +
      '<button type="button" class="button button-primary polanger-shield-save">' + getI18n("saveRule", "Save Rule") + "</button>" +
      "</div>";

    buildModal(getI18n("hideThisPage", "Hide this page"), bodyHtml);
    $(".polanger-shield-modal").attr("data-rule-type", "page_block");
  }

  function openElementHideModal(selectorData) {
    var bodyHtml =
      selectorSummaryHtml(selectorData, state.lastTargetLabel) +
      "<p>" + getI18n("selectorReliability", "Selector reliability") + ": " + selectorData.strength + "/100</p>" +
      '<p class="polanger-shield-help-text">' + getI18n("elementHideHelp", "Selected users will not see this area on this admin page.") + "</p>" +
      '<p class="polanger-shield-users-title"><strong>' + getI18n("selectedUsersLabel", "Affected users") + "</strong></p>" +
      '<div class="polanger-shield-user-list">' + renderUserCheckboxes("target_user_ids") + "</div>" +
      '<div class="polanger-shield-modal-actions">' +
      '<button type="button" class="button button-secondary polanger-shield-cancel">' + getI18n("cancel", "Cancel") + "</button>" +
      '<button type="button" class="button button-primary polanger-shield-save">' + getI18n("saveRule", "Save Rule") + "</button>" +
      "</div>";
    buildModal(getI18n("selectUsers", "Select users"), bodyHtml);
    $(".polanger-shield-modal").attr("data-rule-type", "element_hide");
  }

  function openNoteModal(selectorData) {
    var bodyHtml =
      selectorSummaryHtml(selectorData, state.lastTargetLabel) +
      '<p class="polanger-shield-help-text">' + getI18n("noteHelp", "Only selected users will see this note on the selected area.") + "</p>" +
      '<textarea name="shield_note" rows="4" placeholder="' + $("<div>").text(getI18n("notePlaceholder", "Write your note...")).html() + '"></textarea>' +
      '<p class="polanger-shield-users-title"><strong>' + getI18n("visibleUsersLabel", "Users who can see this note") + "</strong></p>" +
      '<div class="polanger-shield-user-list">' + renderUserCheckboxes("note_visible_user_ids") + "</div>" +
      '<div class="polanger-shield-modal-actions">' +
      '<button type="button" class="button button-secondary polanger-shield-cancel">' + getI18n("cancel", "Cancel") + "</button>" +
      '<button type="button" class="button button-primary polanger-shield-save">' + getI18n("saveRule", "Save Rule") + "</button>" +
      "</div>";
    buildModal(getI18n("leaveNote", "Leave note"), bodyHtml);
    $(".polanger-shield-modal").attr("data-rule-type", "note");
  }

  function stopSelectorMode() {
    $("body").removeClass("polanger-shield-selecting");
    $(".polanger-shield-hover").removeClass("polanger-shield-hover");
    $(document).off(".polangerShieldSelect");
    $(window).off(".polangerShieldSelect");
    state.selectingType = "";
  }

  function startSelectorMode(type) {
    closePanel();
    closeModal();
    state.selectingType = type;
    $("body").addClass("polanger-shield-selecting");

    var ignoreSelector = "#wpadminbar,#adminmenu,#polanger-shield-trigger,#polanger-shield-panel,.polanger-shield-modal-wrap";

    $(document)
      .on("mouseover.polangerShieldSelect", function (event) {
        var $target = $(event.target);
        if ($target.closest(ignoreSelector).length) {
          return;
        }
        $(".polanger-shield-hover").removeClass("polanger-shield-hover");
        $target.addClass("polanger-shield-hover");
      })
      .on("click.polangerShieldSelect", function (event) {
        var $target = $(event.target);
        if ($target.closest(ignoreSelector).length) {
          return;
        }

        event.preventDefault();
        event.stopPropagation();
        var selectorData = window.PolangerShieldSelector.generate(event.target);
        state.lastSelector = selectorData;
        state.lastTargetLabel = getTargetLabel(event.target, selectorData);
        stopSelectorMode();

        if (type === "element_hide") {
          openElementHideModal(selectorData);
        } else if (type === "note") {
          openNoteModal(selectorData);
        }
      });

    $(window).on("keydown.polangerShieldSelect", function (event) {
      if (event.key === "Escape" || event.keyCode === 27) {
        event.preventDefault();
        stopSelectorMode();
      }
    });
  }

  function handleModalSubmit() {
    var $modal = $(".polanger-shield-modal");
    var selectorData = state.lastSelector || {};
    var type = $modal.attr("data-rule-type") || "";
    if (type === "page_block") {
      selectorData = {};
    }

    var payload = {
      rule_type: type,
      selector: selectorData.selector || "",
      selector_strength: selectorData.strength || 0,
      target_user_ids: parseCheckedValues($modal, "target_user_ids"),
      note_visible_user_ids: parseCheckedValues($modal, "note_visible_user_ids"),
      note: $modal.find('textarea[name="shield_note"]').val() || "",
      block_url: $modal.find('input[name="block_url"]').is(":checked") ? 1 : 0
    };

    var context = (getData().context || {});
    payload.context_screen_id = context.screen_id || "";
    payload.context_page_hook = context.page_hook || "";
    payload.context_page_slug = context.page_slug || "";
    payload.context_request_uri = context.request_uri || "";

    if (type === "note") {
      if (!String(payload.note || "").replace(/\s+/g, " ").trim()) {
        showToast(getI18n("noteRequired", "Please write a note before saving."), true);
        return;
      }

      if (!payload.note_visible_user_ids.length) {
        showToast(getI18n("selectUserWarning", "Please select at least one user."), true);
        return;
      }
    } else if (type === "page_block" || type === "element_hide") {
      if (!payload.target_user_ids.length) {
        showToast(getI18n("selectUserWarning", "Please select at least one user."), true);
        return;
      }
    }

    saveRule(payload)
      .done(function (response) {
        if (!response || !response.success) {
          showToast((response && response.data && response.data.message) || getI18n("saveFailed", "Rule could not be saved."), true);
          return;
        }
        closeModal();
        showToast((response.data && response.data.message) || getI18n("saveSuccess", "Rule saved successfully."));
      })
      .fail(function () {
        showToast(getI18n("saveFailed", "Rule could not be saved."), true);
      });
  }

  function bindEvents() {
    $(document).on("click", "#polanger-shield-trigger", function (event) {
      event.preventDefault();
      event.stopPropagation();
      togglePanel();
    });
    $(document).on("click", ".polanger-shield-panel__close", function (event) {
      event.preventDefault();
      closePanel();
    });
    $(document).on("click", ".polanger-shield-cancel,.polanger-shield-modal-close,.polanger-shield-modal-backdrop", closeModal);
    $(document).on("click", "[data-shield-action='page_block']", openPageBlockModal);
    $(document).on("click", "[data-shield-action='element_hide']", function () { startSelectorMode("element_hide"); });
    $(document).on("click", "[data-shield-action='note']", function () { startSelectorMode("note"); });
    $(document).on("click", ".polanger-shield-save", handleModalSubmit);
    $(document).on("click", function (event) {
      var $target = $(event.target);
      if (!$target.closest("#polanger-shield-panel, #polanger-shield-trigger").length) {
        closePanel();
      }
    });
    $(window).on("keydown.polangerShieldPanel", function (event) {
      if (event.key === "Escape" || event.keyCode === 27) {
        closePanel();
      }
    });
  }

  function applyTestRuleHighlight() {
    var data = getData();
    var testRule = data.testRule || null;
    if (!testRule || !testRule.selector) {
      return;
    }

    try {
      var nodes = document.querySelectorAll(testRule.selector);
      if (!nodes.length) {
        return;
      }
      nodes.forEach(function (node) {
        node.classList.add("polanger-shield-test-highlight");
      });
      if (nodes[0] && typeof nodes[0].scrollIntoView === "function") {
        nodes[0].scrollIntoView({ block: "center", behavior: "smooth" });
      }
      showToast(getI18n("testModeApplied", "Rule test mode: selected area is highlighted."));
    } catch (error) {
      // Invalid selector or missing node.
    }
  }

  $(function () {
    bindEvents();
    applyTestRuleHighlight();
  });
})(jQuery);
