(function () {
  window.Warpbox = window.Warpbox || {};

  window.Warpbox.openInNewTab = function openInNewTab(url) {
    window.open(url, "_blank", "noopener,noreferrer");
  };

  window.Warpbox.absoluteURL = function absoluteURL(url) {
    if (!url) {
      return "";
    }
    try {
      return new URL(url, window.location.origin).href;
    } catch (_) {
      return url;
    }
  };

  window.Warpbox.writeClipboard = async function writeClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return;
    }

    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.setAttribute("readonly", "");
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.append(textarea);
    textarea.select();
    document.execCommand("copy");
    textarea.remove();
  };

  window.Warpbox.copyText = async function copyText(text, button, copiedLabel) {
    if (!text || !button) {
      return;
    }
    if (typeof text === "string" && (text.startsWith("/") || /^https?:\/\//i.test(text))) {
      text = window.Warpbox.absoluteURL(text);
    }
    await window.Warpbox.writeClipboard(text);
    const previous = button.textContent;
    button.textContent = copiedLabel;
    setTimeout(() => {
      button.textContent = previous;
    }, 1400);
  };

  window.Warpbox.formatDate = function formatDate(value) {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
      return value;
    }
    return date.toLocaleDateString(undefined, {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  window.Warpbox.formatBytes = function formatBytes(bytes) {
    if (bytes < 1024) {
      return `${bytes} B`;
    }
    const units = ["KiB", "MiB", "GiB", "TiB"];
    let value = bytes / 1024;
    let unit = 0;
    while (value >= 1024 && unit < units.length - 1) {
      value /= 1024;
      unit += 1;
    }
    return `${value.toFixed(1)} ${units[unit]}`;
  };
})();
