import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '@cameleer/design-system';
import type { ReactNode } from 'react';
import { SideDrawer } from './SideDrawer';

function wrap(ui: ReactNode) {
  return render(<ThemeProvider>{ui}</ThemeProvider>);
}

describe('SideDrawer', () => {
  it('renders nothing when closed', () => {
    wrap(<SideDrawer open={false} onClose={() => {}} title="X">body</SideDrawer>);
    expect(screen.queryByText('body')).toBeNull();
  });

  it('renders title, body, and close button when open', () => {
    wrap(<SideDrawer open onClose={() => {}} title="My Title">body content</SideDrawer>);
    expect(screen.getByText('My Title')).toBeInTheDocument();
    expect(screen.getByText('body content')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /close/i })).toBeInTheDocument();
  });

  it('calls onClose when close button clicked', () => {
    const onClose = vi.fn();
    wrap(<SideDrawer open onClose={onClose} title="X">body</SideDrawer>);
    fireEvent.click(screen.getByRole('button', { name: /close/i }));
    expect(onClose).toHaveBeenCalledOnce();
  });

  it('calls onClose when ESC pressed', () => {
    const onClose = vi.fn();
    wrap(<SideDrawer open onClose={onClose} title="X">body</SideDrawer>);
    fireEvent.keyDown(document, { key: 'Escape' });
    expect(onClose).toHaveBeenCalledOnce();
  });

  it('calls onClose when backdrop clicked', () => {
    const onClose = vi.fn();
    wrap(<SideDrawer open onClose={onClose} title="X">body</SideDrawer>);
    fireEvent.click(screen.getByTestId('side-drawer-backdrop'));
    expect(onClose).toHaveBeenCalledOnce();
  });

  it('renders footer when provided', () => {
    wrap(
      <SideDrawer open onClose={() => {}} title="X" footer={<button>Save</button>}>
        body
      </SideDrawer>
    );
    expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
  });
});
