import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MarkdownUI } from './markdown-ui'

describe('<MarkdownUI>', () => {
  it('renders headings, paragraphs, and inline emphasis', () => {
    render(
      <MarkdownUI
        content={'# Title\n\nSome **bold** text and _italic_ text.'}
      />,
    )
    expect(screen.getByText('Title')).toBeTruthy()
    expect(screen.getByText('bold')).toBeTruthy()
    expect(screen.getByText('italic')).toBeTruthy()
  })

  it('renders lists', () => {
    render(<MarkdownUI content={'- one\n- two\n- three'} />)
    expect(screen.getByText('one')).toBeTruthy()
    expect(screen.getByText('two')).toBeTruthy()
    expect(screen.getByText('three')).toBeTruthy()
  })

  it('renders links', () => {
    render(<MarkdownUI content={'[CARTO](https://carto.com)'} />)
    const link = screen.getByRole('link', { name: 'CARTO' })
    expect(link.getAttribute('href')).toBe('https://carto.com')
  })

  it('renders inline images', () => {
    const { container } = render(
      <MarkdownUI
        content={'![alt text](https://example.com/img.png)\n\nplain text'}
      />,
    )
    const img = container.querySelector('img')
    expect(img).not.toBeNull()
    expect(img?.getAttribute('src')).toBe('https://example.com/img.png')
    expect(img?.getAttribute('alt')).toBe('alt text')
    expect(screen.getByText('plain text')).toBeTruthy()
  })

  it('renders raw HTML', () => {
    const { container } = render(
      <MarkdownUI
        content={'<span>inline <em>html</em></span>\n\nplain text'}
      />,
    )
    // Sanitizer keeps safe inline tags; only `data-*` attrs are stripped.
    expect(container.querySelector('span')).not.toBeNull()
    expect(container.querySelector('em')?.textContent).toBe('html')
    expect(container.textContent).toContain('inline html')
    expect(screen.getByText('plain text')).toBeTruthy()
  })

  it('renders empty content without errors', () => {
    const { container } = render(<MarkdownUI content='' />)
    // Root box exists, but no markdown elements inside.
    expect(container.querySelector('p, h1, h2, h3')).toBeNull()
  })

  it('maps every heading level (h1–h6) through MUI Typography', () => {
    const { getByText } = render(
      <MarkdownUI
        content={'# H1\n\n## H2\n\n### H3\n\n#### H4\n\n##### H5\n\n###### H6'}
      />,
    )
    expect(getByText('H1')).toBeTruthy()
    expect(getByText('H2')).toBeTruthy()
    expect(getByText('H3')).toBeTruthy()
    expect(getByText('H4')).toBeTruthy()
    expect(getByText('H5')).toBeTruthy()
    expect(getByText('H6')).toBeTruthy()
  })
})
