(function ($) {
  "use strict";

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

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

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

  function escapeHtml(value) {
    return $("<div>").text(value || "").html();
  }

  function closePanel() {
    $("#polanger-shield-panel").prop("hidden", true).removeClass("is-open");
    $("#polanger-shield-trigger").attr("aria-expanded", "false");
  }

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

  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();
      }, 220);
    }, 2400);
  }

  function renderUserCheckboxes() {
    var users = getShieldData().users || [];
    if (!users.length) {
      return "<p>" + escapeHtml(i18n("selectUserWarning", "Please select at least one user.")) + "</p>";
    }

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

  function renderOption(name, title, text, checked) {
    return (
      '<label class="polanger-shield-demo-lock-option">' +
        '<input type="checkbox" name="' + name + '"' + (checked ? ' checked="checked"' : "") + ' />' +
        '<span class="polanger-shield-demo-lock-option__content">' +
          '<span class="polanger-shield-demo-lock-option__title">' + escapeHtml(title) + "</span>" +
          '<span class="polanger-shield-demo-lock-option__text">' + escapeHtml(text) + "</span>" +
        "</span>" +
      "</label>"
    );
  }

  function buildModal() {
    var defaults = getData().defaults || {};
    var bodyHtml =
      '<p class="polanger-shield-help-text">' + escapeHtml(i18n("description", "Selected administrators can explore this page, but Shield will turn it into a view-only demo screen and block save attempts.")) + "</p>" +
      '<p class="polanger-shield-users-title"><strong>' + escapeHtml(i18n("affectedUsersLabel", "Affected users")) + "</strong></p>" +
      '<div class="polanger-shield-user-list">' + renderUserCheckboxes() + "</div>" +
      '<div class="polanger-shield-demo-lock-grid">' +
        '<p class="polanger-shield-demo-lock-grid__intro">' + escapeHtml(i18n("optionIntro", "Choose how strict this demo protection should be for the current admin screen.")) + "</p>" +
        renderOption("show_notice", i18n("optionNoticeLabel", "Show a clear demo-mode notice on the page"), i18n("optionNoticeText", "Lets the user know they are browsing a protected demo screen and that changes are intentionally disabled."), defaults.show_notice !== false) +
        renderOption("disable_controls", i18n("optionVisualLabel", "Dim or disable common save controls visually"), i18n("optionVisualText", "Marks primary save and publish controls as unavailable before the user even clicks them."), defaults.disable_controls !== false) +
        renderOption("block_form_submissions", i18n("optionFormsLabel", "Block standard form submissions"), i18n("optionFormsText", "Prevents settings forms, classic editor saves, and similar POST requests from completing."), defaults.block_form_submissions !== false) +
        renderOption("block_ajax_requests", i18n("optionAjaxLabel", "Block likely AJAX save requests from this page"), i18n("optionAjaxText", "Stops common admin-ajax save or update actions while keeping harmless background reads untouched where possible."), defaults.block_ajax_requests !== false) +
        renderOption("block_rest_requests", i18n("optionRestLabel", "Block REST write requests from this page"), i18n("optionRestText", "Protects modern interfaces that submit changes through the WordPress REST API."), defaults.block_rest_requests !== false) +
      "</div>" +
      '<div class="polanger-shield-modal-actions">' +
        '<button type="button" class="button button-secondary polanger-shield-demo-lock-cancel">' + escapeHtml(i18n("cancel", "Cancel")) + "</button>" +
        '<button type="button" class="button button-primary polanger-shield-demo-lock-save">' + escapeHtml(i18n("saveRule", "Save Demo Lock")) + "</button>" +
      "</div>";

    return (
      '<div class="polanger-shield-modal-wrap">' +
        '<div class="polanger-shield-modal-backdrop"></div>' +
        '<div class="polanger-shield-modal" role="dialog" aria-modal="true" data-rule-type="demo_lock">' +
          '<div class="polanger-shield-modal-header">' +
            "<h3>" + escapeHtml(i18n("title", "Lock This Page for Demo")) + "</h3>" +
            '<button type="button" class="polanger-shield-modal-close" aria-label="' + escapeHtml(i18n("cancel", "Cancel")) + '">&times;</button>' +
          "</div>" +
          '<div class="polanger-shield-modal-body">' + bodyHtml + "</div>" +
        "</div>" +
      "</div>"
    );
  }

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

  function buildRuleMeta($modal) {
    return {
      show_notice: $modal.find('input[name="show_notice"]').is(":checked") ? 1 : 0,
      disable_controls: $modal.find('input[name="disable_controls"]').is(":checked") ? 1 : 0,
      block_form_submissions: $modal.find('input[name="block_form_submissions"]').is(":checked") ? 1 : 0,
      block_ajax_requests: $modal.find('input[name="block_ajax_requests"]').is(":checked") ? 1 : 0,
      block_rest_requests: $modal.find('input[name="block_rest_requests"]').is(":checked") ? 1 : 0
    };
  }

  function saveRule(payload) {
    var data = getShieldData();
    return $.post(data.ajaxUrl, $.extend({}, payload, {
      action: "polanger_shield_save_rule",
      nonce: data.nonce
    }));
  }

  function openModal() {
    closeModal();
    closePanel();
    $("body").append(buildModal());
  }

  function handleSave() {
    var $modal = $('.polanger-shield-modal[data-rule-type="demo_lock"]');
    if (!$modal.length) {
      return;
    }

    var targetUsers = getCheckedValues($modal, "target_user_ids");
    if (!targetUsers.length) {
      showToast(i18n("selectUserWarning", "Please select at least one user."), true);
      return;
    }

    var context = getShieldData().context || {};
    var payload = {
      rule_type: "demo_lock",
      target_user_ids: targetUsers,
      rule_meta: buildRuleMeta($modal),
      context_screen_id: context.screen_id || "",
      context_page_hook: context.page_hook || "",
      context_page_slug: context.page_slug || "",
      context_request_uri: context.request_uri || ""
    };

    saveRule(payload)
      .done(function (response) {
        if (!response || !response.success) {
          showToast((response && response.data && response.data.message) || i18n("saveFailed", "Demo Lock rule could not be saved."), true);
          return;
        }

        closeModal();
        showToast((response.data && response.data.message) || i18n("saveSuccess", "Demo Lock rule saved successfully."));
      })
      .fail(function () {
        showToast(i18n("saveFailed", "Demo Lock rule could not be saved."), true);
      });
  }

  $(document).on("click", "[data-shield-action='demo_lock']", function (event) {
    event.preventDefault();
    openModal();
  });

  $(document).on("click", ".polanger-shield-demo-lock-cancel", function (event) {
    event.preventDefault();
    closeModal();
  });

  $(document).on("click", ".polanger-shield-demo-lock-save", function (event) {
    event.preventDefault();
    handleSave();
  });
})(jQuery);
