import test from 'node:test';
import assert from 'node:assert/strict';
import {
  allowPlazaEmbedFrame,
  appendPlazaEmbedQuery,
  injectPlazaEmbedBootstrap,
  isPlazaEmbedRequest,
  preparePublicationHtmlForEmbed,
  publishedPageCspForEmbed,
  stripPublicationHtmlCspMeta,
} from './plaza-embed.mjs';

test('isPlazaEmbedRequest detects embed=plaza', () => {
  assert.equal(isPlazaEmbedRequest({ embed: 'plaza' }), true);
  assert.equal(isPlazaEmbedRequest({ embed: 'other' }), false);
  assert.equal(isPlazaEmbedRequest({}), false);
});

test('appendPlazaEmbedQuery appends query once', () => {
  assert.equal(
    appendPlazaEmbedQuery('/u/john/pages/demo'),
    '/u/john/pages/demo?embed=plaza',
  );
  assert.equal(
    appendPlazaEmbedQuery('/u/john/pages/demo?embed=plaza'),
    '/u/john/pages/demo?embed=plaza',
  );
});

test('injectPlazaEmbedBootstrap adds script before closing body', () => {
  const html = '<!doctype html><html><body><h1>Hi</h1></body></html>';
  const out = injectPlazaEmbedBootstrap(html);
  assert.match(out, /plaza-embed-bootstrap/);
  assert.match(out, /<\/body>/);
});

test('publishedPageCspForEmbed allows inline script', () => {
  assert.match(publishedPageCspForEmbed(true), /script-src 'unsafe-inline'/);
});

test('allowPlazaEmbedFrame removes legacy X-Frame-Options header', () => {
  let removed = null;
  allowPlazaEmbedFrame({
    removeHeader(name) {
      removed = name;
    },
  });
  assert.equal(removed, 'X-Frame-Options');
});

test('stripPublicationHtmlCspMeta removes inline CSP meta tags', () => {
  const html =
    '<html><head><meta http-equiv="Content-Security-Policy" content="script-src \'none\'"></head><body></body></html>';
  const out = stripPublicationHtmlCspMeta(html);
  assert.doesNotMatch(out, /Content-Security-Policy/);
});

test('preparePublicationHtmlForEmbed strips CSP and injects bootstrap', () => {
  const html = `<!doctype html><html><head>
<meta http-equiv="Content-Security-Policy" content="script-src 'none'">
</head><body><section class="section">Hi</section></body></html>`;
  const out = preparePublicationHtmlForEmbed(html);
  assert.doesNotMatch(out, /http-equiv="Content-Security-Policy"/);
  assert.match(out, /plaza-embed-bootstrap/);
  assert.match(out, /plaza-embed-overrides/);
  assert.match(out, /\.hero\{height:auto!important;min-height:0!important/);
});

test('embed bootstrap does not cap tall publication height', () => {
  const html = '<!doctype html><html><body><main style="height:24000px">Tall</main></body></html>';
  const out = preparePublicationHtmlForEmbed(html);
  assert.doesNotMatch(out, /Math\.min\(measured,\s*16000\)/);
  assert.match(out, /body\.children\.length/);
  assert.match(out, /MutationObserver/);
});
