import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '../../theme';

jest.mock('next-intl', () => ({ useTranslations: () => (k: string) => k, useLocale: () => 'en' }));

const mockUseDocUrl = jest.fn();
jest.mock('@/services/verification', () => ({ useVerificationDocumentUrl: (...a: unknown[]) => mockUseDocUrl(...a) }));

import DocumentViewer from './DocumentViewer';
import type { VerificationDocument } from '@/services/verification/types';

const DOC: VerificationDocument = {
  id: 5,
  contentType: 'image/png',
  fileSizeBytes: 2048,
  originalFileName: 'license.png',
  url: 'ignored-embedded-url',
};

describe('<DocumentViewer/>', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);
  afterEach(() => mockUseDocUrl.mockReset());

  it('renders the loaded image from the on-demand signed url (never the embedded url)', () => {
    mockUseDocUrl.mockReturnValue({ data: { url: 'https://signed/fresh.png', expiresInSeconds: 60 }, isLoading: false, isFetching: false, isError: false, refetch: jest.fn() });
    const { container } = wrap(<DocumentViewer document={DOC} />);
    const img = container.querySelector('img') as HTMLImageElement;
    expect(img).toBeTruthy();
    expect(img.src).toContain('signed/fresh.png');
    expect(img.src).not.toContain('ignored-embedded-url');
  });

  it('offers a re-request affordance on error and calls refetch', () => {
    const refetch = jest.fn();
    mockUseDocUrl.mockReturnValue({ data: undefined, isLoading: false, isFetching: false, isError: true, refetch });
    wrap(<DocumentViewer document={DOC} />);
    expect(screen.getByText('doc_error')).toBeInTheDocument();
    // Two re-request buttons (header + error panel); click the first.
    fireEvent.click(screen.getAllByText('doc_reload')[0]);
    expect(refetch).toHaveBeenCalled();
  });

  it('shows a skeleton while the signed url is loading', () => {
    mockUseDocUrl.mockReturnValue({ data: undefined, isLoading: true, isFetching: true, isError: false, refetch: jest.fn() });
    const { container } = wrap(<DocumentViewer document={DOC} />);
    expect(container.querySelector('.MuiSkeleton-root')).toBeInTheDocument();
  });
});
