import React from 'react';
import {render, screen, waitFor} from '@testing-library/react';
import MagSection, {readingTimeMinutes} from '../MagSection';
import {getAllArticlesPublished} from '@/services/articleService';

jest.mock('next/link', () => {
  return ({children, href, ...props}: {children: React.ReactNode; href: string; [key: string]: unknown}) => (
    <a href={href} {...props}>{children}</a>
  );
});

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

const mockArticles = [
  {id: 1, title: 'Bilan des festoù-noz', slug: 'bilan-festou-noz', body: '<p>' + 'mot '.repeat(400) + '</p>', createdAt: '2026-05-15T10:00:00Z', updatedAt: null},
  {id: 2, title: 'Le renouveau du fest-noz', slug: 'renouveau-fest-noz', body: '<p>Court.</p>', createdAt: '2026-02-15T10:00:00Z', updatedAt: null},
];

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

  it('shouldRenderPublishedArticles', async () => {
    (getAllArticlesPublished as jest.Mock).mockResolvedValue(mockArticles);
    render(<MagSection locale="fr" />);

    await waitFor(() => {
      expect(screen.getByText('Bilan des festoù-noz')).toBeInTheDocument();
      expect(screen.getByText('Le renouveau du fest-noz')).toBeInTheDocument();
    });
  });

  it('shouldLinkArticlesBySlug', async () => {
    (getAllArticlesPublished as jest.Mock).mockResolvedValue(mockArticles);
    render(<MagSection locale="fr" />);

    await waitFor(() => {
      const title = screen.getByText('Bilan des festoù-noz');
      expect(title.closest('a')).toHaveAttribute('href', '/fr/articles/bilan-festou-noz');
    });
  });

  it('shouldRenderSeeAllLink', async () => {
    (getAllArticlesPublished as jest.Mock).mockResolvedValue(mockArticles);
    render(<MagSection locale="fr" />);

    await waitFor(() => {
      expect(screen.getByText(/mag_see_all/)).toBeInTheDocument();
    });
  });

  it('shouldShowEmptyStateWithoutArticles', async () => {
    (getAllArticlesPublished as jest.Mock).mockResolvedValue([]);
    render(<MagSection locale="fr" />);

    await waitFor(() => {
      expect(screen.getByText('mag_empty')).toBeInTheDocument();
    });
  });
});

describe('readingTimeMinutes', () => {
  it('shouldEstimateReadingTimeFromWordCount', () => {
    expect(readingTimeMinutes('mot '.repeat(400))).toBe(2);
  });

  it('shouldReturnAtLeastOneMinute', () => {
    expect(readingTimeMinutes('<p>Court.</p>')).toBe(1);
    expect(readingTimeMinutes('')).toBe(1);
    expect(readingTimeMinutes(null)).toBe(1);
  });

  it('shouldIgnoreHtmlTags', () => {
    expect(readingTimeMinutes('<div><span>un deux trois</span></div>')).toBe(1);
  });
});
