import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';

import { TableOfContents } from './TableOfContents';

describe('TableOfContents', () => {
  it('renders headings from HTML content', () => {
    const html = `
      <h2>Introduction</h2>
      <p>Some text</p>
      <h2>Getting Started</h2>
      <h3>Installation</h3>
      <h2>Conclusion</h2>
    `;

    render(<TableOfContents html={html} />);

    expect(screen.getByText('Table of Contents')).toBeInTheDocument();
    expect(screen.getByText('Introduction')).toBeInTheDocument();
    expect(screen.getByText('Getting Started')).toBeInTheDocument();
    expect(screen.getByText('Installation')).toBeInTheDocument();
    expect(screen.getByText('Conclusion')).toBeInTheDocument();
  });

  it('returns null when fewer headings than minHeadings', () => {
    const html = '<h2>Only One</h2><h2>Two</h2>';

    const { container } = render(<TableOfContents html={html} />);

    expect(container.innerHTML).toBe('');
  });

  it('renders with custom minHeadings threshold', () => {
    const html = '<h2>First</h2><h2>Second</h2>';

    render(<TableOfContents html={html} minHeadings={2} />);

    expect(screen.getByText('First')).toBeInTheDocument();
    expect(screen.getByText('Second')).toBeInTheDocument();
  });

  it('generates correct anchor links', () => {
    const html = '<h2>My Heading Title</h2><h2>Another One</h2><h2>Third</h2>';

    render(<TableOfContents html={html} />);

    const link = screen.getByText('My Heading Title');
    expect(link.closest('a')).toHaveAttribute('href', '#my-heading-title');
  });

  it('indents h3 headings', () => {
    const html = `
      <h2>Parent</h2>
      <h3>Child</h3>
      <h2>Another Parent</h2>
    `;

    render(<TableOfContents html={html} />);

    const childItem = screen.getByText('Child').closest('li');
    expect(childItem).toHaveClass('ml-4');

    const parentItem = screen.getByText('Parent').closest('li');
    expect(parentItem).not.toHaveClass('ml-4');
  });

  it('strips inline HTML from heading text', () => {
    const html = `
      <h2><strong>Bold</strong> Heading</h2>
      <h2>Normal Heading</h2>
      <h2>Third Heading</h2>
    `;

    render(<TableOfContents html={html} />);

    expect(screen.getByText('Bold Heading')).toBeInTheDocument();
  });

  it('has correct aria-label for accessibility', () => {
    const html = '<h2>One</h2><h2>Two</h2><h2>Three</h2>';

    render(<TableOfContents html={html} />);

    expect(screen.getByRole('navigation', { name: 'Table of contents' })).toBeInTheDocument();
  });
});
