(function ($) {
  "use strict";

  var modalOpen = false;

  function getConfig() {
    return window.psvElementorProLock || {
      pricingUrl: "#",
      title: "Pro Feature",
      message: "Upgrade to unlock this control.",
      upgrade: "Upgrade Now",
      close: "Close",
    };
  }

  function closeModal() {
    $(".psv-pro-lock-overlay").remove();
    modalOpen = false;
  }

  function openModal() {
    if (modalOpen) {
      return;
    }

    modalOpen = true;
    var cfg = getConfig();

    var html = [
      '<div class="psv-pro-lock-overlay">',
      '  <div class="psv-pro-lock-modal" role="dialog" aria-modal="true">',
      '    <div class="psv-pro-lock-header">',
      '      <div class="psv-pro-lock-title-wrap">',
      '        <span class="psv-pro-lock-title">' + cfg.title + '</span>',
      '        <span class="psv-pro-lock-badge">PRO</span>',
      "      </div>",
      '      <button type="button" class="psv-pro-lock-close" aria-label="' + cfg.close + '">×</button>',
      "    </div>",
      '    <div class="psv-pro-lock-body">',
      '      <p>' + cfg.message + '</p>',
      '      <a class="psv-pro-lock-upgrade" href="' + cfg.pricingUrl + '" target="_blank" rel="noopener noreferrer">' + cfg.upgrade + "</a>",
      "    </div>",
      "  </div>",
      "</div>",
    ].join("");

    $("body").append(html);
  }

  function blockAndPrompt(event) {
    if ($(event.target).closest(".psv-pro-lock-overlay").length) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();
    if (event.stopImmediatePropagation) {
      event.stopImmediatePropagation();
    }

    openModal();
    return false;
  }

  $(document)
    .on(
      "mousedown click keydown",
      ".psv-pro-locked-control .elementor-switch, .psv-pro-locked-control .elementor-control-input-wrapper, .psv-pro-locked-control .elementor-control-field",
      function (event) {
        if (event.type === "keydown" && event.key !== "Enter" && event.key !== " ") {
          return;
        }
        blockAndPrompt(event);
      }
    )
    .on("click", ".psv-pro-lock-close", function (event) {
      event.preventDefault();
      closeModal();
    })
    .on("click", ".psv-pro-lock-overlay", function (event) {
      if ($(event.target).is(".psv-pro-lock-overlay")) {
        closeModal();
      }
    });
})(jQuery);
