import { isIOS } from "src/utils/isDevice";

// setSelectionRange throws InvalidStateError on input types other than
// text/search/url/tel/password (e.g. email, number).
const supportsSelection = (
  el: HTMLInputElement | HTMLTextAreaElement,
): boolean => {
  if (el instanceof HTMLTextAreaElement) return true;
  return ["text", "search", "url", "tel", "password"].includes(el.type);
};

export const focusElement = (
  el?: HTMLInputElement | HTMLTextAreaElement | null,
) => {
  if (!isIOS()) {
    el?.focus();
    return;
  }

  let fakeInput = document.createElement("input");
  fakeInput.setAttribute("type", "text");
  fakeInput.style.position = "fixed";
  fakeInput.style.height = "0px";
  fakeInput.style.width = "0px";
  fakeInput.style.fontSize = "16px"; // disable auto zoom
  document.body.appendChild(fakeInput);
  fakeInput.focus();
  setTimeout(() => {
    if (!el) return;
    el.style.transform = "translateY(-2000px)";
    el?.focus();
    fakeInput.remove();
    el.value = " ";
    if (supportsSelection(el)) el.setSelectionRange(1, 1);
    requestAnimationFrame(() => {
      if (el) {
        el.style.transform = "";
      }
    });
    setTimeout(() => {
      if (!el) return;
      el.value = "";
      if (supportsSelection(el)) el.setSelectionRange(0, 0);
    }, 50);
  }, 20);
};
