import { Box, Typography, type TypographyProps } from '@mui/material'
import type { Components } from 'react-markdown'
import { MarkdownContent } from './markdown-content'
import { styles } from './style'

export interface MarkdownUIProps {
  content: string
}

/** MUI-styled element mapping for `react-markdown`. */
const components: Components = {
  h1: (props) => mdHeading(props, 'h4'),
  h2: (props) => mdHeading(props, 'h5'),
  h3: (props) => mdHeading(props, 'h6'),
  h4: (props) => mdHeading(props, 'subtitle1'),
  h5: (props) => mdHeading(props, 'subtitle2'),
  h6: (props) => mdHeading(props, 'subtitle2'),
  p: ({ children }) => (
    <Typography variant='body2' component='p' sx={styles.paragraph}>
      {children}
    </Typography>
  ),
}

function mdHeading(
  props: { children?: React.ReactNode },
  variant: TypographyProps['variant'],
) {
  return (
    <Typography variant={variant} component='div' sx={styles.heading}>
      {props.children}
    </Typography>
  )
}

/**
 * Pure presentational component for the Markdown widget. Delegates the
 * `react-markdown` engine to {@link MarkdownContent} and supplies a
 * document-style MUI element mapping (body2 paragraphs, real heading
 * typography). Opts INTO raw HTML and inline images — the Markdown widget is
 * the one slot in the library where authors can ship rich content. Caption
 * slots like `Note` keep the conservative defaults.
 */
export function MarkdownUI({ content }: MarkdownUIProps) {
  return (
    <Box sx={styles.root}>
      <MarkdownContent
        content={content}
        components={components}
        allowHtml
        allowImages
      />
    </Box>
  )
}
