import React, { useEffect, useMemo, useRef, useState } from 'react';
import './index.scss';
interface IllustrationI {
  src: string;
  sizes: number[];
}

const getSize = (sizes: number[]): number => {
  const screenWidth: number = window.innerWidth;
  if (screenWidth <= 1280) {
    return sizes?.[0] ?? 448;
  }
  if (screenWidth > 1280 && screenWidth <= 1920) {
    return sizes?.[1] ?? 560;
  }
  return sizes?.[2] ?? 672;
};

export default function Illustration(props: IllustrationI) {
  const { src, sizes } = props;

  const [size, setSize] = useState(getSize(sizes));
  const sizeRecord = useRef(size);
  useMemo(() => {
    sizeRecord.current = size;
  }, [size]);

  useEffect(() => {
    window.onresize = () => {
      const nowSize = getSize(sizes);
      if (nowSize !== sizeRecord.current) {
        setSize(nowSize);
      }
    };
  }, []);

  return (
    <img
      className='op-illustration'
      style={{ width: size, height: size }}
      src={src}
      alt=''
    />
  );
}
