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

import Dom from '@/components/dom.jsx';
import {RESOLUTION} from '@/constants.js';

function Decorator({children, style}) {
  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
      ref={ref}
      style={{
        backgroundColor: '#1099bb',
        opacity: 0 === scale ? 0 : 1,
        position: 'relative',
        height: `calc(${RESOLUTION[1]}px * ${scale})`,
        width: '100%',
      }}
    >
      <Dom>
        <div style={style}>
          {children}
        </div>
      </Dom>
    </div>
  );
}

export default function(options = {}) {
  return function decorate(Decorating) {
    return (
      <Decorator style={options.style}>
        <Decorating />
      </Decorator>
    );
  };
}
