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

const navigateMock = vi.fn();

vi.mock('react-router-dom', () => ({
  useNavigate: () => navigateMock,
}));

function TestComponent({ fallback }: { fallback?: string }) {
  const back = useBackNavigation(fallback);
  return (
    <button type="button" onClick={back}>
      Back
    </button>
  );
}

describe('useBackNavigation', () => {
  beforeEach(() => {
    navigateMock.mockReset();
  });

  it('navigates back when history is available', () => {
    Object.defineProperty(window.history, 'length', {
      configurable: true,
      get: () => 3,
    });

    const { getByText } = render(<TestComponent />);
    fireEvent.click(getByText('Back'));
    expect(navigateMock).toHaveBeenCalledWith(-1);
  });

  it('navigates to fallback when history is empty', () => {
    Object.defineProperty(window.history, 'length', {
      configurable: true,
      get: () => 1,
    });

    const { getByText } = render(<TestComponent fallback="/event-admin/mobile/dashboard" />);
    fireEvent.click(getByText('Back'));
    expect(navigateMock).toHaveBeenCalledWith('/event-admin/mobile/dashboard', { replace: true });
  });
});
