import React from 'react';
import {render, screen} from '@testing-library/react';

jest.mock('@/services/bandeauService', () => ({
  getBandeau: jest.fn(),
}));

jest.mock('next/navigation', () => ({
  usePathname: jest.fn(),
}));

jest.mock('next/image', () => ({
  __esModule: true,
  default: ({src, alt}: {src: string; alt: string}) => <img src={src} alt={alt} />,
}));

import BandeauTk from '../BandeauTk';
import {getBandeau} from '@/services/bandeauService';
import {usePathname} from 'next/navigation';

const mockedGetBandeau = getBandeau as jest.Mock;
const mockedUsePathname = usePathname as jest.Mock;

async function renderBandeau(pathname: string) {
  mockedUsePathname.mockReturnValue(pathname);
  render(await (BandeauTk as any)({locale: 'fr'}));
}

describe('BandeauTk', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldRenderNothingWithoutBandeau', async () => {
    mockedGetBandeau.mockResolvedValue(null);

    await renderBandeau('/fr');

    expect(screen.queryByRole('img')).not.toBeInTheDocument();
  });

  it('shouldRenderTheImageOnTheHomepage', async () => {
    mockedGetBandeau.mockResolvedValue({
      imageUrl: 'https://media.tamm-kreiz.bzh/bandeau.jpg',
      toutesPages: false,
    });

    await renderBandeau('/fr');

    expect(screen.getByRole('img')).toHaveAttribute(
      'src',
      'https://media.tamm-kreiz.bzh/bandeau.jpg'
    );
  });

  it('shouldStayOnTheHomepageWhenNotSetForEveryPage', async () => {
    mockedGetBandeau.mockResolvedValue({
      imageUrl: 'https://media.tamm-kreiz.bzh/bandeau.jpg',
      toutesPages: false,
    });

    await renderBandeau('/fr/evenements');

    expect(screen.queryByRole('img')).not.toBeInTheDocument();
  });

  it('shouldRenderOnEveryPageWhenSetForEveryPage', async () => {
    mockedGetBandeau.mockResolvedValue({
      imageUrl: 'https://media.tamm-kreiz.bzh/bandeau.jpg',
      toutesPages: true,
    });

    await renderBandeau('/fr/evenements');

    expect(screen.getByRole('img')).toBeInTheDocument();
  });

  it('shouldWrapTheImageInALinkWhenOneIsConfigured', async () => {
    mockedGetBandeau.mockResolvedValue({imageUrl: 'https://pimcore.test/bandeau.jpg', toutesPages: true, lien: 'https://www.tamm-kreiz.bzh/festival'});
    await renderBandeau('/fr/evenements');

    expect(screen.getByRole('img', {name: 'Bandeau Tamm Kreiz'}).closest('a')).toHaveAttribute('href', 'https://www.tamm-kreiz.bzh/festival');
  });

  it('shouldNotBeClickableWithoutLink', async () => {
    mockedGetBandeau.mockResolvedValue({imageUrl: 'https://pimcore.test/bandeau.jpg', toutesPages: true, lien: null});
    await renderBandeau('/fr/evenements');

    expect(screen.getByRole('img', {name: 'Bandeau Tamm Kreiz'}).closest('a')).toBeNull();
  });
});
