// @flow
import React 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';
import type { PatchworkComponent } from '../../../types';

const GridInternals = styled.div`
  display: flex;
  flex-wrap: wrap;
  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: PatchworkComponent<GridProps> = styled(
  ({ children, ...props }: GridProps) => (
    <GridWrapper {...props}>
      <GridInternals {...props}>{children}</GridInternals>
    </GridWrapper>
  ),
)``;

Grid.displayName = 'Grid';
