(function () {
  const shareButtons = document.querySelectorAll("[data-share-box]");
  if (shareButtons.length === 0) {
    return;
  }

  shareButtons.forEach((button) => {
    const label = button.querySelector("[data-share-box-label]") || button;
    const shareData = {
      title: button.dataset.shareTitle || document.title,
      text: button.dataset.shareText || "",
      url: window.Warpbox.absoluteURL(button.dataset.shareUrl || window.location.href),
    };
    const canShare = typeof navigator.share === "function" && (!navigator.canShare || navigator.canShare(shareData));

    label.textContent = canShare ? "Share" : "Copy Link";
    button.setAttribute("aria-label", canShare ? "Share this box" : "Copy box link");

    button.addEventListener("click", async () => {
      if (canShare) {
        try {
          await navigator.share(shareData);
          return;
        } catch (error) {
          if (error && error.name === "AbortError") {
            return;
          }
        }
      }
      await copyShareURL(button, label, shareData.url, canShare);
    });
  });

  async function copyShareURL(button, label, url, shareMode) {
    try {
      await window.Warpbox.writeClipboard(url);
      const previous = label.textContent;
      label.textContent = "Copied";
      window.setTimeout(() => {
        label.textContent = shareMode ? "Share" : "Copy Link";
      }, 1400);
    } catch (error) {
      if (window.Warpbox && typeof window.Warpbox.error === "function") {
        window.Warpbox.error("The share link could not be copied.", {
          title: "Copy failed",
        });
      }
    }
  }
})();
