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

import {RESOLUTION} from '@/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[0]);
    }
    window.addEventListener('resize', onResize);
    onResize();
    return () => {
      window.removeEventListener('resize', onResize);
    }
  }, [ref.current]);
  return (
    <div className={styles.dom} ref={ref}>
      {scale > 0 && (
        <style>{`.${styles.dom}{--scale:${scale}}`}</style>
      )}
      {children}
    </div>
  );
}

