import React from 'react'

type TimestampProps = {
  publishedTimestamp: string
  textCase?: 'sentence'
}

const TimeStamp: React.FC<TimestampProps> = ({
  publishedTimestamp,
  textCase,
}) => {
  const now = new Date()
  const oneDay = 24 * 60 * 60 * 1000
  const date = new Date(publishedTimestamp)
  const formatted = date.toLocaleString()

  let format: string

  if (now.getTime() - date.getTime() < oneDay) {
    // display published date in 'xx minutes ago' format
    // and render exact time next to it
    format = 'time-ago-no-seconds'
  } else {
    // don't display time string if the post is older than one day
    // because it is already included in the formatted timestamp
    format = 'MMM dd, HH:mm'
  }

  return (
    <span className="x-live-blog-post__timestamp-container o3-type-detail">
      <time
        data-o-component="o-date"
        className="o-date"
        dateTime={publishedTimestamp}
        data-o-date-format={format}
        data-o-date-text-case={textCase}
        itemProp="datePublished"
      >
        <span data-o-date-printer>{formatted}</span>
      </time>
    </span>
  )
}

export default TimeStamp
