"use client";

import DOMPurify, { Config } from "dompurify";

// Standard HTML tags only (exclude custom elements like elevenlabs-convai)
type StandardHTMLTag =
  | "div"
  | "span"
  | "p"
  | "article"
  | "section"
  | "main"
  | "aside"
  | "header"
  | "footer"
  | "nav";

interface SafeHTMLProps {
  html: string;
  className?: string;
  tag?: StandardHTMLTag;
  allowedTags?: string[];
  allowedAttributes?: Record<string, string[]>;
}

/**
 * SafeHTML Component - XSS Protection
 *
 * Sanitizes HTML content using DOMPurify to prevent XSS attacks.
 * Use this component whenever rendering user-generated or untrusted HTML.
 *
 * @example
 * <SafeHTML html={userContent} className="prose" />
 *
 * @example Custom configuration
 * <SafeHTML
 *   html={content}
 *   allowedTags={['p', 'a', 'strong']}
 *   allowedAttributes={{ a: ['href'] }}
 * />
 */
export function SafeHTML({
  html,
  className,
  tag: Tag = "div",
  allowedTags,
  allowedAttributes,
}: SafeHTMLProps) {
  // Flatten custom allowedAttributes to array for DOMPurify
  const defaultAttrs = [
    "href",
    "title",
    "target",
    "rel",
    "src",
    "alt",
    "width",
    "height",
    "class",
  ];
  const customAttrs = allowedAttributes
    ? Object.values(allowedAttributes).flat()
    : defaultAttrs;

  const config: Config = {
    ALLOWED_TAGS: allowedTags || [
      "p",
      "br",
      "strong",
      "em",
      "u",
      "a",
      "ul",
      "ol",
      "li",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "blockquote",
      "code",
      "pre",
      "span",
      "div",
      "img",
    ],
    ALLOWED_ATTR: customAttrs,
    ALLOWED_URI_REGEXP:
      /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
    ALLOW_DATA_ATTR: false,
    KEEP_CONTENT: true,
    RETURN_TRUSTED_TYPE: false,
    FORBID_TAGS: [
      "script",
      "style",
      "iframe",
      "object",
      "embed",
      "link",
      "base",
      "meta",
    ],
    FORBID_ATTR: [
      "onerror",
      "onload",
      "onclick",
      "onmouseover",
      "onfocus",
      "onblur",
      "style",
    ],
  };

  const sanitized = DOMPurify.sanitize(html, config);

  return (
    <Tag
      className={className}
      dangerouslySetInnerHTML={{ __html: sanitized }}
    />
  );
}
