import React, { ReactElement } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { BrowserRouter, MemoryRouter } from 'react-router-dom';
import { LoadingProvider } from '../../shared/contexts/LoadingContext';
import { CookieConsentProvider } from '../../shared/contexts/CookieConsentContext';
import { CurrencyProvider } from '../../features/payments/contexts/CurrencyContext';
import { CompanySettingsProvider } from '../../shared/contexts/CompanySettingsContext';
import { AuthModalProvider } from '../../features/auth/contexts/AuthModalContext';

// Inner providers (without router)
const InnerProviders = ({ children }: { children: React.ReactNode }) => {
  return (
    <LoadingProvider>
      <CookieConsentProvider>
        <CurrencyProvider>
          <CompanySettingsProvider>
            <AuthModalProvider>
              {children}
            </AuthModalProvider>
          </CompanySettingsProvider>
        </CurrencyProvider>
      </CookieConsentProvider>
    </LoadingProvider>
  );
};

// Custom render function that includes all providers with BrowserRouter
const AllTheProviders = ({ children }: { children: React.ReactNode }) => {
  return (
    <BrowserRouter>
      <InnerProviders>
        {children}
      </InnerProviders>
    </BrowserRouter>
  );
};

const customRender = (
  ui: ReactElement,
  options?: Omit<RenderOptions, 'wrapper'>,
) => render(ui, { wrapper: AllTheProviders, ...options });

// Render with MemoryRouter (for tests that need to control routing)
export const renderWithRouter = (
  ui: ReactElement,
  { initialEntries = ['/'], ...options }: { initialEntries?: string[] } & Omit<RenderOptions, 'wrapper'> = {},
) => {
  const Wrapper = ({ children }: { children: React.ReactNode }) => (
    <MemoryRouter initialEntries={initialEntries}>
      <InnerProviders>
        {children}
      </InnerProviders>
    </MemoryRouter>
  );
  return render(ui, { wrapper: Wrapper, ...options });
};

export * from '@testing-library/react';
export { customRender as render };

