import type { FC, ReactNode } from 'react';
import type { BoxProps } from '../Box';

import Box from '../Box';

const AspectBox: FC<
  {
    containerAspect: number;
    aspect: number;
    children?: ReactNode;
  } & BoxProps
> = ({ aspect, containerAspect, children, ...boxProps }) => {
  // To always keep the container 'filled' (no horizontal/vertical black bars)
  // we have to change whether we scale relative to the container width or height.
  const fitToWidth = containerAspect <= aspect;

  return (
    <Box centerContent fullHeight {...boxProps}>
      <div
        style={{
          position: 'relative',
          flexShrink: 0,
          width: fitToWidth ? '100%' : '',
          height: fitToWidth ? 'auto' : '100%',
        }}
      >
        <svg
          viewBox={`0 0 1 ${aspect}`}
          style={{
            width: fitToWidth ? '100%' : '',
            height: fitToWidth ? 'auto' : '100%',
          }}
        />
        <Box coverParent>{children}</Box>
      </div>
    </Box>
  );
};

export default AspectBox;
