/**
 * Source collaboration binding adapted from TeXlyre 0.10.16
 * (AGPL-3.0-or-later). Learnitive keeps its own project/session lifecycle while
 * delegating text, remote selections/carets and local collaborative undo to
 * y-codemirror.next.
 */
import type { Extension } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import type { Awareness } from 'y-protocols/awareness';
import { yCollab, yUndoManagerKeymap } from 'y-codemirror.next';
import type * as Y from 'yjs';

export function createCodeMirrorYjsBinding(
  yText: Y.Text,
  awareness: Awareness,
  undoManager: Y.UndoManager,
): Extension {
  return [
    yCollab(yText, awareness, { undoManager }),
    keymap.of(yUndoManagerKeymap),
    EditorView.baseTheme({
      '.cm-ySelectionCaret': { position: 'relative', zIndex: '4' },
      '.cm-ySelectionInfo': {
        opacity: '1 !important',
        visibility: 'visible',
        position: 'absolute',
        left: '-2px',
        top: '-20px',
        bottom: 'auto',
        maxWidth: '180px',
        overflow: 'hidden',
        padding: '2px 6px',
        borderRadius: '4px 4px 4px 0',
        color: '#ffffff',
        fontFamily: 'ui-sans-serif, system-ui, sans-serif',
        fontSize: '11px',
        fontWeight: '600',
        lineHeight: '16px',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        pointerEvents: 'none',
        zIndex: '5',
      },
    }),
  ];
}
