import React from 'react'
import { useSelector } from 'react-redux'
import classNames from 'classnames'

import { getNextSmallerNumber } from '../lib/array-util.js'
import {
  selectParsedText,
  selectCurrentSegmentIndex
} from '../store/selectors.js'

import styles from './TextOutput.css'

export const TextOutput = () => {
  const { segments, sentences, words } = useSelector(selectParsedText)
  const curSegment = useSelector(selectCurrentSegmentIndex)
  return (
    <div>
      {segments.map((segment, idx) => {
        const isCurrent = curSegment === idx
        const isWordStart = words.includes(idx)
        const wordBeginning = isWordStart
          ? idx
          : getNextSmallerNumber(idx, words)
        const isSentenceStart = sentences.includes(wordBeginning)

        return (
          <span
            key={idx}
            className={classNames({
              [styles.current]: isCurrent,
              [styles.sentenceBeginning]: isSentenceStart
            })}
          >
            {isWordStart && ' '}
            {segment}
          </span>
        )
      })}
    </div>
  )
}
