import { test, expect } from '@playwright/test';
import { loginToJamUI, createAndJoinSession } from '../utils/test-helpers';

test.describe('Chat Window', () => {
  test.beforeEach(async ({ page }) => {
    await loginToJamUI(page);
    await createAndJoinSession(page);
  });

  test('opens chat window when dispatching openChatWindow action', async ({ page, context }) => {
    // Dispatch openChatWindow action via Redux
    await page.evaluate(() => {
      const store = (window as any).__REDUX_STORE__;
      if (!store) {
        throw new Error('Redux store not exposed for testing');
      }
      store.dispatch({ type: 'sessionChat/openChatWindow' });
    });

    // Wait for popup window
    const popupPromise = context.waitForEvent('page');
    const popup = await popupPromise;

    // Verify popup opened
    expect(popup).toBeTruthy();
    await expect(popup).toHaveTitle('JamKazam Chat');

    // Verify header content
    const header = popup.locator('h5');
    await expect(header).toBeVisible();
    await expect(header).toContainText('Chat');
  });

  test('closes chat window when clicking close button', async ({ page, context }) => {
    // Open chat window
    await page.evaluate(() => {
      const store = (window as any).__REDUX_STORE__;
      store.dispatch({ type: 'sessionChat/openChatWindow' });
    });

    const popupPromise = context.waitForEvent('page');
    const popup = await popupPromise;

    // Wait for popup to be ready
    await popup.waitForLoadState('domcontentloaded');

    // Click close button
    const closeButton = popup.locator('button[aria-label="Close chat"]');
    await expect(closeButton).toBeVisible();
    await closeButton.click();

    // Verify popup closed (wait a bit for close to complete)
    await page.waitForTimeout(1000);
    expect(popup.isClosed()).toBe(true);

    // Verify Redux state updated
    const isWindowOpen = await page.evaluate(() => {
      const store = (window as any).__REDUX_STORE__;
      return store.getState().sessionChat.isWindowOpen;
    });
    expect(isWindowOpen).toBe(false);
  });

  test('shows placeholder message before messages loaded', async ({ page, context }) => {
    // Open chat window
    await page.evaluate(() => {
      const store = (window as any).__REDUX_STORE__;
      store.dispatch({ type: 'sessionChat/openChatWindow' });
    });

    const popupPromise = context.waitForEvent('page');
    const popup = await popupPromise;

    // Wait for popup to be ready
    await popup.waitForLoadState('domcontentloaded');

    // Verify placeholder text
    const placeholder = popup.locator('p:has-text("Chat messages will appear here")');
    await expect(placeholder).toBeVisible();
  });
});
