// @flow
import React from 'react';

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

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

  const inlineSpanProps = { ...baseSpanProps, ..._inlineSpanProps };

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

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

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

InlineStyledText.displayName = 'InlineStyledText';
