import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resetStore } from '../test/storeTestUtils';
import { useStore } from '../store/useStore';
import { Sidebar } from './Sidebar';

vi.mock('./ModelStatusBadge', () => ({
  ModelStatusBadge: () => <div>模型状态</div>,
}));

describe('Sidebar', () => {
  beforeEach(() => {
    resetStore();
  });

  it('shows admin user management only for admin users', () => {
    const setActiveModule = vi.fn();
    useStore.setState({ currentUser: { id: 1, username: 'admin', role: 'admin' } });

    render(<Sidebar activeModule="dashboard" setActiveModule={setActiveModule} />);

    const adminButton = screen.getByTitle('用户管理');
    expect(adminButton.querySelector('.lucide-circle-user')).toBeInTheDocument();
    fireEvent.click(adminButton);
    expect(setActiveModule).toHaveBeenCalledWith('admin');
  });

  it('hides admin user management for non-admin users', () => {
    useStore.setState({ currentUser: { id: 2, username: 'doctor', role: 'annotator' } });

    render(<Sidebar activeModule="dashboard" setActiveModule={vi.fn()} />);

    expect(screen.queryByTitle('用户管理')).not.toBeInTheDocument();
  });

  it('uses an explicit AI-styled icon for AI segmentation', () => {
    useStore.setState({ currentUser: { id: 2, username: 'doctor', role: 'annotator' } });

    render(<Sidebar activeModule="dashboard" setActiveModule={vi.fn()} />);

    expect(screen.getByTitle('AI智能分割').querySelector('[data-testid="ai-segmentation-icon"]')).toBeInTheDocument();
  });

  it('uses the root logo_square asset for the sidebar logo', () => {
    render(<Sidebar activeModule="dashboard" setActiveModule={vi.fn()} />);

    expect(screen.getByAltText('Logo')).toHaveAttribute('src', expect.stringContaining('logo_square'));
  });

  it('uses a logout icon and prevents the logout tooltip from catching workspace hover', () => {
    useStore.setState({ currentUser: { id: 1, username: 'admin', role: 'admin' } });

    render(<Sidebar activeModule="dashboard" setActiveModule={vi.fn()} />);

    const logoutButton = screen.getByTitle('当前用户：admin，点击退出');
    expect(logoutButton.querySelector('.lucide-log-out')).toBeInTheDocument();
    expect(screen.getByText('admin / 退出')).toHaveClass('pointer-events-none');
    expect(screen.getByText('admin / 退出')).toHaveClass('invisible');
  });
});
