import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import App from './App';

const mockAllData = {
  profile: {
    nickname: 'Test User',
    avatar: null,
    introduction: 'Hello',
    footer: '© Test Footer'
  },
  techstack: null,
  projects: null,
  contacts: null
};

const mockVisitorInfo = {
  ip: '66.90.99.202',
  ipVersion: 'ipv4',
  geo: {
    country: 'JP',
    countryName: '日本',
    region: 'Tokyo',
    regionName: '东京都',
    city: 'Ebara',
    cityName: '东京'
  }
};

beforeEach(() => {
  jest.spyOn(global, 'fetch').mockImplementation((url) => {
    if (typeof url === 'string' && url.includes('/api/all')) {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve(mockAllData)
      });
    }
    if (url === 'https://cf-ip-geo.smyhub.com/api') {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve(mockVisitorInfo)
      });
    }
    if (typeof url === 'string' && url.includes('randbg.api.smyhub.com')) {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve({ url: 'https://example.com/bg.webp' })
      });
    }
    return Promise.resolve({
      ok: true,
      json: () => Promise.resolve({})
    });
  });
});

afterEach(() => {
  global.fetch.mockRestore();
});

test('renders visitor ip and geo in footer', async () => {
  render(
    <MemoryRouter initialEntries={['/']}>
      <App />
    </MemoryRouter>
  );
  const visitorLine = await screen.findByText(/访客 IP：66\.90\.99\.202/i);
  expect(visitorLine).toBeInTheDocument();
  expect(visitorLine).toHaveTextContent('日本');
  expect(visitorLine).toHaveTextContent('东京都');
});
