import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import { TitleBar } from '@/components/layout/TitleBar';
import { useSettingsStore } from '@/stores/settings';

const invokeIpcMock = vi.hoisted(() => vi.fn());

vi.mock('@/lib/api-client', () => ({
  invokeIpc: (...args: unknown[]) => invokeIpcMock(...args),
}));

describe('TitleBar platform behavior', () => {
  beforeEach(() => {
    invokeIpcMock.mockReset();
    invokeIpcMock.mockResolvedValue(false);
    useSettingsStore.setState({ sidebarCollapsed: false });
  });

  it('extends the product surfaces through the macOS title bar', () => {
    window.electron.platform = 'darwin';

    render(<TitleBar integrated />);

    expect(screen.getByTestId('product-titlebar')).not.toHaveClass('border-b-4');
    expect(screen.getByTestId('product-titlebar')).toHaveClass('bg-[#FFFFFF]');
    expect(screen.getByTestId('titlebar-sidebar-surface')).toHaveClass('w-72', 'bg-[#F6F8FA]');

    act(() => useSettingsStore.setState({ sidebarCollapsed: true }));

    expect(screen.getByTestId('titlebar-sidebar-surface')).toHaveClass('w-16');
  });

  it('renders macOS drag region', () => {
    window.electron.platform = 'darwin';

    const { container } = render(<TitleBar />);

    expect(container.querySelector('.drag-region')).toBeInTheDocument();
    expect(screen.queryByTitle('Minimize')).not.toBeInTheDocument();
    expect(invokeIpcMock).not.toHaveBeenCalled();
  });

  it('renders custom controls on Windows', async () => {
    window.electron.platform = 'win32';

    render(<TitleBar />);

    expect(screen.getByTitle('Minimize')).toBeInTheDocument();
    expect(screen.getByTitle('Maximize')).toBeInTheDocument();
    expect(screen.getByTitle('Close')).toBeInTheDocument();

    await waitFor(() => {
      expect(invokeIpcMock).toHaveBeenCalledWith('window:isMaximized');
    });
  });

  it('renders no custom title bar on Linux', () => {
    window.electron.platform = 'linux';

    const { container } = render(<TitleBar />);

    expect(container.firstChild).toBeNull();
    expect(screen.queryByTitle('Minimize')).not.toBeInTheDocument();
    expect(invokeIpcMock).not.toHaveBeenCalled();
  });
});
