import { renderHook } from '@testing-library/react';
import useResponsive from '../useResponsive';

describe('useResponsive', () => {
  let mockObserve: jest.Mock;
  let mockDisconnect: jest.Mock;
  let mockResizeObserver: jest.Mock;

  beforeEach(() => {
    mockObserve = jest.fn();
    mockDisconnect = jest.fn();
    mockResizeObserver = jest.fn((callback) => ({
      observe: mockObserve,
      disconnect: mockDisconnect,
      callback,
    }));

    global.ResizeObserver = mockResizeObserver;
  });

  it('should not create observer when root is null', () => {
    const onResize = jest.fn();
    renderHook(() => useResponsive(null as unknown as HTMLElement, onResize));

    expect(mockResizeObserver).not.toHaveBeenCalled();
    expect(mockObserve).not.toHaveBeenCalled();
  });

  it('should create observer and observe root element', () => {
    const root = document.createElement('div');
    const onResize = jest.fn();

    renderHook(() => useResponsive(root, onResize));

    expect(mockResizeObserver).toHaveBeenCalled();
    expect(mockObserve).toHaveBeenCalledWith(root);
  });

  it('should call onResize with correct width when size changes', () => {
    const root = document.createElement('div');
    const onResize = jest.fn();

    renderHook(() => useResponsive(root, onResize));

    const [[callback]] = mockResizeObserver.mock.calls;
    callback([{ contentRect: { width: 100.75 } }]);

    expect(onResize).toHaveBeenCalledWith(100);
  });

  it('should disconnect observer on unmount', () => {
    const root = document.createElement('div');
    const onResize = jest.fn();

    const { unmount } = renderHook(() => useResponsive(root, onResize));
    unmount();

    expect(mockDisconnect).toHaveBeenCalled();
  });
});
