import React from 'react';
import { render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import JKChatMessageList from '../JKChatMessageList';
import sessionChatReducer from '../../../../store/features/sessionChatSlice';

// Mock scrollTo function (not available in JSDOM)
Element.prototype.scrollTo = jest.fn();

const createMockStore = (messages = [], fetchStatus = 'idle') => {
  return configureStore({
    reducer: {
      sessionChat: sessionChatReducer
    },
    preloadedState: {
      sessionChat: {
        messagesByChannel: { 'test-channel': messages },
        activeChannel: 'test-channel',
        channelType: 'session',
        unreadCounts: {},
        lastReadAt: {},
        fetchStatus: { 'test-channel': fetchStatus },
        fetchError: {},
        sendStatus: 'idle',
        sendError: null,
        nextCursors: {},
        isWindowOpen: true,
        windowPosition: null
      }
    }
  });
};

describe('JKChatMessageList', () => {
  test('shows empty state when no messages', () => {
    const store = createMockStore([]);

    render(
      <Provider store={store}>
        <JKChatMessageList />
      </Provider>
    );

    expect(screen.getByText('No messages yet')).toBeInTheDocument();
  });

  test('shows loading spinner when fetching', () => {
    const store = createMockStore([], 'loading');

    render(
      <Provider store={store}>
        <JKChatMessageList />
      </Provider>
    );

    expect(screen.getByText('Loading messages...')).toBeInTheDocument();
  });

  test('renders messages when available', () => {
    const messages = [
      {
        id: '1',
        senderId: 'user1',
        senderName: 'User One',
        message: 'Hello, world!',
        createdAt: new Date().toISOString()
      },
      {
        id: '2',
        senderId: 'user2',
        senderName: 'User Two',
        message: 'Hi there!',
        createdAt: new Date().toISOString()
      }
    ];
    const store = createMockStore(messages);

    render(
      <Provider store={store}>
        <JKChatMessageList />
      </Provider>
    );

    expect(screen.getByText('Hello, world!')).toBeInTheDocument();
    expect(screen.getByText('Hi there!')).toBeInTheDocument();
    expect(screen.getByText('User One')).toBeInTheDocument();
    expect(screen.getByText('User Two')).toBeInTheDocument();
  });
});
