/**
 * The single place in the app layer that knows which package renders the
 * editing surface. Everything else in the app interacts with the editor via
 * the `editorEngine` service slot (`EditorEngineContract`).
 *
 * Known exception to the engine-agnostic seam: the surface component itself
 * is engine-specific because it renders the engine's own overlay UI (slash
 * menu, link menu, table menu, ...). This module is therefore the per-engine
 * component switch (plans/011-wordgard-editor-w-migration.md).
 */
import { useCoreServices } from '@learnitive/context';
import { isProjectCodeTextPath, isLearnitiveEditableTextPath } from '@learnitive/project-storage';
import { WsPath } from '@learnitive/ws-path';
import type { LatexCodeMirrorPersistedState } from '@learnitive/latex-codemirror';
import { Editor as PmEditor } from '@learnitive/editor';
import { Editor as WordgardEditor } from '@learnitive/editor-w';
import React from 'react';
import type { LatexDocumentController } from '../latex-document-controller';
import type { PaperMemoryManuscriptSelection } from '../paper-memory-manuscript';
import type { ReviewCommentTarget } from './review-comment-dialog';
import { LatexSourceEditor } from './latex-source-editor';
import { ProjectCodeEditor } from './project-code-editor';

export function EditorSurface(props: {
  wsPath: string;
  name: string;
  className?: string;
  active?: boolean;
  restoredState?: LatexCodeMirrorPersistedState;
  onPersistState?: (state: LatexCodeMirrorPersistedState, revision: number) => void;
  latexDocumentController?: LatexDocumentController;
  onManuscriptSelectionChange?: (selection: PaperMemoryManuscriptSelection | undefined) => void;
  onRequestReviewComment?: (target: ReviewCommentTarget) => void;
  onOpenReviewThread?: (threadId: string) => void;
  onOpenPaper?: (paperId: string, page?: number) => void;
}) {
  const { editorEngine } = useCoreServices();
  const filePath = WsPath.safeParseFile(props.wsPath).data;
  if (filePath && isLearnitiveEditableTextPath(filePath.path)) {
    return <LatexSourceEditor {...props} />;
  }
  if (filePath && isProjectCodeTextPath(filePath.path)) {
    return <ProjectCodeEditor wsPath={props.wsPath} className={props.className} onOpenReviewThread={props.onOpenReviewThread} />;
  }

  const Surface =
    editorEngine.engineId === 'wordgard' ? WordgardEditor : PmEditor;

  const { restoredState: _restoredState, onPersistState: _onPersistState, latexDocumentController: _latexDocumentController, onManuscriptSelectionChange: _onManuscriptSelectionChange, onRequestReviewComment: _onRequestReviewComment, onOpenReviewThread: _onOpenReviewThread, onOpenPaper: _onOpenPaper, ...editorProps } = props;
  return <Surface {...editorProps} />;
}
