import { render, screen, fireEvent } from '@testing-library/react'
import { GroupedNav, type GroupedNavEntry } from '../grouped-nav'

const items: GroupedNavEntry[] = [
  { href: '/', label: 'Dashboard' },
  {
    label: 'Content',
    items: [
      { href: '/t/weekly_brief', label: 'Weekly Briefs' },
      { href: '/t/lead_magnet', label: 'Lead Magnets' },
      { href: '/t/general', label: 'General' },
    ],
  },
]

describe('GroupedNav', () => {
  it('renders top-level links and grouped links', () => {
    render(<GroupedNav items={items} activeHref="/" />)
    expect(screen.getByText('Dashboard')).toBeInTheDocument()
    expect(screen.getByText('Content')).toBeInTheDocument()
    expect(screen.getByText('Weekly Briefs')).toBeInTheDocument()
    expect(screen.getByText('General')).toBeInTheDocument()
  })

  it('marks the active link with aria-current=page', () => {
    render(<GroupedNav items={items} activeHref="/t/lead_magnet" />)
    expect(screen.getByRole('link', { name: 'Lead Magnets' })).toHaveAttribute('aria-current', 'page')
    expect(screen.getByRole('link', { name: 'Weekly Briefs' })).not.toHaveAttribute('aria-current')
  })

  it('treats a child path as active for its link', () => {
    render(<GroupedNav items={items} activeHref="/t/general/42" />)
    expect(screen.getByRole('link', { name: 'General' })).toHaveAttribute('aria-current', 'page')
  })

  it('collapses and expands a group on heading click', () => {
    render(<GroupedNav items={items} activeHref="/" />)
    expect(screen.getByText('Weekly Briefs')).toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: /Content/ }))
    expect(screen.queryByText('Weekly Briefs')).not.toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: /Content/ }))
    expect(screen.getByText('Weekly Briefs')).toBeInTheDocument()
  })

  it('forces a collapsed group open when one of its children is active', () => {
    const collapsed: GroupedNavEntry[] = [
      { label: 'Content', defaultOpen: false, items: [{ href: '/t/general', label: 'General' }] },
    ]
    render(<GroupedNav items={collapsed} activeHref="/t/general" />)
    // defaultOpen=false but the active child forces it visible
    expect(screen.getByText('General')).toBeInTheDocument()
  })

  it('uses a custom renderLink (e.g. a router Link)', () => {
    render(
      <GroupedNav
        items={items}
        activeHref="/"
        renderLink={({ link, active, className }) => (
          <a href={link.href} className={className} data-active={active} data-router-link="1">
            {link.label}
          </a>
        )}
      />,
    )
    const link = screen.getByText('Weekly Briefs')
    expect(link).toHaveAttribute('data-router-link', '1')
  })
})
