import { useState as L, useRef as T, useCallback as r, useEffect as u } from "react";
import { useDebounce as g } from "./useDebounce.js";
import { useZoomContext as A } from "../../contexts/ZoomContext.js";
const I = (n) => {
  const { currentZoom: p, setZoomLevel: w } = A(), [D, d] = L(0), a = g(D, 100), [o, b] = L(!1), c = T(null), i = r((e) => {
    d(e ? (t) => t + 3 : (t) => t - 3);
  }, []), f = r(
    (e) => {
      if (!e.ctrlKey)
        return;
      e.preventDefault();
      const t = e.deltaY < 0;
      i(t);
    },
    [i]
  );
  u(() => {
    if (a) {
      const e = Math.round(p * 100 + a);
      d(0), w(e > 25 ? e : 25);
    }
  }, [a]);
  const E = (e, t) => {
    const s = e.clientX - t.clientX, l = e.clientY - t.clientY;
    return Math.sqrt(s * s + l * l);
  }, h = r(
    (e) => {
      if (!o || e.touches.length !== 2)
        return;
      const t = E(e.touches[0], e.touches[1]);
      c.current = t, e.preventDefault();
    },
    [o]
  ), v = r(() => {
    c.current = null;
  }, []), m = r(
    (e) => {
      if (!o || e.touches.length !== 2 || c.current === null)
        return;
      const t = E(e.touches[0], e.touches[1]), s = t - c.current, l = Math.abs(s) > 5, S = s > 0;
      l && (i(S), c.current = t, e.preventDefault());
    },
    [i, o]
  ), y = () => {
    document.activeElement instanceof HTMLElement && document.activeElement.blur();
  };
  u(() => {
    if (o) {
      document.body.style.touchAction = "pan-x pan-y";
      return;
    }
    document.body.style.touchAction = "";
  }, [o]), u(() => {
    const e = () => {
      const t = document.activeElement, s = !!(t != null && t.closest('[data-rp="container"]'));
      b(s);
    };
    return window.addEventListener("focusin", e), window.addEventListener("focusout", e), e(), () => {
      window.removeEventListener("focusin", e), window.removeEventListener("focusout", e);
    };
  }, []), u(() => {
    if (!n)
      return;
    const e = (t) => {
      n.contains(t.target) || y();
    };
    return document.addEventListener("scroll", e), () => {
      document.removeEventListener("scroll", e);
    };
  }, [n]), u(() => {
    if (n)
      return n.addEventListener("wheel", f, { passive: !1 }), n.addEventListener("touchstart", h, { passive: !1 }), n.addEventListener("touchmove", m, { passive: !1 }), n.addEventListener("touchend", v, { passive: !1 }), () => {
        n.removeEventListener("wheel", f), n.removeEventListener("touchstart", h), n.removeEventListener("touchmove", m), n.removeEventListener("touchend", v);
      };
  }, [n, f, h, m, v]);
};
export {
  I as usePinch
};
