'use client'

import { useMemo } from 'react'

interface SvgPreviewProps {
  content: string
  fileName?: string
}

/**
 * SVG inline preview.
 * Sanitises the SVG content to prevent XSS before injecting into DOM.
 *
 * NOTE: We intentionally do NOT use DOMPurify here to avoid adding a new
 * dependency for a single use-case. A lightweight whitelist-based sanitiser
 * strips dangerous tags and attributes.
 */
const DANGEROUS_TAGS = new Set([
  'script', 'iframe', 'object', 'embed', 'form', 'input', 'textarea',
  'button', 'select', 'option', 'link', 'meta', 'base', 'style',
])

const DANGEROUS_ATTRS = new Set([
  'onabort', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onerror',
  'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown',
  'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onreset',
  'onresize', 'onselect', 'onsubmit', 'onunload', 'javascript:',
])

function sanitizeSvg(svg: string): string {
  const parser = new DOMParser()
  const doc = parser.parseFromString(svg, 'image/svg+xml')

  // Remove dangerous elements
  const allElements = doc.querySelectorAll('*')
  for (const el of Array.from(allElements)) {
    const tag = el.tagName.toLowerCase()
    if (DANGEROUS_TAGS.has(tag)) {
      el.remove()
      continue
    }
    // Strip dangerous attributes
    for (const attr of Array.from(el.attributes)) {
      const name = attr.name.toLowerCase()
      if (DANGEROUS_ATTRS.has(name) || name.startsWith('on')) {
        el.removeAttribute(attr.name)
      }
    }
  }

  return new XMLSerializer().serializeToString(doc)
}

export function SvgPreview({ content, fileName }: SvgPreviewProps) {
  const sanitized = useMemo(() => {
    try {
      return sanitizeSvg(content)
    } catch {
      return content
    }
  }, [content])

  return (
    <div className="flex flex-col h-full bg-surface-2">
      <div className="flex items-center justify-between px-3 py-1.5 border-b border-subtle bg-surface shrink-0">
        <span className="text-[11px] text-muted">SVG</span>
        {fileName && (
          <span className="text-[11px] text-tertiary truncate max-w-[200px]">{fileName}</span>
        )}
      </div>
      <div className="flex-1 flex items-center justify-center p-6 overflow-auto">
        <div
          className="max-w-full max-h-full"
          dangerouslySetInnerHTML={{ __html: sanitized }}
        />
      </div>
    </div>
  )
}
