import { describe, expect, it } from 'vitest';

import {
  hasEquivalentMarkdownSemantics,
  normalizeLiveMarkdownUpdate,
} from './markdown-fidelity';

describe('markdown semantic fidelity', () => {
  it('accepts equivalent list markers, rules, and table delimiter widths', () => {
    const source = [
      '- first',
      '- second',
      '',
      '---',
      '',
      '| A | B |',
      '| --- | :---: |',
      '| 1 | 2 |',
    ].join('\n');
    const normalized = [
      '* first',
      '* second',
      '',
      '***',
      '',
      '| A | B |',
      '| - | :-: |',
      '| 1 | 2 |',
      '',
    ].join('\n');

    expect(hasEquivalentMarkdownSemantics(source, normalized)).toBe(true);
  });

  it('preserves a valid single-column table', () => {
    expect(
      hasEquivalentMarkdownSemantics('| A |\n| --- |', '| A |\n| - |'),
    ).toBe(true);
  });

  it.each([
    ['mixed list boundaries', '- first\n* second', '* first\n* second'],
    ['tight and loose lists', '- first\n- second', '* first\n\n* second'],
    ['setext and thematic breaks', 'Heading\n---', 'Heading\n***'],
    ['fenced code content', '```\n- code\n```', '```\n* code\n```'],
    ['indented code content', '    - code', '    * code'],
    ['invalid table-like text', 'A | B | C\n--- | ---', 'A | B | C\n- | -'],
  ])('rejects %s changes', (_name, source, normalized) => {
    expect(hasEquivalentMarkdownSemantics(source, normalized)).toBe(false);
  });
});

describe('live markdown normalization', () => {
  it('removes empty paragraph markers introduced by the live editor', () => {
    expect(
      normalizeLiveMarkdownUpdate(
        '# Title\n\nFirst\n\nSecond\n',
        '# Title\n\n<br />\n\nFirst\n\n<br />\n\nSecond\n',
      ),
    ).toBe('# Title\n\nFirst\n\nSecond\n');
  });

  it('preserves explicit standalone HTML breaks from source mode', () => {
    const source = '# Title\n\n<br />\n\nText\n';
    expect(normalizeLiveMarkdownUpdate(source, source)).toBe(source);
  });
});
