// @flow
import React, { type StatelessFunctionalComponent } from 'react';
import styled from 'styled-components';
import type { GridProps } from './grid.proptypes';
import {
  gutterSize,
  containerPaddingSm,
  containerPaddingMd,
  containerPaddingLg,
} from './grid.css-rules';
import { bpXLarge, bpMedium, bpLarge } from '../../../breakpoints';

const GridInternals = styled.div`
  display: flex;
  flex-wrap: wrap;

  @media (min-width: ${bpMedium}) {
    margin-right: -${gutterSize};

    > * {
      box-sizing: border-box;

      /* over-compensate for gutter size while considering container padding */
      /* no overflow right now because gutterSize === containerPaddingSm */
      /* if gutterSize > containerPaddingSm we will have horizontal scrolling < bpMedium */
      padding-right: ${gutterSize};
    }
  }
`;

const GridWrapper = styled.div`
  /* center container */
  margin-left: auto;
  margin-right: auto;

  box-sizing: border-box;
  width: 100%;
  padding: 0 ${containerPaddingSm};

  @media (min-width: ${bpMedium}) {
    padding: 0 ${containerPaddingMd};
    max-width: ${bpMedium};
  }

  @media (min-width: ${bpLarge}) {
    padding: 0 ${containerPaddingLg};
    max-width: ${bpLarge};
  }

  @media (min-width: ${bpXLarge}) {
    padding: 0 ${containerPaddingLg};
    max-width: ${bpXLarge};
  }
`;

export const Grid: StatelessFunctionalComponent<GridProps> = styled(
  ({
    children,
    'data-qa': dataQa,
    'data-cy': dataCy,
    id,
    ...props
  }: GridProps) => (
    <GridWrapper data-cy={dataCy} data-qa={dataQa} {...props} id={id}>
      <GridInternals {...props}>{children}</GridInternals>
    </GridWrapper>
  ),
)``;

Grid.displayName = 'Grid';
