import assert from 'node:assert/strict';
import test from 'node:test';
import {
  MINDSPACE_PAGE_CONTENT_MESSAGE,
  buildEditablePreviewDocument,
} from './src/utils/mindspaceVisualEditor.ts';

test('buildEditablePreviewDocument injects visual editor into body', () => {
  const html = '<!doctype html><html><head></head><body><p>Hi</p></body></html>';
  const result = buildEditablePreviewDocument(html);

  assert.match(result, /mindspace-visual-editor-style/);
  assert.match(result, /mindspace-visual-editor-script/);
  assert.match(result, /data-mindspace-editing/);
  assert.match(result, /<p>Hi<\/p>/);
  assert.match(result, new RegExp(MINDSPACE_PAGE_CONTENT_MESSAGE.replace(':', '\\:')));
});

test('buildEditablePreviewDocument wraps fragment html', () => {
  const result = buildEditablePreviewDocument('<section>块</section>');
  assert.match(result, /<section>块<\/section>/);
  assert.match(result, /<\/body>/);
});

test('buildEditablePreviewDocument provides blank fallback', () => {
  const result = buildEditablePreviewDocument('');
  assert.match(result, /空白页面/);
});

test('buildEditablePreviewDocument strips CSP meta so editor script can run', () => {
  const html = `<!DOCTYPE html><html><head>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'none'">
</head><body><h1>探索世界</h1></body></html>`;
  const result = buildEditablePreviewDocument(html);

  assert.doesNotMatch(result, /Content-Security-Policy/);
  assert.match(result, /mindspace-visual-editor-script/);
  assert.match(result, /<h1>探索世界<\/h1>/);
});
