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

import DomContext from '@/react/context/dom-scale.js';
import {RESOLUTION} from '@/util/constants.js';

import styles from './dom.module.css';

/**
 * Dom autoscales with resolution.
 */
export default function Dom({children}) {
  const ref = useRef();
  const [scale, setScale] = useState(0);
  useEffect(() => {
    if (!ref.current) {
      return;
    }
    function onResize() {
      const {parentNode} = ref.current;
      const {width} = parentNode.getBoundingClientRect();
      setScale(width / RESOLUTION.x);
    }
    window.addEventListener('resize', onResize);
    onResize();
    return () => {
      window.removeEventListener('resize', onResize);
    }
  });
  return (
    <div className={styles.dom} ref={ref}>
      {scale > 0 && (
        <style>{`
          .${styles.dom}{
            --scale: ${scale};
          }
        `}</style>
      )}
      <DomContext.Provider value={scale}>
        {children}
      </DomContext.Provider>
    </div>
  );
}

