/**
 * Component tests for SafeHtmlPreview — the sandboxed email-template preview.
 *
 * Context (security/xss): the admin Template Settings preview rendered
 * `template.body` via dangerouslySetInnerHTML, so admin-authored HTML executed
 * in the dashboard origin (admin-only self-XSS, but unnecessary). The fix
 * renders the HTML inside a sandboxed <iframe srcDoc> with NO allow-scripts, so
 * the markup can't run script or reach the parent DOM. No new dependency.
 */
import { render, screen } from '@testing-library/react';
import { SafeHtmlPreview } from '../SafeHtmlPreview';

describe('<SafeHtmlPreview>', () => {
    it('renders the html inside an iframe, not the parent DOM', () => {
        const { container } = render(<SafeHtmlPreview html="<p>hello</p>" title="Body Preview" />);
        const iframe = container.querySelector('iframe');
        expect(iframe).not.toBeNull();
        // The body must NOT become a LIVE node in the parent document — the
        // dangerouslySetInnerHTML path used to do exactly that.
        expect(container.querySelector('p')).toBeNull();
        // It must be carried by the iframe's srcDoc instead (string attribute).
        expect(iframe!.getAttribute('srcdoc')).toContain('<p>hello</p>');
    });

    it('sandboxes the iframe WITHOUT allow-scripts', () => {
        const { container } = render(<SafeHtmlPreview html="<p>x</p>" title="t" />);
        const iframe = container.querySelector('iframe')!;
        expect(iframe.hasAttribute('sandbox')).toBe(true);
        expect(iframe.getAttribute('sandbox') ?? '').not.toContain('allow-scripts');
    });

    it('does not surface a <script>/<img> payload as live nodes in the parent document', () => {
        const evil = '<img src=x onerror="window.__pwned=1"><script>window.__pwned=1<\/script>';
        const { container } = render(<SafeHtmlPreview html={evil} title="t" />);
        // The component never injects the payload as live nodes in the parent DOM.
        expect(container.querySelector('img')).toBeNull();
        expect(container.querySelector('script')).toBeNull();
        // The raw markup lives only in the sandboxed srcDoc.
        const iframe = container.querySelector('iframe')!;
        expect(iframe.getAttribute('srcdoc')).toContain('onerror');
    });

    it('exposes the title as the iframe accessibility label', () => {
        render(<SafeHtmlPreview html="<p>x</p>" title="Body Preview" />);
        expect(screen.getByTitle('Body Preview')).toBeInTheDocument();
    });
});
