import {
  DefinitionItem,
  DefinitionList,
} from '@/components/Markdoc/DefinitionList'
import { Highlight } from '@/components/Markdoc/Highlight'
import { tags } from '@/lib/markdoc/tags'
import type { Node } from '@markdoc/markdoc'
import Markdoc from '@markdoc/markdoc'
import React from 'react'

import styles from './Renderer.module.css'

interface ContentRendererProps {
  content: () => Promise<{ node: Node }>
  className?: string
}

export default async function Renderer({
  content,
  className = 'content',
}: ContentRendererProps) {
  const components = {
    DefinitionList,
    DefinitionItem,
    Highlight,
  }
  const { node } = await content()
  const errors = Markdoc.validate(node, { tags })

  if (errors.length) {
    console.error(errors)
    throw new Error('Invalid content')
  }

  const renderable = Markdoc.transform(node, { tags })

  return (
    <div className={`${styles.content} ${className}`}>
      {Markdoc.renderers.react(renderable, React, { components })}
    </div>
  )
}
