import { useCallback, useState } from 'react';

export type Dimensions = { width: number; height: number };

export const defaultDimensions = { width: 0, height: 0 };

/**
 * @deprecated
 * Use `useDimensions` from material-hu instead.
 */
export const useDimensions = () => {
  const [dimensions, setDimensions] = useState<Dimensions>(defaultDimensions);

  const ref = useCallback((node: HTMLElement | null) => {
    if (!node) return;

    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        const element = entry.target as HTMLElement;

        setDimensions({
          width: element.offsetWidth || 0,
          height: element.offsetHeight || 0,
        });
      }
    });

    resizeObserver.observe(node);

    return () => {
      resizeObserver.unobserve(node);
    };
  }, []);

  return {
    ref,
    dimensions,
  };
};

export default useDimensions;
