import { useReducer as N, useRef as V, useLayoutEffect as x, useEffect as R } from "react";
const A = (r) => {
  const [, E] = N((e) => e + 1, 0), l = V(null), {
    replace: i,
    append: g
  } = r, f = i ? i(r.format(r.value)) : r.format(r.value), m = V(!1), k = (e) => {
    if (process.env.NODE_ENV !== "production" && (e.target.type === "number" || e.target.type === "date"))
      return;
    const t = e.target.value;
    if (l.current = [
      t,
      // eventValue
      e.target,
      // input
      t.length > f.length,
      // isSizeIncreaseOperation
      m.current,
      // isDeleleteButtonDown
      f === r.format(t)
      // isNoOperation
    ], process.env.NODE_ENV !== "production") {
      const o = r.format(t);
      t !== o && (t.toLowerCase(), o.toLowerCase());
    }
    E();
  };
  return (process.env.NODE_ENV === "production" || typeof window < "u") && x(() => {
    if (l.current == null) return;
    let [
      e,
      t,
      o,
      y,
      // No operation means that value itself hasn't been changed, BTW cursor, selection etc can be changed
      v
    ] = l.current;
    l.current = null;
    const p = y && v, D = e.slice(t.selectionStart).search(r.accept || /\d/g), L = D !== -1 ? D : 0, c = (n) => (n.match(r.accept || /\d/g) || []).join(""), h = c(e.substr(0, t.selectionStart)), S = (n) => {
      let s = 0, u = 0;
      for (let d = 0; d !== h.length; ++d) {
        let O = n.indexOf(h[d], s) + 1, w = c(n).indexOf(h[d], u) + 1;
        w - u > 1 && (O = s, w = u), u = Math.max(w, u), s = Math.max(s, O);
      }
      return s;
    };
    if (r.mask === !0 && o && !v) {
      let n = S(e);
      const s = c(e.substr(n))[0];
      n = e.indexOf(s, n), e = `${e.substr(0, n)}${e.substr(n + 1)}`;
    }
    let a = r.format(e);
    g != null && // cursor at the end
    t.selectionStart === e.length && !v && (o ? a = g(a) : c(a.slice(-1)) === "" && (a = a.slice(0, -1)));
    const C = i ? i(a) : a;
    return f === C ? E() : r.onChange(C), () => {
      let n = S(a);
      if (r.mask != null && (o || y && !p))
        for (; a[n] && c(a[n]) === ""; )
          n += 1;
      t.selectionStart = t.selectionEnd = n + (p ? 1 + L : 0);
    };
  }), R(() => {
    const e = (o) => {
      o.code === "Delete" && (m.current = !0);
    }, t = (o) => {
      o.code === "Delete" && (m.current = !1);
    };
    return document.addEventListener("keydown", e), document.addEventListener("keyup", t), () => {
      document.removeEventListener("keydown", e), document.removeEventListener("keyup", t);
    };
  }, []), {
    value: l.current != null ? l.current[0] : f,
    onChange: k
  };
};
export {
  A as useRifm
};
