const runWhenReady = (callback: () => void) => {
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", callback, { once: true });
    return;
  }

  callback();
};

const typewriterEffect = (selector: string) => {
  const typedTextContainer = document.querySelector<HTMLDivElement>(selector);

  if (!typedTextContainer) {
    return;
  }

  const text = typedTextContainer.innerText;
  const followingPromptLine = typedTextContainer.parentElement?.querySelector<HTMLElement>(
    ".devcm-prompt-line--after-typed"
  );

  typedTextContainer.innerText = "";
  typedTextContainer.classList.add("typed-text--typing");
  typedTextContainer.classList.remove("typed-text--complete");
  followingPromptLine?.classList.add("devcm-prompt-line--pending");
  followingPromptLine?.setAttribute("aria-hidden", "true");

  let index = 0;

  const typeNextCharacter = () => {
    if (index >= text.length) {
      typedTextContainer.classList.remove("typed-text--typing");
      typedTextContainer.classList.add("typed-text--complete");
      followingPromptLine?.classList.remove("devcm-prompt-line--pending");
      followingPromptLine?.removeAttribute("aria-hidden");
      return;
    }

    typedTextContainer.innerText += text.charAt(index);
    index += 1;

    window.setTimeout(typeNextCharacter, Math.random() * 200 + 50);
  };

  typeNextCharacter();
};

export const initTypedText = (selector = ".typed-text") => {
  runWhenReady(() => typewriterEffect(selector));
};
