import { screen, fireEvent, waitFor } from '@testing-library/react';
import { renderWithProviders as render } from '../../../test/render';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Sidebar } from './sidebar';
import React from 'react';

// Mock framer-motion
vi.mock('framer-motion', () => ({
  motion: {
    div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
    button: ({ children, ...props }: any) => <button {...props}>{children}</button>,
  },
  AnimatePresence: ({ children }: any) => <>{children}</>,
}));

describe('Sidebar', () => {
  const defaultProps = {
    expanded: true,
    onToggle: vi.fn(),
    user: { email: 'test@example.com' },
    onLogout: vi.fn(),
    location: { pathname: '/' },
    navigate: vi.fn(),
    routes: [
      { path: '/', label: 'Home', icon: () => <div data-testid="icon-home" /> },
      { path: '/dashboard', label: 'Dashboard', icon: () => <div data-testid="icon-dash" /> },
    ],
  };

  beforeEach(() => {
    vi.clearAllMocks();
    // Mock clientHeight for overflow detection
    Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
      configurable: true,
      value: 1000,
    });
  });

  it('renders with local fallback state when no LayoutProvider is present', () => {
    render(<Sidebar routes={defaultProps.routes} location={{ pathname: '/' }} />);

    expect(screen.getByLabelText('Expandir menu')).toBeInTheDocument();
  });

  it('renders correctly when expanded', async () => {
    render(<Sidebar {...defaultProps} />);
    await waitFor(() => {
      expect(screen.getByText('Início')).toBeInTheDocument(); // Translated from Home
      expect(screen.getByText('Painel')).toBeInTheDocument(); // Translated from Dashboard
    });
  });

  it('calls onToggle when toggle button is clicked', () => {
    render(<Sidebar {...defaultProps} />);
    const toggleButton = screen.getByLabelText('Recolher menu');
    fireEvent.click(toggleButton);
    expect(defaultProps.onToggle).toHaveBeenCalled();
  });

  it('calls navigate when a menu item is clicked', async () => {
    render(<Sidebar {...defaultProps} />);
    const dashboardLink = await screen.findByText('Painel');
    fireEvent.click(dashboardLink);
    expect(defaultProps.navigate).toHaveBeenCalledWith('/dashboard');
  });

  it('renders correctly in assistant variant', () => {
    render(
      <Sidebar
        {...defaultProps}
        variant="assistant"
        search={{ show: true, placeholder: 'Buscar conversas' }}
      />
    );
    expect(screen.getByPlaceholderText('Buscar conversas')).toBeInTheDocument();
  });
});
