import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';

import { api } from './api';
import PublicCvPage from './views/PublicCvPage';

jest.mock('./api', () => ({
  api: {
    defaults: { baseURL: '/api' },
    get: jest.fn(),
  },
}));

const mockedApi = api as jest.Mocked<typeof api>;

test('public CV exposes the rendered CV and PDF download', async () => {
  const originalInnerWidth = window.innerWidth;
  Object.defineProperty(window, 'innerWidth', { configurable: true, value: 375 });
  mockedApi.get.mockResolvedValueOnce({ data: { html: '<p>Public CV</p>', name: 'Ada Lovelace' } } as any);

  render(
    <MemoryRouter initialEntries={['/cv/public-slug']}>
      <Routes><Route path="/cv/:slug" element={<PublicCvPage />} /></Routes>
    </MemoryRouter>,
  );

  const frame = await screen.findByTitle('Public CV');
  expect(frame).toHaveAttribute('srcdoc', '<p>Public CV</p>');
  expect(Number.parseFloat(frame.style.width)).toBeGreaterThan(790);
  await waitFor(() => expect(frame.style.transform).not.toBe('scale(1)'));
  expect(Number.parseFloat(screen.getByTestId('public-cv-frame-container').style.width)).toBeLessThanOrEqual(343);
  expect(screen.getByRole('link', { name: 'Download PDF' })).toHaveAttribute('href', '/api/public-cv/public-slug/pdf');
  expect(mockedApi.get).toHaveBeenCalledWith('/public-cv/public-slug');
  Object.defineProperty(window, 'innerWidth', { configurable: true, value: originalInnerWidth });
});
