/**
 * SITS Locked Widget Handler for Elementor Editor
 *
 * @package Softech_Addons_for_Elementor
 * @since 1.0.0
 */

(function ($) {
  "use strict";

  const lockedData =
    typeof sitselLockedWidgets !== "undefined"
      ? sitselLockedWidgets
      : {
          widgets: [],
          messages: {
            lockedTitle: "Premium Widget",
            lockedMessage:
              "This is a premium widget. Upgrade to Pro to unlock it!",
            upgradeUrl: "tester.com",
            upgradeText: "Upgrade Now",
          },
        };

  const lockedWidgets = lockedData.widgets || [];
  const messages = lockedData.messages;

  $(document).on("click", function (e) {
    const $target = $(e.target);
    if ($target.closest('.elementor-button, a[href*="elementor"]').length) {
      $target.attr("href") || $target.closest("a").attr("href");
    }
  });

  if (lockedWidgets.length === 0) return;

  let currentLockedWidget = null;

  $(window).on("elementor:init", function () {
    if (elementor.dialogsManager) {
      const originalShowModal = elementor.dialogsManager.showModal;
      if (originalShowModal) {
        elementor.dialogsManager.showModal = function () {
          const result = originalShowModal.apply(this, arguments);

          [50, 100, 200, 500].forEach(function (delay) {
            setTimeout(function () {
              $(
                ".dialog-widget:visible, .elementor-templates-modal:visible, .dialog-lightbox-widget:visible"
              ).each(function () {
                const $dialog = $(this);
                $dialog
                  .find(
                    'a[href*="elementor.com"], a[href*="go.elementor.com"], button[onclick*="elementor.com"]'
                  )
                  .each(function () {
                    const $link = $(this);
                    if (!$link.data("sitsel-modified")) {
                      $link.data("sitsel-modified", true);
                      if ($link.is("a")) {
                        $link.attr("href", messages.upgradeUrl);
                        $link.attr("target", "_self");
                      }
                      $link.off("click");
                      $link.on("click.sitsel", function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        window.location.href = messages.upgradeUrl;
                        return false;
                      });
                    }
                  });
              });
            }, delay);
          });

          return result;
        };
      }
    }

    elementor.hooks.addFilter(
      "elements/widget/before:render",
      preventLockedWidgetRender
    );

    elementor.hooks.addFilter(
      "panel/elements/regionViews",
      handlePanelElements
    );

    elementor.on("preview:loaded", function () {
      setTimeout(function () {
        setupLockedWidgets();
        monitorAndRemoveFromCanvas();
      }, 500);
    });

    setupLockedWidgets();
    observePanelChanges();
    preventWidgetAddition();

    elementor.hooks.addFilter(
      "promotion/get_data",
      function (promotionData, widgetType) {
        if (lockedWidgets.includes(widgetType)) {
          currentLockedWidget = widgetType;
          return {
            title: messages.lockedTitle,
            description: messages.lockedMessage,
            url: messages.upgradeUrl,
            upgrade_url: messages.upgradeUrl,
            action_button: {
              text: messages.upgradeText,
              url: messages.upgradeUrl,
            },
          };
        }
        return promotionData;
      }
    );

    elementor.hooks.addFilter(
      "promotion/get_action_button",
      function (actionButton, widgetType) {
        if (lockedWidgets.includes(widgetType)) {
          return {
            text: messages.upgradeText,
            url: messages.upgradeUrl,
          };
        }
        return actionButton;
      }
    );

    elementor.hooks.addFilter("promotion/get_url", function (url, widgetType) {
      if (lockedWidgets.includes(widgetType)) {
        return messages.upgradeUrl;
      }
      return url;
    });

    setTimeout(function () {
      const originalCreateWidget = elementor.dialogsManager.createWidget.bind(
        elementor.dialogsManager
      );

      elementor.dialogsManager.createWidget = function (type, options) {
        if (
          (type === "promotionDialog" || type === "lightbox") &&
          currentLockedWidget
        ) {
          if (options && options.buttons) {
            options.buttons.forEach(function (button) {
              if (button.name === "action" || button.text.includes("Upgrade")) {
                button.callback = function () {
                  window.location.href = messages.upgradeUrl;
                  return false;
                };
              }
            });
          }
        }

        const dialog = originalCreateWidget(type, options);

        if (type === "promotionDialog" || type === "lightbox") {
          dialog.on("show", function () {
            if (currentLockedWidget) {
              [10, 50, 100, 200].forEach(function (delay) {
                setTimeout(function () {
                  const $dialog = dialog.getElements("widget");
                  const $links = $dialog.find(
                    'a[href*="elementor.com"], ' +
                      'a[href*="go.elementor"], ' +
                      ".elementor-button, " +
                      'button[class*="action"], ' +
                      "[data-action], " +
                      ".dialog-button"
                  );

                  $links.each(function () {
                    const $link = $(this);
                    if ($link.is("a")) {
                      $link.attr("href", messages.upgradeUrl);
                    }
                    $link.off();
                    $link.on("click.sitsel", function (e) {
                      e.preventDefault();
                      e.stopPropagation();
                      e.stopImmediatePropagation();
                      window.location.href = messages.upgradeUrl;
                      dialog.hide();
                      return false;
                    });
                  });
                }, delay);
              });
            }
          });

          dialog.on("hide", function () {
            currentLockedWidget = null;
          });
        }

        return dialog;
      };
    }, 100);

    setInterval(function () {
      if (!currentLockedWidget) return;

      $(
        ".dialog-widget:visible, " +
          ".elementor-templates-modal:visible, " +
          ".elementor-control-promotion:visible, " +
          ".dialog-lightbox-widget:visible, " +
          ".elementor-dialog:visible"
      ).each(function () {
        const $container = $(this);

        $container
          .find(
            'a[href*="elementor.com"], ' +
              'a[href*="go.elementor"], ' +
              "button, " +
              ".elementor-button, " +
              '[class*="button"]'
          )
          .each(function () {
            const $el = $(this);

            if (!$el.data("sitsel-intercepted")) {
              $el.data("sitsel-intercepted", true);

              const originalHref = $el.attr("href");

              if (
                $el.is("a") &&
                originalHref &&
                originalHref.includes("elementor")
              ) {
                $el.attr("href", messages.upgradeUrl);
                $el.attr("target", "_self");
              }

              $el[0].addEventListener(
                "click",
                function (e) {
                  e.preventDefault();
                  e.stopPropagation();
                  e.stopImmediatePropagation();
                  window.location.href = messages.upgradeUrl;
                  return false;
                },
                true
              );

              $el.off("click.sitsel");
              $el.on("click.sitsel", function (e) {
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                window.location.href = messages.upgradeUrl;
                return false;
              });
            }
          });
      });
    }, 100);
  });

  function preventLockedWidgetRender(view) {
    if (!view || !view.model) return view;
    const widgetType = view.model.get("widgetType");
    if (lockedWidgets.includes(widgetType)) {
      setTimeout(function () {
        view.model.destroy();
      }, 10);
      showLockedNotification();
      return false;
    }
    return view;
  }

  function handlePanelElements(regionViews) {
    if (regionViews && regionViews.widgets) {
      const originalOnDragStart = regionViews.widgets.prototype.onDragStart;

      regionViews.widgets.prototype.onDragStart = function (e) {
        const $target = $(e.currentTarget);
        const widgetType = $target.data("widget_type");

        if (lockedWidgets.includes(widgetType)) {
          e.preventDefault();
          e.stopImmediatePropagation();
          showLockedNotification();
          return false;
        }

        if (originalOnDragStart) {
          return originalOnDragStart.apply(this, arguments);
        }
      };
    }
    return regionViews;
  }

  function preventWidgetAddition() {
    if (elementor.channels && elementor.channels.data) {
      elementor.channels.data.on("element:before:add", function (model) {
        if (!model) return;
        const widgetType = model.get("widgetType");
        if (lockedWidgets.includes(widgetType)) {
          showLockedNotification();
          return false;
        }
      });
    }
  }

  function setupLockedWidgets() {
    lockedWidgets.forEach(function (widgetType) {
      const selector = '[data-widget_type="' + widgetType + '"]';
      const $widgets = $("#elementor-panel").find(selector);

      $widgets.each(function () {
        const $widget = $(this);
        if ($widget.data("locked-processed")) return;

        $widget.data("locked-processed", true);
        $widget.addClass("sitsel-locked-widget");

        if (!$widget.find(".sitsel-lock-badge").length) {
          const $badge = $("<div>", {
            class: "sitsel-lock-badge",
            html: '<i class="eicon-lock"></i>',
          });
          $widget.append($badge);
        }

        $widget.attr("draggable", "false");
        $widget.css({
          cursor: "not-allowed",
          opacity: "0.6",
          "pointer-events": "none",
        });

        $widget.find(".sitsel-lock-badge").css("pointer-events", "all");

        $widget.off("click.locked mousedown.locked touchstart.locked");
        $widget.on(
          "click.locked mousedown.locked touchstart.locked",
          function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            currentLockedWidget = widgetType;
            showLockedNotification();
            return false;
          }
        );

        $widget.find(".sitsel-lock-badge").off("click.badge");
        $widget.find(".sitsel-lock-badge").on("click.badge", function (e) {
          e.preventDefault();
          e.stopImmediatePropagation();
          showLockedNotification();
          return false;
        });
      });
    });
  }

  function showLockedNotification() {
    if (elementor && elementor.dialogsManager) {
      const dialog = elementor.dialogsManager.createWidget("lightbox", {
        id: "sitsel-locked-dialog",
        headerMessage: messages.lockedTitle,
        message: messages.lockedMessage,
        position: {
          my: "center center",
          at: "center center",
        },
        hide: {
          onBackgroundClick: true,
          onEscKeyPress: true,
        },
      });

      dialog.addButton({
        name: "upgrade",
        text: messages.upgradeText,
        classes: "elementor-button elementor-button-success",
        callback: function () {
          window.location.href = messages.upgradeUrl;
          dialog.hide();
        },
      });

      dialog.addButton({
        name: "cancel",
        text: "Close",
        callback: function () {
          dialog.hide();
        },
      });

      dialog.show();
    }
  }

  function observePanelChanges() {
    const panelElement = document.getElementById("elementor-panel");

    if (!panelElement) {
      setTimeout(observePanelChanges, 500);
      return;
    }

    const observer = new MutationObserver(function (mutations) {
      let needsSetup = false;

      mutations.forEach(function (mutation) {
        if (mutation.addedNodes.length > 0) {
          mutation.addedNodes.forEach(function (node) {
            if (node.nodeType === 1) {
              const $node = $(node);
              lockedWidgets.forEach(function (widgetType) {
                if (
                  $node.is('[data-widget_type="' + widgetType + '"]') ||
                  $node.find('[data-widget_type="' + widgetType + '"]').length >
                    0
                ) {
                  needsSetup = true;
                }
              });
            }
          });
        }
      });

      if (needsSetup) {
        setTimeout(setupLockedWidgets, 100);
      }
    });

    observer.observe(panelElement, {
      childList: true,
      subtree: true,
    });
  }

  function monitorAndRemoveFromCanvas() {
    setInterval(function () {
      lockedWidgets.forEach(function (widgetType) {
        const selector = ".elementor-widget-" + widgetType.replace(/_/g, "-");
        const $elements = elementor.$previewContents.find(selector);

        $elements.each(function () {
          const $el = $(this);
          const elementId = $el.data("id");

          if (!elementId) {
            $el.remove();
            return;
          }

          try {
            const elementModel = elementor
              .getPreviewView()
              .collection.get(elementId);
            if (elementModel) {
              elementModel.destroy();
              return;
            }
          } catch (e) {}

          $el.remove();
        });
      });
    }, 500);
  }

  setInterval(function () {
    $(
      ".dialog-widget:visible, " +
        ".elementor-dialog:visible, " +
        ".elementor-templates-modal:visible, " +
        ".dialog-lightbox-widget:visible"
    ).each(function () {
      const $dialog = $(this);

      $dialog
        .find(
          'a[href*="elementor.com"], a[href*="go.elementor.com"], ' +
            "button.go-pro, .dialog-button.dialog-action, .elementor-button.go-pro"
        )
        .each(function () {
          const $el = $(this);

          if ($el.data("softechure-modified")) return;
          $el.data("softechure-modified", true);

          const targetUrl =
            "https://softechaddons.sitslab.com/#pro-plan";

          $el.attr("href", targetUrl);
          $el.attr("target", "_blank");

          $el.off();

          $el.on("click.softechure", function (e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            // Always open in new tab
            window.open(targetUrl, "_blank");

            return false;
          });
        });
    });
  }, 300);

  if (currentLockedWidget && lockedWidgets.includes(currentLockedWidget)) {
    $(document).on(
      "click",
      'a[href*="elementor.com"], a[href*="go.elementor.com"], button.go-pro, .elementor-button.go-pro, .dialog-button.dialog-action',
      function (e) {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        const targetUrl =
          "https://softechaddons.sitslab.com/#pro-plan";

        if (e.ctrlKey || e.metaKey) {
          window.open(targetUrl, "_blank");
        } else {
          window.location.href = targetUrl;
        }
        return false;
      }
    );
  }
})(jQuery);
