import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { ChatWindow } from './chat-window';

// Mock scrollIntoView
Element.prototype.scrollIntoView = vi.fn();

// Mock store hooks
vi.mock('@/store/use-session', () => ({
  useTeacherStatus: vi.fn(() => 'idle'),
}));

// Mock Dexie hooks
const mockMessages = [
  { id: 1, role: 'user', content: 'Hello', timestamp: 1000 },
  { id: 2, role: 'assistant', content: 'Hi there!', timestamp: 2000 },
];

vi.mock('dexie-react-hooks', () => ({
  useLiveQuery: vi.fn((cb) => {
    // If we wanted to test the callback, we'd mock db. But for UI testing, 
    // we can just return what we want the hook to return.
    // However, existing check calls the callback. 
    // Let's rely on a variable we can change, or just mock return value.
    // For simplicity in this file, let's assume it returns the global mockMessages var
    // initialized in test blocks.
    return (globalThis as any).mockLiveQueryValue;
  }),
}));

// Mock db to avoid runtime errors if useLiveQuery callback is executed (though we mocked useLiveQuery)
vi.mock('@/lib/db/db', () => ({
  db: {},
}));

describe('ChatWindow', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    (globalThis as any).mockLiveQueryValue = [];
  });

  it('renders loading state when no sessionId is provided', () => {
    render(<ChatWindow sessionId={null} />);
    expect(screen.getByText(/loading session/i)).toBeInTheDocument();
  });

  it('renders empty state when sessionId is provided but no messages', () => {
    (globalThis as any).mockLiveQueryValue = [];
    render(<ChatWindow sessionId="123" />);
    // Updated text expectation
    expect(screen.getByText(/what do you want to record?/i)).toBeInTheDocument();
    expect(screen.getByText(/let me help you summarize your day/i)).toBeInTheDocument();
    // Verify theme class
    expect(screen.getByText(/what do you want to record?/i)).toHaveClass('text-foreground');
  });

  it('renders messages when they exist', () => {
    (globalThis as any).mockLiveQueryValue = mockMessages;
    render(<ChatWindow sessionId="123" />);
    expect(screen.getByText('Hello')).toBeInTheDocument();
    expect(screen.getByText('Hi there!')).toBeInTheDocument();
  });

  it('scrolls to bottom on new messages', () => {
    (globalThis as any).mockLiveQueryValue = mockMessages;
    render(<ChatWindow sessionId="123" />);
    expect(Element.prototype.scrollIntoView).toHaveBeenCalled();
  });
});
