import { describe, test, expect } from 'vitest';
import { renderEditorHarness } from '../test-utils/editorHarness';
import { repairOrphanNodes } from '../utils/orphan-repair';
import { EMPTY_CANVAS } from './PageContext';

describe('EMPTY_CANVAS is exported and loadable', () => {
  test('deserializing EMPTY_CANVAS gives a ROOT with no children', () => {
    const harness = renderEditorHarness({ initialState: EMPTY_CANVAS });
    const nodes = JSON.parse(harness.getSerialized());
    expect(nodes.ROOT.nodes).toEqual([]);
    harness.unmount();
  });
});

describe('repaired state survives a real Craft deserialize', () => {
  test('an orphaned HTML block becomes a selectable child of ROOT', () => {
    const broken = JSON.stringify({
      ROOT: {
        type: { resolvedName: 'Container' },
        isCanvas: true,
        props: { style: {}, tag: 'div' },
        displayName: 'Container',
        custom: {}, hidden: false, nodes: [], linkedNodes: {}, parent: null,
      },
      stray: {
        type: { resolvedName: 'HtmlBlock' },
        isCanvas: false,
        props: { code: '<p>stranded</p>', style: {} },
        displayName: 'HTML',
        custom: {}, hidden: false, nodes: [], linkedNodes: {}, parent: 'ghost',
      },
    });

    const { state, repaired } = repairOrphanNodes(broken);
    expect(repaired).toEqual(['stray']);

    const harness = renderEditorHarness({ initialState: state });
    const nodes = JSON.parse(harness.getSerialized());
    expect(nodes.ROOT.nodes).toContain('stray');
    expect(harness.container.textContent).toContain('stranded');
    harness.unmount();
  });
});
