'use client';

/**
 * SafeHtmlPreview — renders untrusted/admin-authored HTML in a sandboxed
 * <iframe srcDoc> so it cannot execute script or touch the parent DOM.
 *
 * security/xss: the admin email-template preview previously used
 * dangerouslySetInnerHTML on `template.body`, executing admin-authored HTML in
 * the dashboard origin. The sandbox attribute is intentionally EMPTY — no
 * `allow-scripts`, no `allow-same-origin` — which is the maximally-restricted
 * mode: scripts are blocked and the frame gets a unique opaque origin, so it
 * can't reach `parent`, cookies, or storage. No new dependency (no DOMPurify).
 */

interface SafeHtmlPreviewProps {
    /** Raw HTML to preview. Treated as untrusted; never reaches the parent DOM. */
    html: string;
    /** Accessible label for the iframe (also used as the tooltip). */
    title: string;
    className?: string;
}

export function SafeHtmlPreview({ html, title, className = '' }: SafeHtmlPreviewProps) {
    // Wrap the body in a minimal document so isolated styling (e.g. the
    // {{var}} placeholder highlight injected by the caller) renders without
    // inheriting the dashboard's Tailwind classes, which don't cross the frame.
    const srcDoc = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>`
        + `body{margin:0;padding:12px;font:14px system-ui,-apple-system,sans-serif;color:#0f172a;}`
        + `.tpl-var{background:#fef3c7;color:#b45309;padding:0 .25rem;border-radius:.25rem;}`
        + `</style></head><body>${html}</body></html>`;

    return (
        <iframe
            title={title}
            sandbox=""
            srcDoc={srcDoc}
            className={`w-full min-h-40 bg-white rounded-lg border border-slate-200 dark:border-slate-700 ${className}`}
        />
    );
}
