import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Sheet } from './Sheet';

describe('Sheet', () => {
  it('renders in closed state by default', () => {
    const { container } = render(
      <Sheet open={false} onClose={vi.fn()}>
        <div>Sheet Content</div>
      </Sheet>
    );

    // Sheet should not be visible when closed
    expect(container.querySelector('[data-testid="sheet-content"]')).not.toBeInTheDocument();
  });

  it('opens when open prop is true', () => {
    render(
      <Sheet open={true} onClose={vi.fn()}>
        <div>Sheet Content</div>
      </Sheet>
    );

    // Sheet should be visible when open
    expect(screen.getByTestId('sheet-content')).toBeInTheDocument();
    expect(screen.getByText('Sheet Content')).toBeInTheDocument();
  });

  it('calls onClose when backdrop is clicked', () => {
    const handleClose = vi.fn();

    const { container } = render(
      <Sheet open={true} onClose={handleClose}>
        <div data-testid="sheet-content">Sheet Content</div>
      </Sheet>
    );

    // Click backdrop
    const backdrop = container.querySelector('[data-testid="sheet-backdrop"]');
    if (backdrop) {
      fireEvent.click(backdrop);
      expect(handleClose).toHaveBeenCalledTimes(1);
    }
  });

  it('calls onClose when Escape key is pressed', () => {
    const handleClose = vi.fn();

    render(
      <Sheet open={true} onClose={handleClose}>
        <div data-testid="sheet-content">Sheet Content</div>
      </Sheet>
    );

    // Press Escape key
    fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' });
    expect(handleClose).toHaveBeenCalledTimes(1);
  });

  it('applies responsive classes', () => {
    render(
      <Sheet open={true} onClose={vi.fn()}>
        <div>Sheet Content</div>
      </Sheet>
    );

    const sheetContent = screen.getByTestId('sheet-content');
    expect(sheetContent).toHaveClass('sm:max-w-[600px]', 'h-[85vh]');
  });

  it('renders children correctly', () => {
    render(
      <Sheet open={true} onClose={vi.fn()}>
        <div data-testid="test-child">Test Child Content</div>
      </Sheet>
    );

    expect(screen.getByTestId('test-child')).toBeInTheDocument();
    expect(screen.getByText('Test Child Content')).toBeInTheDocument();
  });

  it('does not close when clicking inside sheet content', () => {
    const handleClose = vi.fn();

    render(
      <Sheet open={true} onClose={handleClose}>
        <div data-testid="test-child">Sheet Content</div>
      </Sheet>
    );

    // Click inside sheet content
    const sheetContent = screen.getByTestId('sheet-content');
    fireEvent.click(sheetContent);
    expect(handleClose).not.toHaveBeenCalled();
  });
});
