import { useEffect, useState } from 'react';
import debounce from 'lodash/debounce';

export default function useSizeByDomId(id?: string) {
  const [state, setState] = useState({
    width: id ? document.getElementById(id)?.clientWidth : document.body.clientWidth,
    height: id ? document.getElementById(id)?.clientHeight : document.body.clientHeight,
  });

  useEffect(() => {
    const target = id ? document.getElementById(id) : document.body;
    if (window.ResizeObserver) {
      const resizeObserver = new ResizeObserver(
        debounce((entries) => {
          setState({
            width: entries[0].target.clientWidth,
            height: entries[0].target.clientHeight,
          });
        }, 100),
      );
      resizeObserver.observe(target);
      return () => {
        resizeObserver.unobserve(target);
      };
    } else {
      const handler = () => {
        setState({
          width: target.clientWidth,
          height: target.clientHeight,
        });
      };
      window.addEventListener('resize', handler);
      return () => {
        window.removeEventListener('resize', handler);
      };
    }
  }, []);

  return state;
}
