import * as React from "react";

const BASE = 1000;
const FACTOR = 0.8;

const INITIAL_STATE: React.CSSProperties = {
  visibility: "hidden",
  position: "absolute",
  fontSize: `${BASE}px`,
  lineHeight: `${BASE}px`,
  height: "auto",
  width: "auto",
  textAlign: "center",
  whiteSpace: "nowrap",
};

interface Props {
  width: number;
  height: number;
  style?: React.CSSProperties;
}

export const FitText: React.FC<Props> = ({
  width,
  height,
  style,
  children,
}) => {
  const element = React.useRef(null);

  React.useEffect(() => {
    if (element.current && width > 0 && height > 0) {
      Object.assign(element.current.style, INITIAL_STATE);

      const factor = Math.max(
        element.current.offsetWidth / width,
        element.current.offsetHeight / height
      );

      const fontSize = Math.floor((BASE / factor) * FACTOR);

      Object.assign(element.current.style, {
        visibility: "visible",
        position: "static",
        fontSize: fontSize + "px",
        lineHeight: height + "px",
        height: height + "px",
        width: width + "px",
        textAlign: "center",
        whiteSpace: "nowrap",
      });
    }
  }, [element.current, width, height, children]);

  return (
    <div ref={element} style={style}>
      {children}
    </div>
  );
};
