import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MainLayout } from '@/components/layout/MainLayout';
import { useOpencodeStore } from '@/stores/opencode';
import { useProjectConfigStore } from '@/stores/project-config';
import { useSettingsStore } from '@/stores/settings';
import { createProjectConfig } from '../../shared/project-config';

vi.mock('@/components/layout/Sidebar', () => ({
  Sidebar: ({ sidebarCollapsedOverride }: { sidebarCollapsedOverride?: boolean }) => (
    <aside data-testid="sidebar-stub" data-sidebar-collapsed={sidebarCollapsedOverride === undefined ? 'unset' : String(sidebarCollapsedOverride)} />
  ),
}));
vi.mock('@/components/layout/TitleBar', () => ({
  TitleBar: ({ integrated = false, overlay = false, pageTitle, sidebarCollapsedOverride }: { integrated?: boolean; overlay?: boolean; pageTitle?: string; sidebarCollapsedOverride?: boolean }) => (
    <header
      data-testid="titlebar-stub"
      data-integrated={integrated ? 'true' : 'false'}
      data-overlay={overlay ? 'true' : 'false'}
      data-page-title={pageTitle ?? ''}
      data-sidebar-collapsed={sidebarCollapsedOverride === undefined ? 'unset' : String(sidebarCollapsedOverride)}
    />
  ),
}));

function renderLayout(path: string) {
  render(
    <MemoryRouter initialEntries={[path]}>
      <Routes>
        <Route element={<MainLayout />}>
          <Route path="*" element={<div data-testid="route-content" />} />
        </Route>
      </Routes>
    </MemoryRouter>,
  );
}

describe('MainLayout module isolation', () => {
  beforeEach(() => {
    const project = {
      id: 'local-project',
      path: '/tmp/local-project',
      name: 'local-project',
      createdAt: '',
      updatedAt: '',
      lastOpenedAt: '',
    };
    useOpencodeStore.setState({ activeProject: project });
    useProjectConfigStore.setState({
      configsByProjectId: {
        [project.id]: { ...createProjectConfig(), initialized: false },
      },
    });
    useSettingsStore.setState({ sidebarCollapsed: false });
  });

  it('does not overlay the local project initialization gate on AI painting', () => {
    renderLayout('/image-canvas');

    expect(screen.getByTestId('route-content')).toBeVisible();
    expect(screen.queryByTestId('project-initialization-gate')).not.toBeInTheDocument();
  });

  it('uses the full-height workspace shell for AI painting', () => {
    renderLayout('/image-canvas');

    expect(screen.getByTestId('main-content')).toHaveClass('basis-0', 'h-full', 'overflow-hidden', 'p-0');
    expect(screen.getByTestId('main-content')).not.toHaveClass('p-5', 'sm:p-6');
    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-overlay', 'true');
  });

  it('keeps the user sidebar preference while moving the inspiration title into the title bar', () => {
    renderLayout('/image-prompts');

    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-page-title', '获取灵感');
    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-overlay', 'false');
    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-sidebar-collapsed', 'unset');
    expect(screen.getByTestId('sidebar-stub')).toHaveAttribute('data-sidebar-collapsed', 'unset');
    expect(useSettingsStore.getState().sidebarCollapsed).toBe(false);
  });

  it('does not overlay the local project initialization gate on AI hardware', () => {
    const load = vi.fn().mockResolvedValue(undefined);
    useProjectConfigStore.setState({ load });
    renderLayout('/ai-hardware');

    expect(screen.getByTestId('route-content')).toBeVisible();
    expect(screen.queryByTestId('project-initialization-gate')).not.toBeInTheDocument();
    expect(load).not.toHaveBeenCalled();
  });

  it('keeps the local project initialization gate for AI programming routes', () => {
    renderLayout('/opencode-chat');

    expect(screen.getByTestId('project-initialization-gate')).toBeVisible();
    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-overlay', 'false');
  });

  it('keeps the programming workspace padding compensation separate from painting', () => {
    renderLayout('/opencode-chat');

    expect(screen.getByTestId('main-content')).toHaveClass('basis-0', 'overflow-hidden', 'p-0', 'sm:p-6');
  });

  it('gives the production learning Stage the full classroom width', () => {
    renderLayout('/learning/course/course-1');

    expect(screen.queryByTestId('sidebar-stub')).not.toBeInTheDocument();
    expect(screen.getByTestId('titlebar-stub')).toHaveAttribute('data-integrated', 'false');
    expect(screen.getByTestId('main-content')).toHaveClass('basis-0', 'h-full', 'overflow-hidden', 'p-0');
    expect(screen.getByTestId('route-content')).toBeVisible();
  });
});
