import { useState, useReducer, useEffect, useLayoutEffect } from "react";
const useClientsideEffect = typeof window === "undefined" ? () => {
} : useLayoutEffect;
function useScrolledToRight(scrollviewRef, options = {}) {
  const { thresholdPx = 8, disabled = false } = options;
  const [scrolledToRight, setScrolledToRight] = useState(false);
  const [transitionsAllowed, allowTransitions] = useReducer(() => true, false);
  useEffect(() => {
    if (disabled) return;
    let timeout;
    const handleScroll = () => {
      const scrollview2 = scrollviewRef.current;
      if (!scrollview2) return;
      const { scrollWidth, clientWidth, scrollLeft } = scrollview2;
      const newState = scrollLeft >= scrollWidth - clientWidth - thresholdPx;
      if (scrolledToRight !== newState) {
        if (!transitionsAllowed) allowTransitions();
        setScrolledToRight(newState);
      }
    };
    const addListener = () => {
      const scrollview2 = scrollviewRef.current;
      if (scrollview2) {
        if (timeout != null) window.clearTimeout(timeout);
        scrollview2.addEventListener("scroll", handleScroll, { passive: true });
      } else {
        timeout = window.setTimeout(() => addListener(), 1e3);
      }
    };
    addListener();
    const scrollview = scrollviewRef.current;
    return () => {
      if (timeout != null) window.clearTimeout(timeout);
      if (scrollview) scrollview.removeEventListener("scroll", handleScroll);
    };
  }, [scrolledToRight, scrollviewRef, thresholdPx, transitionsAllowed, disabled]);
  useClientsideEffect(() => {
    var _a;
    if (disabled) return;
    const scrollview = scrollviewRef.current;
    if (!scrollview) return;
    const childWidth = ((_a = scrollview.firstElementChild) == null ? void 0 : _a.clientWidth) || scrollview.clientWidth;
    if (Math.abs(scrollview.clientWidth - childWidth) < thresholdPx) {
      setScrolledToRight(true);
    }
  }, [scrollviewRef, disabled]);
  return { scrolledToRight, shouldTransition: transitionsAllowed };
}
export {
  useScrolledToRight
};
