// @flow
import React from 'react';
import styled from 'styled-components';
import type { FieldSetProps } from './field-set.proptypes';
import { getSpacingRules } from '../../../mixins/spacing';
import { getStackedRules } from '../../../mixins/stacking';
import { getStackeeRules } from '../../../mixins/stackee';
import { FieldLabel } from '../../typography/field-label';

const StyledFieldSet = styled.fieldset`
  /* Resets: fieldset has some browser styling which we want to discard. */
  border: none;
  padding: 0.01em 0 0 0;
  margin: 0;
  min-width: 0;

  ${getSpacingRules}
  ${getStackedRules};
  ${getStackeeRules};
`;

const InvisibleLegend = styled.legend`
  &&& {
    position: absolute;
    overflow: hidden;
    clip: rect(0 0 0 0);
    height: 1px;
    width: 1px;
    margin: -1px;
    padding: 0;
    border: 0;
  }
`;

// Legend is needed for screen readers, but it's impossible to style.
// So we render it invisibly for screen readers and also render a visible
// version with custom styling. The visible version has `aria-hidden` to stop
// the text from being announced twice.
export const FieldSet = ({
  label,
  hideLabel,
  children,
  ...props
}: FieldSetProps) => (
  <StyledFieldSet {...props}>
    <InvisibleLegend>{label}</InvisibleLegend>
    {!hideLabel && (
      <FieldLabel aria-hidden spacing="mb2">
        {label}
      </FieldLabel>
    )}
    {children}
  </StyledFieldSet>
);

FieldSet.displayName = 'FieldSet';
