import DOMPurify from 'isomorphic-dompurify';
import { useId, useMemo } from 'react';
import type { HtmlSpec } from '@/lib/agent-stream';

// Keep this in lockstep with the backend allowlist in
// App\Support\Agent\ArtifactValidator::sanitizeHtml().
const ALLOWED_TAGS = [
    'p',
    'h1',
    'h2',
    'h3',
    'ul',
    'ol',
    'li',
    'table',
    'thead',
    'tbody',
    'tr',
    'th',
    'td',
    'strong',
    'em',
    'span',
    'div',
    'br',
    'hr',
    'section',
    'header',
    'footer',
    'article',
    'figure',
    'figcaption',
    'small',
    'blockquote',
    'code',
    'pre',
    'mark',
    'b',
    'i',
];

export function HtmlMessage({
    htmlSpec,
    artifactId,
}: {
    htmlSpec: HtmlSpec;
    artifactId: string;
}) {
    const titleId = useId();

    const sanitizedHtml = useMemo(
        () =>
            DOMPurify.sanitize(htmlSpec.html, {
                ALLOWED_TAGS,
                ALLOWED_ATTR: ['class'],
            }),
        [htmlSpec.html],
    );

    if (sanitizedHtml.trim() === '') {
        return null;
    }

    return (
        <figure
            className="my-3 w-full max-w-2xl min-w-0 overflow-hidden rounded-xl border border-border bg-card p-4"
            aria-labelledby={htmlSpec.title ? titleId : undefined}
            data-artifact-id={artifactId}
        >
            {htmlSpec.title ? (
                <figcaption
                    id={titleId}
                    className="mb-3 text-sm font-medium text-foreground"
                >
                    {htmlSpec.title}
                </figcaption>
            ) : null}
            <div
                className="agent-html-content prose prose-sm prose-headings:text-foreground prose-p:text-muted-foreground prose-strong:text-foreground prose-table:text-sm max-w-none text-foreground"
                dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
            />
        </figure>
    );
}
