import { renderOptions } from "./renderOptions"

import JsonToHtml from "@/components/JsonToHtml"
import Link from "next/link"

import styles from "./puff.module.css"

import type { PuffProps } from "@/types/components/current/asides/puff"
import Image from "@/components/Image"

export default function Puff({ imageConnection, is_internal, link, link_text, pageConnection, text, title }: PuffProps) {
  if (is_internal) {
    const page = pageConnection.edges[0]
    if (!page?.node?.url) {
      return null
    }
    return (
      <Link className={styles.link} href={page.node.url}>
        <PuffContent
          imageConnection={imageConnection}
          text={text}
          title={title}
        />
      </Link>
    )
  }
  return (
    <a className={styles.link} href={link.href} target="_blank">
      <PuffContent
        imageConnection={imageConnection}
        text={text}
        title={title}
      />
    </a>
  )
}


function PuffContent({ imageConnection, text, title }: Pick<PuffProps, "imageConnection" | "text" | "title">) {
  return (
    <article>
      {imageConnection.edges.map(image => (
        <Image
          alt={image.node.title}
          className={styles.image}
          height={image.node.dimension.height}
          key={image.node.system.uid}
          src={image.node.url}
          width={image.node.dimension.width}
        />
      ))}
      <section className={styles.content}>
        <header className="content-teaser__body-wrapper">
          <h3 className={styles.heading}>
            {title}
          </h3>
        </header>
        <JsonToHtml
          embeds={text.embedded_itemsConnection.edges}
          nodes={text.json.children}
          renderOptions={renderOptions}
        />
      </section>
    </article>
  )
}