// @flow
import React from 'react';

import { Span } from '../../core/typography/span';
import { type InlineStyledTextProps } from './inline-styled-text.proptypes';
import { type SpanProps } from '../../core/typography/span/span.proptypes';
import { splitStyledTextByToken } from './inline-styled-text.helpers';

const combinedSpanProps = (base: ?SpanProps, inline: ?SpanProps): SpanProps => {
  // $FlowFixMe - manual typecasting to work around https://github.com/facebook/flow/issues/8186
  return ({ ...(base: Object), ...inline }: SpanProps);
};

export const InlineStyledText = ({
  text,
  baseSpanProps,
  inlineSpanProps,
}: InlineStyledTextProps) => {
  const textSegments = splitStyledTextByToken(text);

  const combined = combinedSpanProps(baseSpanProps, inlineSpanProps);

  if (textSegments.length === 1) {
    const [onlySegment] = textSegments;

    return (
      <Span {...(onlySegment.applyInlineStyle ? combined : baseSpanProps)}>
        {onlySegment.text}
      </Span>
    );
  }

  return (
    <>
      {textSegments.map(
        (segment) =>
          segment.text.length > 0 && (
            <Span
              key={segment.text}
              {...(segment.applyInlineStyle ? combined : baseSpanProps)}
            >
              {segment.text}
            </Span>
          ),
      )}
    </>
  );
};

InlineStyledText.displayName = 'InlineStyledText';
