// REQ-USR-003: NavOverlay 全部导航总览（开关 / 分组渲染 / 路由项与占位项，BR7/BR8/D4）
import { describe, it, expect, vi } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ConfigProvider, App as AntdApp } from 'antd';
import NavOverlay from '../../src/layouts/AppLayout/NavOverlay';

function renderOverlay(props: Partial<React.ComponentProps<typeof NavOverlay>> = {}) {
  const onClose = props.onClose ?? vi.fn();
  const onNavigate = props.onNavigate ?? vi.fn();
  const onPlaceholder = props.onPlaceholder ?? vi.fn();
  const open = props.open ?? true;
  render(
    <ConfigProvider>
      <AntdApp>
        <NavOverlay
          open={open}
          onClose={onClose}
          onNavigate={onNavigate}
          onPlaceholder={onPlaceholder}
        />
      </AntdApp>
    </ConfigProvider>,
  );
  return { onClose, onNavigate, onPlaceholder };
}

describe('NavOverlay', () => {
  it('hidden when open is false / visible when true', () => {
    const { unmount } = render(
      <ConfigProvider>
        <AntdApp>
          <NavOverlay open={false} onClose={vi.fn()} onNavigate={vi.fn()} onPlaceholder={vi.fn()} />
        </AntdApp>
      </ConfigProvider>,
    );
    expect(screen.queryByText('期初设置')).not.toBeInTheDocument();
    unmount();

    renderOverlay({ open: true });
    expect(screen.getByText('期初设置')).toBeInTheDocument();
    expect(screen.getByText('API对接管理')).toBeInTheDocument();
  });

  it('side has 系统设置 active', () => {
    renderOverlay({ open: true });
    const side = screen.getByTestId('nav-side');
    const sys = within(side).getByText('系统设置');
    expect(sys.closest('[aria-current]')?.getAttribute('aria-current')).toBe('true');
  });

  it("clicking 用户列表 calls onNavigate('/usr/users')", async () => {
    const { onNavigate, onPlaceholder } = renderOverlay({ open: true });
    await userEvent.click(screen.getByRole('button', { name: /用户列表/ }));
    expect(onNavigate).toHaveBeenCalledWith('/usr/users');
    expect(onPlaceholder).not.toHaveBeenCalled();
  });

  it('clicking placeholder leaf calls onPlaceholder (no navigate)', async () => {
    const { onNavigate, onPlaceholder } = renderOverlay({ open: true });
    await userEvent.click(screen.getByRole('button', { name: '系统权限' }));
    expect(onPlaceholder).toHaveBeenCalledTimes(1);
    expect(onNavigate).not.toHaveBeenCalled();
  });

  it('Esc / mask click calls onClose', async () => {
    const { onClose } = renderOverlay({ open: true });
    await userEvent.keyboard('{Escape}');
    expect(onClose).toHaveBeenCalled();

    await userEvent.click(screen.getByTestId('nav-overlay-mask'));
    expect(onClose).toHaveBeenCalledTimes(2);
  });
});
