import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../theme';
import type { LinkToPage } from '@/utils';

const mockPush = jest.fn();
let pathname = '/nurse';

jest.mock('@/i18n/navigation', () => ({
  usePathname: () => pathname,
  useRouter: () => ({ push: mockPush }),
}));

import BottomBar from './BottomBar';

const TABS: Array<LinkToPage> = [
  { title: 'Today', path: '/nurse', icon: 'today' },
  { title: 'Practice', path: '/nurse/practice', icon: 'practice', matchPaths: ['/nurse/profile', '/nurse/services'] },
  { title: 'Money', path: '/nurse/finance', icon: 'earnings', matchPaths: ['/nurse/earnings', '/nurse/bank'] },
  { title: 'More', path: '/nurse/more', icon: 'more', badgeCount: 2 },
];

function renderBar(at: string) {
  pathname = at;
  return render(
    <ThemeProvider>
      <BottomBar items={TABS} />
    </ThemeProvider>
  );
}

/** The single active tab, read off the aria-current the bar stamps on it. */
function activeTabName(): string | undefined {
  return screen.queryByRole('button', { current: 'page' })?.textContent ?? undefined;
}

describe('<BottomBar/> component', () => {
  beforeEach(() => mockPush.mockReset());

  it('renders one tab per item', () => {
    renderBar('/nurse');
    expect(screen.getAllByRole('button')).toHaveLength(TABS.length);
  });

  it('marks the exact tab as active', () => {
    renderBar('/nurse');
    expect(activeTabName()).toBe('Today');
  });

  it('keeps a nested route on its own tab (longest prefix wins over the shell root)', () => {
    renderBar('/nurse/practice');
    expect(activeTabName()).toBe('Practice');
  });

  it('lights up the group tab for a destination outside its subtree (matchPaths)', () => {
    // The regression this guards: `/nurse/earnings` is not under `/nurse/finance`, so a plain
    // longest-prefix match would fall back to the `/nurse` root tab and highlight «Today» instead.
    renderBar('/nurse/earnings/payouts');
    expect(activeTabName()).toBe('Money');
  });

  it('navigates on tap', async () => {
    renderBar('/nurse');
    await userEvent.click(screen.getByRole('button', { name: /Money/ }));
    expect(mockPush).toHaveBeenCalledWith('/nurse/finance');
  });

  it('shows a badge only on the tab that has a count', () => {
    renderBar('/nurse');
    expect(screen.getByText('2')).toBeInTheDocument();
  });

  it('floats as a rounded, elevated bar rather than an edge-to-edge slab', () => {
    renderBar('/nurse');
    const bar = screen.getByRole('navigation').firstElementChild as HTMLElement;
    expect(bar).toHaveStyle('border-radius: var(--bal-radius-pill)');
    expect(bar).toHaveStyle('box-shadow: var(--bal-shadow-2)');
  });
});
