import { describe, expect, it } from 'vitest';
import {
  canonicalOffsetToEditorOffset,
  detectLatexLineEnding,
  editorInsertedTextToCanonical,
  editorOffsetToCanonicalOffset,
  latexSourceToEditorText,
} from '../line-endings';

describe('LaTeX line-ending mapping', () => {
  it('keeps LF-only editor offsets identical to canonical offsets', () => {
    const source = 'alpha\nbeta\ngamma\n';
    expect(detectLatexLineEnding(source)).toBe('\n');
    expect(canonicalOffsetToEditorOffset(source, 8)).toBe(8);
    expect(editorOffsetToCanonicalOffset(source, 8)).toBe(8);
    expect(latexSourceToEditorText(source)).toBe(source);
    expect(editorInsertedTextToCanonical(source, 'x')).toBe('x');
  });

  it('preserves CRLF canonical offsets while CodeMirror uses LF', () => {
    const source = 'alpha\r\nbeta\r\ngamma\r\n';
    const editor = 'alpha\nbeta\ngamma\n';
    expect(detectLatexLineEnding(source)).toBe('\r\n');
    expect(latexSourceToEditorText(source)).toBe(editor);

    const canonicalBeta = source.indexOf('beta');
    const editorBeta = editor.indexOf('beta');
    expect(canonicalOffsetToEditorOffset(source, canonicalBeta)).toBe(editorBeta);
    expect(editorOffsetToCanonicalOffset(source, editorBeta)).toBe(canonicalBeta);
    expect(editorInsertedTextToCanonical(source, '\nnext')).toBe('\r\nnext');
  });

  it('does not rewrite ordinary non-newline insertions in CRLF projects', () => {
    const source = 'alpha\r\nbeta\r\n';
    expect(editorInsertedTextToCanonical(source, String.raw`\\cite{key}`)).toBe(String.raw`\\cite{key}`);
  });
});
