import React from 'react'

function highlightText(text, toHighlight) {
  if (!text) {
    return ''
  }
  try {
    const re = new RegExp(toHighlight, 'gi')
    return text.replace(re, `<mark>${toHighlight}</mark>`)
  } catch (e) {
    return text
  }
}

export default function Question({ question, searchTerm }) {
  let qdata = question.data
  if (typeof qdata === 'object' && qdata.type === 'simple') {
    qdata = ''
  }
  if (qdata) {
    try {
      qdata = JSON.stringify(qdata)
    } catch (e) {
      //
    }
  }

  const questionText = searchTerm
    ? highlightText(question.Q, searchTerm)
    : question.Q
  const answerText = searchTerm
    ? highlightText(question.A, searchTerm)
    : question.A

  return (
    <div className="questionContainer">
      <div className="question">{questionText}</div>
      <div className="answer">{answerText}</div>
      <div className="data">{qdata || null}</div>
    </div>
  )
}
