import { describe, it, expect } from 'vitest';
import { parseHTML } from 'linkedom';
import { renderSafeMarkdown } from './markdown.js';

describe('renderSafeMarkdown', () => {
  const { document, window } = parseHTML('<!doctype html><html><body></body></html>');
  (globalThis as { document?: unknown }).document = document;
  (globalThis as { window?: unknown }).window = window;
  (globalThis as { marked?: { parse: (text: string) => string } }).marked = {
    parse: (text: string) => text,
  };

  it('removes script tags', () => {
    const html = renderSafeMarkdown('hello<script>alert(1)</script>');
    expect(html).not.toContain('<script');
    expect(html).toContain('hello');
  });

  it('removes inline event handlers', () => {
    const html = renderSafeMarkdown('<img src="https://example.com/x.png" onerror="alert(1)">');
    expect(html).toContain('<img');
    expect(html).not.toContain('onerror=');
  });

  it('removes javascript: href values', () => {
    const html = renderSafeMarkdown('<a href="javascript:alert(1)">click</a>');
    expect(html).toContain('<a');
    expect(html).not.toContain('javascript:');
  });

  it('adds rel noopener noreferrer for target=_blank links', () => {
    const html = renderSafeMarkdown('<a href="https://example.com" target="_blank">x</a>');
    expect(html).toContain('rel="noopener noreferrer"');
  });
});
