import React from 'react'
import RichText from '../../RichText'
import type { BodyProps } from '../../Body'

type PodcastBodyProps = BodyProps & {
  showPlayer?: boolean
  showAccessibilityGuide?: boolean
}

const PodcastBody: React.FC<PodcastBodyProps> = ({
  content,
  richTextComponents,
  showPlayer = true,
  showAccessibilityGuide = true,
}) => {
  if (content.__typename !== 'Audio') {
    return null
  }
  const podcastMediaType = 'audio/mpeg'
  const podcast = content.media?.find(
    (media) => media?.mediaType === podcastMediaType
  )

  return (
    <div
      // HACK:20230712:IM use next-article's CSS classes until we bundle styles
      className="article__content-body n-content-body js-article__content-body o3-type-body-content-base"
      data-trackable="article-body"
      data-attribute="article-content-body"
    >
      {showPlayer && podcast?.url && (
        <div className="article__media">
          <audio
            controls
            data-o-component="o-audio"
            data-audio-subtype="podcast"
            data-content-id={content.id}
            data-dispatch-listened-event-on-unload
          >
            <source src={podcast.url} type={podcastMediaType} />
            <p>
              Your browser does not support playing this file but you can still{' '}
              <a href={podcast.url}>download the MP3 file</a> to play locally.
            </p>
          </audio>
        </div>
      )}

      {content.body?.structured && (
        <article className="n-content-body o3-type-body-content-base">
          <RichText
            structuredContent={content.body.structured}
            components={richTextComponents}
          />
          {showAccessibilityGuide && (
            <p>
              <a href="/accessibility#podcast-transcriptions">
                View our accessibility guide
              </a>
              .
            </p>
          )}
        </article>
      )}
    </div>
  )
}

export default PodcastBody
