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

const { mockUsePathname } = vi.hoisted(() => ({
  mockUsePathname: vi.fn(),
}));

const { mockUseApi } = vi.hoisted(() => ({
  mockUseApi: vi.fn(),
}));

vi.mock('next/navigation', () => ({
  usePathname: mockUsePathname,
}));

vi.mock('next/link', () => ({
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  default: (props: any) => <a href={props.href}>{props.children}</a>,
}));

vi.mock('@/lib/useApi', () => ({ useApi: mockUseApi }));

import { Sidebar, NAV } from '../../src/components/layout/Sidebar';

describe('Sidebar', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockUsePathname.mockReturnValue('/shopping-lists');
    mockUseApi.mockReturnValue({ profile: { displayName: 'Alice' } });
  });

  it('renders brand name', () => {
    render(<Sidebar />);
    expect(screen.getByText('MeshiTrack')).toBeInTheDocument();
  });

  it('renders active nav items', () => {
    render(<Sidebar />);
    expect(screen.getByText('Shopping Lists')).toBeInTheDocument();
    expect(screen.getByText('Stores')).toBeInTheDocument();
  });

  it('highlights active route', () => {
    mockUsePathname.mockReturnValue('/shopping-lists');
    render(<Sidebar />);
    const link = screen.getByText('Shopping Lists').closest('a');
    expect(link).toHaveAttribute('href', '/shopping-lists');
  });

  it('shows user avatar with display name', () => {
    render(<Sidebar />);
    expect(screen.getByLabelText('Alice')).toBeInTheDocument();
  });

  it('shows fallback name when no profile', () => {
    mockUseApi.mockReturnValue({ profile: null });
    render(<Sidebar />);
    expect(screen.getByLabelText('User')).toBeInTheDocument();
  });

  it('highlights nested route', () => {
    mockUsePathname.mockReturnValue('/shopping-lists/some-id');
    render(<Sidebar />);
    const link = screen.getByText('Shopping Lists').closest('a');
    expect(link).toBeInTheDocument();
  });

  it('renders item badge when present', () => {
    NAV.push({ id: 'test-badge', label: 'Test Badge', href: '/test-badge', icon: 'bell', badge: 5, section: 'Test Section' });
    render(<Sidebar />);
    expect(screen.getByText('5')).toBeInTheDocument();
    expect(screen.getByText('Test Section')).toBeInTheDocument();
    NAV.pop(); // Clean up NAV list mutation
  });
});
