import { render, screen, waitFor } from '@testing-library/react';
import Sticky, { StickyProps } from './Sticky';

describe('Sticky', () => {
  const defaultProps = {
    open: true,
    children: <div>Test Content</div>,
    position: 'bottom' as const,
    testId: 'test-sticky-panel',
  };

  let rerenderSticky: (props?: StickyProps) => void;

  beforeEach(() => {
    const { rerender } = render(<Sticky {...defaultProps} />);

    rerenderSticky = (props?: StickyProps) => {
      rerender(<Sticky {...defaultProps} {...props} />);
    };
  });

  test('renders with default props', () => {
    expect(screen.getByTestId('test-sticky-panel')).toBeVisible();
    expect(screen.getByTestId('test-sticky-panel')).toHaveClass('sliding-panel--open-bottom');
    expect(screen.getByText('Test Content')).toBeInTheDocument();
  });

  test('renders with open `false`', async () => {
    const props: StickyProps = {
      ...defaultProps,
      open: false, // Ensure the Sticky is initially open
    };

    expect(screen.getByTestId('test-sticky-panel')).toBeVisible();

    // Change props to close the Sticky
    rerenderSticky(props);

    await waitFor(() => {
      // Use queryByText instead of getByText for conditional presence checks
      expect(screen.queryByText('Test Content')).not.toBeInTheDocument();
    });
  });

  it('renders new content', () => {
    const props: StickyProps = {
      ...defaultProps,
      children: <div>New Test Content</div>,
    };
    expect(screen.getByText('Test Content')).toBeInTheDocument();

    // Change props
    rerenderSticky(props);

    expect(screen.getByText('New Test Content')).toBeInTheDocument();
  });

  it('renders with position set to `top`', () => {
    const props: StickyProps = {
      ...defaultProps,
      position: 'top',
    };
    expect(screen.getByTestId('test-sticky-panel')).toBeInTheDocument();
    expect(screen.getByTestId('test-sticky-panel')).toHaveClass('sliding-panel--open-bottom');

    // Change props
    rerenderSticky(props);

    expect(screen.getByTestId('test-sticky-panel')).toHaveClass('sliding-panel--open-top');
  });
});
