"use client"

import { displayFileName } from "@/lib/drive/display-file-name"
import { cn } from "@/lib/utils"

type SvgPreviewViewerProps = {
  markup: string
  name: string
  className?: string
}

function svgToSrcDoc(markup: string): string {
  const trimmed = markup.trim()
  const lower = trimmed.toLowerCase()
  if (lower.startsWith("<!doctype") || lower.startsWith("<html")) return trimmed
  return `<!DOCTYPE html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:transparent}svg{max-width:100%;max-height:100%;width:auto;height:auto}</style></head><body>${trimmed}</body></html>`
}

/** Sandboxed inline SVG — avoids blob MIME issues (Nextcloud often serves text/xml). */
export function SvgPreviewViewer({ markup, name, className }: SvgPreviewViewerProps) {
  return (
    <iframe
      title={displayFileName(name)}
      srcDoc={svgToSrcDoc(markup)}
      sandbox=""
      className={cn(
        "h-full min-h-[120px] w-full max-w-full flex-1 border-0 bg-transparent",
        className
      )}
    />
  )
}
