/*
    MainImage component renders the main image of a Topper.
    It uses the leadImages for consistency with other toppers but
    it will be rendered as Main Image in the content area, instead of in the topper area.
*/
import React from 'react'
import type { TopperFragment } from '@financial-times/cp-content-pipeline-client'
import { Sources } from '../content-tree/ImageSet'
import { ContentTree } from '@financial-times/content-tree'
import { PictureOverrideWrapper } from '../ImageOverrideWrappers'

export type TopperMainImageProps = {
  topper: TopperFragment
  hasValidTopperType: boolean
}

// It outputs the same markup of the MainImage component.
// This component should be temporary. When the article will support a shared grid between content and topper,
// we will have a single component to render all the images in a topper.
// The two components are this one and the Picture component in the Topper folder.
const TopperMainImage: React.FC<TopperMainImageProps> = (props) => {
  const { topper } = props

  // This topper is currently used only for simple topper types when they use leadImages
  if (
    !topper ||
    !('images' in topper) ||
    !topper.fallbackImage ||
    !props.hasValidTopperType
  ) {
    return null
  }

  return (
    <figure
      className="n-content-image n-content-image--full"
      data-component="topper-main-image"
    >
      <picture>
        <PictureOverrideWrapper {...props}>
          <Sources images={topper.images as readonly ContentTree.Image[]} />
          <img
            // ts is this shape so we can update templates before api
            // can be simplified to alt={topper.fallbackImage.altText || ''}
            alt={
              (topper.fallbackImage as { altText?: string } | null | undefined)
                ?.altText || ''
            }
            src={topper.fallbackImage.sourceSet[0]?.url}
            key="fallback-image"
            width={topper.fallbackImage.width ?? undefined}
            height={topper.fallbackImage.height ?? undefined}
          />
        </PictureOverrideWrapper>
      </picture>
      {(topper.fallbackImage.caption || topper.fallbackImage.credit) && (
        <figcaption className="n-content-picture__caption o3-editorial-typography-caption">
          <span>{topper.fallbackImage.caption}</span>
          <span>
            {topper.fallbackImage.caption ? ' ' : ''}
            {topper.fallbackImage.credit}
          </span>
        </figcaption>
      )}
    </figure>
  )
}

export default TopperMainImage
