import { useState, useRef, useEffect } from 'react';

export const useCellWidth = () => {
  const [width, setWidth] = useState(0);
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const getWidth = () => {
      if (ref.current) {
        setWidth(ref.current.offsetWidth);
      }
    };

    let prevPixelRatio = window.devicePixelRatio;

    const handleZoomOrResize = () => {
      if (prevPixelRatio !== window.devicePixelRatio) {
        prevPixelRatio = window.devicePixelRatio;
        getWidth();
      }
    };

    const resizeObserver = new ResizeObserver(getWidth);
    if (ref.current) {
      resizeObserver.observe(ref.current);
    }

    window.addEventListener('resize', handleZoomOrResize);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', handleZoomOrResize);
    };
  }, [setWidth]);

  return { ref, width };
};
