export function createTextDetector(applyStyle: (element: HTMLDivElement) => void) {
  const container = document.createElement("div");
  container.style.position = "absolute";
  container.style.top = "-9999px";
  container.style.left = "-9999px";
  applyStyle(container);
  document.body.appendChild(container);
  let destroyed = false;

  const detector = {
    applyContainer(apply: (element: HTMLDivElement) => void) {
      apply(container);
      return this;
    },
    applyText(text: string) {
      if (destroyed) {
        throw new Error("text container has been destroyed");
      }
      container.textContent = text;
      return this;
    },
    getWidth: () => {
      return container.getBoundingClientRect().width;
    },
    getHeight: () => {
      return container.getBoundingClientRect().height;
    },
    destroy() {
      destroyed = true;
      container.parentElement?.removeChild(container);
    },
  };

  return detector;
}
