"use client"

import { ObfuscatedEmail } from "@/components/obfuscated-email"
import { ObfuscatedAddress } from "@/components/obfuscated-address"

interface ImprintBodyProps {
  html: string
}

/**
 * Renders imprint HTML with {email} and {address} placeholders replaced by
 * ObfuscatedEmail and ObfuscatedAddress components.
 */
export function ImprintBody({ html }: ImprintBodyProps) {
  const placeholderRegex = /\{(email|address)\}/g
  const parts: (string | React.ReactNode)[] = []
  let lastIndex = 0
  let match
  let key = 0

  while ((match = placeholderRegex.exec(html)) !== null) {
    const before = html.slice(lastIndex, match.index)
    if (before) {
      parts.push(
        <span
          key={`html-${key++}`}
          style={{ display: "contents" }}
          dangerouslySetInnerHTML={{ __html: before }}
        />
      )
    }
    if (match[1] === "email") {
      parts.push(
        <ObfuscatedEmail
          key={`email-${key++}`}
          className="text-emerald-600 outline-none transition-colors hover:text-emerald-500 focus-visible:ring-2 focus-visible:ring-emerald-500 focus-visible:ring-offset-2"
        />
      )
    } else {
      parts.push(<ObfuscatedAddress key={`addr-${key++}`} />)
    }
    lastIndex = match.index + match[0].length
  }

  const after = html.slice(lastIndex)
  if (after) {
    parts.push(
      <span
        key={`html-${key++}`}
        style={{ display: "contents" }}
        dangerouslySetInnerHTML={{ __html: after }}
      />
    )
  }

  return <>{parts}</>
}
