import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Home from '@/app/page';
import * as awareness from '@/lib/awareness';

// Mock the publish function
const publishSpy = vi.spyOn(awareness, 'publish');

describe('Awareness Integration Smoke Test', () => {

  beforeEach(() => {
    vi.clearAllMocks();
    // Mock performance.now for consistent timestamps
    vi.spyOn(performance, 'now').mockReturnValue(12345.678);
  });

  it('should publish awareness events through the component lifecycle', async () => {
    render(<Home />);

    // 1. Login and unlock
    // Assuming LoginScreen is shown and we can trigger unlock
    // A simple way is to find a button and click it.
    // From reading LoginScreen.tsx, there is a button with text "Unlock".
    // Let's wait for the loader to disappear first.
    await act(async () => {
        await new Promise(resolve => setTimeout(resolve, 4000)); // Wait for loader and login screen to appear
    });

    const unlockButton = screen.getByRole('button', { name: /unlock/i });
    fireEvent.click(unlockButton);

    // 2. Check for DESKTOP_LOADED on unlock
    expect(publishSpy).toHaveBeenCalledWith({
      type: awareness.AwarenessEvent.DESKTOP_LOADED,
      payload: {
        timestamp: expect.any(Number),
        openWindows: 0,
        activeWindow: null,
      },
    });

    // 3. Open a window (e.g., by double-clicking a desktop icon)
    const aboutIcon = screen.getByText('About Me');
    fireEvent.doubleClick(aboutIcon);

    await waitFor(() => {
        expect(screen.getByRole('dialog', { name: /about me/i })).toBeInTheDocument();
    });

    // 4. Check for WINDOW_OPENED
    expect(publishSpy).toHaveBeenCalledWith({
      type: awareness.AwarenessEvent.WINDOW_OPENED,
      payload: {
        windowId: 'about',
        timestamp: expect.any(Number),
      },
    });

    // 5. Focus the window (clicking on it should be enough)
    const window = await screen.findByRole('dialog', { name: /about me/i });
    fireEvent.click(window);

    // 6. Check for WINDOW_FOCUSED
    expect(publishSpy).toHaveBeenCalledWith({
        type: awareness.AwarenessEvent.WINDOW_FOCUSED,
        payload: {
            windowId: 'about',
            timestamp: expect.any(Number),
        }
    });

    // 7. Close the window
    const closeButton = screen.getByRole('button', { name: /close/i });
    fireEvent.click(closeButton);

    // 8. Check for WINDOW_CLOSED
    expect(publishSpy).toHaveBeenCalledWith({
        type: awareness.AwarenessEvent.WINDOW_CLOSED,
        payload: {
            windowId: 'about',
            timestamp: expect.any(Number),
        }
    });

  }, 10000);
});
