import { useEffect } from 'react';

export const useMessageScrollObserver = (
  boxRef: React.RefObject<HTMLDivElement>,
  scrollRef: React.RefObject<HTMLDivElement>,
  onScrollChange: (position: number) => void,
) => {
  const calculateScrollHeight = () => {
    const boxHeight = boxRef?.current?.getBoundingClientRect().height || 0;
    const scrollHeight = scrollRef?.current?.getBoundingClientRect().height || 0;
    return boxHeight - scrollHeight;
  };

  const updateState = () => {
    const scrollHeight = calculateScrollHeight();
    if (scrollHeight > 0) {
      onScrollChange(scrollHeight);
    }
  };

  useEffect(() => {
    let boxRO = null;
    let scrollRO = null;

    if (scrollRef?.current) {
      boxRO = new ResizeObserver(updateState);
      boxRO.observe(scrollRef?.current);
    }

    if (boxRef?.current) {
      scrollRO = new ResizeObserver(updateState);
      scrollRO.observe(boxRef?.current);
    }

    return () => {
      if (scrollRef?.current && boxRO) {
        boxRO.unobserve(scrollRef?.current);
      }

      if (scrollRO && boxRef?.current) {
        scrollRO?.unobserve(boxRef?.current);
      }
    };
  }, []);
};
