'use client'

import { useMemo } from 'react'
import { ExternalLink } from 'lucide-react'

interface HtmlPreviewProps {
  content: string
  /** Absolute file path (including workspace root) used to inject <base> tag */
  filePath?: string
  /** Workspace ID for building raw API base URLs */
  workspaceId?: string
  onOpenExternal?: () => void
}

/**
 * Inject a <base> tag so that relative paths (CSS, JS, images) in the HTML
 * resolve against the file's directory via the workspace raw API.
 */
function injectBaseTag(html: string, filePath?: string, workspaceId?: string): string {
  if (!filePath || !workspaceId) return html

  const lastSlash = filePath.lastIndexOf('/')
  const dirPath = lastSlash >= 0 ? filePath.substring(0, lastSlash + 1) : ''
  if (!dirPath) return html

  const baseHref = `/api/workspaces/${workspaceId}/raw?path=${encodeURIComponent(dirPath)}`
  const baseTag = `<base href="${baseHref}">`

  if (html.includes('<head>')) {
    return html.replace('<head>', `<head>\n    ${baseTag}`)
  }
  // Prepend if no <head> present
  return baseTag + '\n' + html
}

/**
 * Isolated HTML preview for project file editors.
 *
 * Security design:
 * - Uses iframe srcDoc for isolation from the main Forge UI.
 * - sandbox="allow-same-origin" intentionally disables scripts.
 *   (allow-same-origin + allow-scripts would let the iframe break out of
 *   the sandbox and access host APIs.)
 * - A "Open in browser" button is provided for users who need script execution.
 */
export function HtmlPreview({ content, filePath, workspaceId, onOpenExternal }: HtmlPreviewProps) {
  const srcDoc = useMemo(
    () => injectBaseTag(content, filePath, workspaceId),
    [content, filePath, workspaceId]
  )

  return (
    <div className="flex flex-col h-full">
      <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">HTML Preview (scripts disabled)</span>
        {onOpenExternal && (
          <button
            onClick={onOpenExternal}
            className="flex items-center gap-1 px-2 py-0.5 rounded text-[11px] text-brand hover:bg-surface-hover transition-colors"
            title="Open with default browser"
          >
            <ExternalLink size={10} />
            <span>Open in browser</span>
          </button>
        )}
      </div>
      <iframe
        title="HTML Preview"
        sandbox="allow-same-origin"
        srcDoc={srcDoc}
        className="flex-1 w-full border-0 bg-white"
      />
    </div>
  )
}
