import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { render, screen } from '@testing-library/react';
import { BlogList } from '@/pages/BlogList/BlogList';
import { store } from '@/state/store';
import { addPosts, setCountNewPosts } from '@/state/features/blogSlice';
import { addUser } from '@/state/features/authSlice';

describe('BlogList', () => {
  beforeEach(() => {
    // reset likely mutated lists by replacing posts
    store.dispatch(addPosts([] as any));
    store.dispatch(setCountNewPosts(0));
  });

  it('renders posts provided in store', async () => {
    store.dispatch(
      addPosts([
        {
          id: 'q-blog-b1-post-1',
          user: 'alice',
          title: 'Post A',
          description: 'Desc A',
          createdAt: 0,
        },
        {
          id: 'q-blog-b2-post-2',
          user: 'bob',
          title: 'Post B',
          description: 'Desc B',
          createdAt: 0,
        },
      ] as any),
    );
    render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter>
            <BlogList />
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );

    expect(await screen.findByText('Post A')).toBeInTheDocument();
    expect(screen.getByText('Post B')).toBeInTheDocument();
  });

  it('shows new posts banner when countNewPosts > 0', async () => {
    store.dispatch(setCountNewPosts(2));
    render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter>
            <BlogList />
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );
    expect(await screen.findByText('There are 2 new posts')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Load new Posts/i })).toBeInTheDocument();
  });
});
