import { useState, useLayoutEffect, useRef } from 'react';
let hookUsagesCount = 0;
let fontSizeElement = null;
function getFontSizeElement() {
  if (!fontSizeElement) {
    fontSizeElement = document.createElement('span');
    fontSizeElement.id = 'font-size-change-tracking-element';
    fontSizeElement.innerText = 'font size change tracking';
    fontSizeElement.style.visibility = 'hidden';
    fontSizeElement.style.position = 'absolute';
    fontSizeElement.style.top = '-9999px';
    fontSizeElement.style.left = '-9999px';
    document.body.appendChild(fontSizeElement);
  }
  return fontSizeElement;
}
export function getFontSize(element) {
  return parseFloat(window.getComputedStyle(element).fontSize);
}

/** Track browser font-size changes, updated via Chrome's settings. (Settings -> Appearance -> Font-size) */
export const useFontSizeObserver = () => {
  const [size, setSize] = useState({
    previousSize: 0,
    currentSize: 0
  });
  const fontSizeElementRef = useRef();
  useLayoutEffect(() => {
    hookUsagesCount++;
    if (!fontSizeElementRef.current) {
      fontSizeElementRef.current = getFontSizeElement();
    }
    const observer = new ResizeObserver(() => {
      const fontSize = getFontSize(fontSizeElementRef.current);
      setSize(prevState => ({
        previousSize: prevState.currentSize || fontSize,
        currentSize: fontSize
      }));
    });
    observer.observe(fontSizeElementRef.current);
    return () => {
      observer.disconnect();
      if (hookUsagesCount === 0 && fontSizeElementRef.current) {
        document.body.removeChild(fontSizeElementRef.current);
      }
      hookUsagesCount--;
    };
  }, []);
  return size;
};