import { createRoot } from 'react-dom/client';
import { Buffer } from 'buffer';
import { toast } from 'sonner';
import { jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useRef, useEffect } from 'react';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { reaction, computed, makeObservable, action, observable } from 'mobx';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

// util/date.ts
var formatDateToUSLocaleString = /* @__PURE__ */ __name((date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString("en-US", {
    year: "numeric",
    month: "numeric",
    day: "numeric"
  });
}, "formatDateToUSLocaleString");
var formatDateToLocaleStringWithTime = /* @__PURE__ */ __name((date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString("en-US", {
    year: "numeric",
    month: "numeric",
    day: "numeric",
    hour: "numeric",
    minute: "numeric"
  });
}, "formatDateToLocaleStringWithTime");
var getRelativeDateLabel = /* @__PURE__ */ __name((date) => {
  const today = /* @__PURE__ */ new Date();
  const yesterday = /* @__PURE__ */ new Date();
  yesterday.setDate(today.getDate() - 1);
  if (date.toDateString() === today.toDateString()) {
    return "today";
  } else if (date.toDateString() === yesterday.toDateString()) {
    return "yesterday";
  } else {
    return date.toDateString();
  }
}, "getRelativeDateLabel");
var groupMessagesByDate = /* @__PURE__ */ __name((messages) => {
  const groupedMessages = {};
  for (const message of messages) {
    const date = new Date(message.createdAt ?? "").toDateString();
    if (!groupedMessages[date]) {
      groupedMessages[date] = [];
    }
    groupedMessages[date].push(message);
  }
  return groupedMessages;
}, "groupMessagesByDate");
var formatDateToMonthAndDay = /* @__PURE__ */ __name((date) => {
  const today = /* @__PURE__ */ new Date();
  if (date.getDate() === today.getDate() && date.getMonth() === today.getMonth() && date.getFullYear() === today.getFullYear()) {
    return date.toLocaleTimeString("en-US", {
      hour: "numeric",
      minute: "numeric",
      hour12: true
    });
  }
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}/${day}`;
}, "formatDateToMonthAndDay");

// util/file.ts
var getFileName = /* @__PURE__ */ __name((fileName) => {
  const nameParts = fileName.split(".");
  return nameParts.slice(0, -1).join(".");
}, "getFileName");
var getFileExt = /* @__PURE__ */ __name((fileName) => {
  const nameParts = fileName.split(".");
  return nameParts.pop() || "";
}, "getFileExt");
var isFileTypeImageOrPdf = /* @__PURE__ */ __name((file) => {
  if (!file) return false;
  return file?.type.startsWith("image/") || file?.type.startsWith("application/pdf");
}, "isFileTypeImageOrPdf");
function createShadowRoot(tagName, styles) {
  const container = document.createElement(tagName);
  const shadow = container.attachShadow({ mode: "open" });
  const globalStyleSheet = new CSSStyleSheet();
  globalStyleSheet.replaceSync(styles);
  shadow.adoptedStyleSheets = [globalStyleSheet];
  const html = document.querySelector("html");
  html.prepend(container);
  return createRoot(shadow);
}
__name(createShadowRoot, "createShadowRoot");

// util/timing.ts
function delay(e = 1e3) {
  return new Promise((t) => setTimeout(t, e));
}
__name(delay, "delay");
var blobToBase64 = /* @__PURE__ */ __name((blob) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise((resolve) => {
    reader.onloadend = () => {
      resolve(reader.result);
    };
  });
}, "blobToBase64");
var dataUrlToFile = /* @__PURE__ */ __name((dataUrl, filename) => {
  const arr = dataUrl.split(",");
  if (arr.length < 2) {
    return void 0;
  }
  const mimeArr = arr[0].match(/:(.*?);/);
  if (!mimeArr || mimeArr.length < 2) {
    return void 0;
  }
  const mime = mimeArr[1];
  const buff = Buffer.from(arr[1], "base64");
  return new File([buff], filename, { type: mime });
}, "dataUrlToFile");

// util/copy-to-clipboard.ts
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
  } catch {
    const textarea = document.createElement("textarea");
    textarea.style.position = "fixed";
    textarea.style.top = "-9999px";
    textarea.style.left = "-9999px";
    textarea.innerText = text;
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    document.execCommand("copy");
    textarea.remove();
  }
}
__name(copyToClipboard, "copyToClipboard");

// util/format-text.ts
var formatText = /* @__PURE__ */ __name((text) => {
  const camelToSpaces = text.replace(/([a-z])([A-Z])/g, "$1 $2");
  const snakeToSpaces = camelToSpaces.replace(/_/g, " ");
  return snakeToSpaces.split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
}, "formatText");
var formatCamelCaseText = /* @__PURE__ */ __name((text) => {
  const words = text.split(/(?=[A-Z])/);
  const formattedWords = words.map((word) => {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
  const result = formattedWords.join(" ");
  return result.charAt(0).toUpperCase() + result.slice(1);
}, "formatCamelCaseText");
var getVersionFromTool = /* @__PURE__ */ __name((toolRouterKey) => {
  if (toolRouterKey.version) {
    return toolRouterKey.version;
  }
  const parts = toolRouterKey.name.split(":::");
  if (parts.length === 4) {
    return parts[3];
  }
  return "latest";
}, "getVersionFromTool");
var submitRegistrationNoCodeNonPristineError = /* @__PURE__ */ __name(() => {
  return toast.error(
    /* @__PURE__ */ jsx("div", { children: "Your Hanzo Node is currently locked by existing keys, please restore your connection or reset your Hanzo Node Storage" }),
    { position: "bottom-center" }
  );
}, "submitRegistrationNoCodeNonPristineError");
var submitRegistrationNoCodeError = /* @__PURE__ */ __name(() => {
  return toast.error(/* @__PURE__ */ jsx("div", { children: "Error connecting to your Hanzo Node" }), {
    position: "bottom-center"
  });
}, "submitRegistrationNoCodeError");

// util/debounce.ts
var debounce = /* @__PURE__ */ __name((func, delay2) => {
  let timeoutId = null;
  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func(...args);
    }, delay2);
  };
}, "debounce");

// util/spread-to-transform.ts
function spreadToTransform(t) {
  let transformStrings = [];
  const scaleVal = "scale" in t ? t.scale : void 0;
  if (scaleVal) {
    if (typeof scaleVal === "number") {
      transformStrings.push(`scale(${scaleVal})`);
    } else if (Array.isArray(scaleVal) && scaleVal.length == 2 && typeof scaleVal[0] === "number") {
      transformStrings.push(`scale(${scaleVal[0]}, ${scaleVal[1]})`);
    } else {
      throw new Error("parsing MediaTransform: Unrecognized value for 'scale'!");
    }
  }
  return transformStrings.length > 0 ? { transform: transformStrings.join(" ") } : {};
}
__name(spreadToTransform, "spreadToTransform");
var spread_to_transform_default = spreadToTransform;

// util/specifier.ts
var getPrimaryStartingWith = /* @__PURE__ */ __name((s, toFind) => {
  const tokenArray = s.split(" ");
  return tokenArray.find((tok) => tok.startsWith(`${toFind}-`));
}, "getPrimaryStartingWith");
var getTShirtSize = /* @__PURE__ */ __name((s) => {
  const subTokenArray = s.split("-");
  return subTokenArray[subTokenArray.length - 1];
}, "getTShirtSize");
var getTypographySize = /* @__PURE__ */ __name((s) => {
  const subTokenArray = s.split("-");
  return subTokenArray[subTokenArray.length - 1];
}, "getTypographySize");
var getDim = /* @__PURE__ */ __name((s) => {
  const subTokenArray = s.split("-");
  const dimStr = subTokenArray[subTokenArray.length - 1];
  if (dimStr) {
    const dimTokenArray = s.split("x");
    return dimTokenArray ? {
      w: Number(dimTokenArray[0]),
      h: Number(dimTokenArray[1])
    } : void 0;
  }
  return void 0;
}, "getDim");
function getSpecifierData(main, getPrimary, getData, def) {
  const primary = getPrimary(main);
  if (primary) {
    return getData(primary) ?? def;
  }
  return def ?? void 0;
}
__name(getSpecifierData, "getSpecifierData");

// util/number-abbreviate.ts
var ABBR_SYMBOLS_ARRAY = ["K", "M", "B", "T"];
var MOBILE_BREAKPOINT = 768;
function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(void 0);
  React.useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
    const onChange = /* @__PURE__ */ __name(() => {
      setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
    }, "onChange");
    mql.addEventListener("change", onChange);
    setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
    return () => mql.removeEventListener("change", onChange);
  }, []);
  return !!isMobile;
}
__name(useIsMobile, "useIsMobile");
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
__name(cn, "cn");
function formatDate(input) {
  const date = new Date(input);
  return date.toLocaleDateString("en-US", {
    month: "long",
    day: "numeric",
    year: "numeric"
  });
}
__name(formatDate, "formatDate");
function absoluteUrl(path) {
  return `${process.env.NEXT_PUBLIC_APP_URL || ""}${path}`;
}
__name(absoluteUrl, "absoluteUrl");

// util/index.ts
function constrain(value, minOrConstrainTo, max) {
  if (typeof value === "number" && typeof minOrConstrainTo === "number" && typeof max === "number") {
    return Math.min(Math.max(value, minOrConstrainTo), max);
  }
  if (typeof value === "object" && typeof minOrConstrainTo === "object") {
    const dim = value;
    const constrainTo = minOrConstrainTo;
    const aspectRatio = dim.w / dim.h;
    const constrainAspectRatio = constrainTo.w / constrainTo.h;
    if (aspectRatio > constrainAspectRatio) {
      return {
        w: constrainTo.w,
        h: constrainTo.w / aspectRatio
      };
    } else {
      return {
        w: constrainTo.h * aspectRatio,
        h: constrainTo.h
      };
    }
  }
  throw new Error("Invalid parameters for constrain function");
}
__name(constrain, "constrain");
function round(value) {
  return Math.round(value * 100) / 100;
}
__name(round, "round");
function pxToRem(px, base = 16) {
  return `${px / base}rem`;
}
__name(pxToRem, "pxToRem");
function pxToEm(px, base = 16) {
  return `${px / base}em`;
}
__name(pxToEm, "pxToEm");
function containsToken(text, token) {
  if (!text) return false;
  return text.toLowerCase().includes(token.toLowerCase());
}
__name(containsToken, "containsToken");
function ldMerge(...objects) {
  const result = {};
  for (const obj of objects) {
    if (obj && typeof obj === "object") {
      Object.assign(result, obj);
    }
  }
  return result;
}
__name(ldMerge, "ldMerge");
function asNum(value, defaultValue = 0) {
  const num = Number(value);
  return isNaN(num) ? defaultValue : num;
}
__name(asNum, "asNum");
function capitalize(str) {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}
__name(capitalize, "capitalize");
var _MyStepAnimation = class _MyStepAnimation {
  /**  initialStep: false -> true: step 0
                        true -> false: step 1
           after intervals[0] : step 2
           after intervals[1] : step 3
  
          initialStep must contain at least one mobx observable and return boolean 
          see: https://mobx.js.org/reactions.html#reaction
      */
  constructor(initialStep, intervals) {
    this._step = -1;
    this._reactionDisposer = void 0;
    // This is separated out because reactions have to be created
    // once we have a valid doc / window etc. (mobx internals)
    // Can't just do it in constructor and assign to ref
    this.initialize = /* @__PURE__ */ __name(() => {
      const fireNext = /* @__PURE__ */ __name(() => {
        this._setStep(this._step + 1);
        if (this._step <= this._intervals.length) {
          setTimeout(() => {
            fireNext();
          }, this._intervals[this._step - 1]);
        }
      }, "fireNext");
      this._reactionDisposer = reaction(
        this._initialStep,
        (triggered) => {
          if (triggered && this._step === -1) {
            this._setStep(0);
          } else if (this._step === 0) {
            fireNext();
          }
        }
      );
    }, "initialize");
    this._setStep = /* @__PURE__ */ __name((v) => {
      this._step = v;
    }, "_setStep");
    this.dispose = /* @__PURE__ */ __name(() => {
      if (this._reactionDisposer) {
        this._reactionDisposer();
      }
    }, "dispose");
    // https://mobx.js.org/computeds-with-args.html#2-close-over-the-arguments
    this.notPast = /* @__PURE__ */ __name((step) => computed(() => this._step > -1 && this._step <= step).get(), "notPast");
    this._initialStep = initialStep;
    this._intervals = intervals;
    makeObservable(this, {
      _step: observable,
      _setStep: action
    });
  }
};
__name(_MyStepAnimation, "MyStepAnimation");
var MyStepAnimation = _MyStepAnimation;
var useStepAnimation = /* @__PURE__ */ __name((initialStep, intervals) => {
  const animRef = useRef(new MyStepAnimation(initialStep, intervals));
  useEffect(() => {
    animRef.current.initialize();
    return animRef.current.dispose;
  }, []);
  return animRef.current;
}, "useStepAnimation");

export { ABBR_SYMBOLS_ARRAY, absoluteUrl, asNum, blobToBase64, capitalize, cn, constrain, containsToken, copyToClipboard, createShadowRoot, dataUrlToFile, debounce, delay, formatCamelCaseText, formatDate, formatDateToLocaleStringWithTime, formatDateToMonthAndDay, formatDateToUSLocaleString, formatText, getDim, getFileExt, getFileName, getPrimaryStartingWith, getRelativeDateLabel, getSpecifierData, getTShirtSize, getTypographySize, getVersionFromTool, groupMessagesByDate, isFileTypeImageOrPdf, ldMerge, pxToEm, pxToRem, round, spread_to_transform_default as spreadToTransform, submitRegistrationNoCodeError, submitRegistrationNoCodeNonPristineError, useIsMobile, useStepAnimation };
