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

describe('BlogList — wiki edit pencil visibility', () => {
  it('shows edit pencil for authorized non-owner editor', async () => {
    // Configure auth user as bob
    store.dispatch(addUser({ address: 'A', publicKey: 'P', name: 'bob' }));
    // Seed one post from another user
    store.dispatch(
      addPosts([
        {
          id: 'q-blog-myblog-post-123',
          user: 'carol',
          title: 'T',
          description: 'd',
          createdAt: 1,
        } as any,
      ]),
    );

    // Owner + settings (whitelist bob)
    server.use(
      http.get('/arbitrary/resources', ({ request }) => {
        const url = new URL(request.url);
        if (
          url.searchParams.get('service') === 'BLOG' &&
          url.searchParams.get('identifier') === 'q-blog-myblog'
        ) {
          return HttpResponse.json([{ name: 'alice', identifier: 'q-blog-myblog' }]);
        }
        return HttpResponse.json([]);
      }),
      http.get('/arbitrary/BLOG/:name/:id', ({ params }) => {
        const { name, id } = params as any;
        if (name === 'alice' && id === 'q-blog-myblog') {
          return HttpResponse.json({ wikiEnabled: true, editorWhitelist: ['bob'] });
        }
        return HttpResponse.json({}, { status: 404 });
      }),
    );

    const { container } = render(
      <Provider store={store}>
        <ThemeProvider theme={createTheme()}>
          <MemoryRouter>
            <BlogList />
          </MemoryRouter>
        </ThemeProvider>
      </Provider>,
    );

    await waitFor(() => {
      const pencil = container.querySelector('.edit-btn');
      expect(pencil).toBeTruthy();
    });
  });
});
