'use client'

import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Loader2 } from 'lucide-react'
import { getViewport, type ViewportId } from './viewports.js'

interface SitePreviewFrameProps {
  /** Public draft URL; null while the preview token is still minting. */
  src: string | null
  viewport: ViewportId
  /** Changing this remounts the iframe so it reloads the persisted draft. */
  reloadKey: number
  title?: string
}

/**
 * Inline branded preview surface — replaces the editor canvas with an iframe
 * of the consumer's real public route rendering the draft (site CSS, real
 * components). Sized to the selected viewport's logical width and scaled to
 * fit the canvas column, mirroring {@link EditorCanvas}.
 */
export function SitePreviewFrame({
  src,
  viewport,
  reloadKey,
  title = 'Site preview',
}: SitePreviewFrameProps) {
  const vp = getViewport(viewport)
  const containerRef = useRef<HTMLDivElement>(null)
  const [scale, setScale] = useState(1)
  const [frameHeight, setFrameHeight] = useState(600)
  const [loaded, setLoaded] = useState(false)

  useLayoutEffect(() => {
    const container = containerRef.current
    if (!container) return
    const recompute = () => {
      // 48px breathing room, matching EditorCanvas.
      const availableW = container.clientWidth - 48
      const availableH = container.clientHeight - 48
      const next = Math.min(1, availableW / vp.width)
      setScale(next > 0 ? next : 1)
      setFrameHeight(availableH > 0 ? availableH : 600)
    }
    recompute()
    const ro = new ResizeObserver(recompute)
    ro.observe(container)
    return () => ro.disconnect()
  }, [vp.width])

  useEffect(() => {
    setLoaded(false)
  }, [src, reloadKey])

  return (
    <div ref={containerRef} className="bg-muted relative h-full overflow-hidden p-6">
      {(!src || !loaded) && (
        <div
          className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2"
          aria-live="polite"
        >
          <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
          <span className="text-muted-foreground text-sm">Loading site preview…</span>
        </div>
      )}
      {src && (
        <div className="mx-auto" style={{ width: vp.width * scale, height: frameHeight }}>
          <iframe
            key={reloadKey}
            src={src}
            title={title}
            onLoad={() => setLoaded(true)}
            className="border-border bg-card rounded-xl border shadow-sm"
            style={{
              width: vp.width,
              height: frameHeight / scale,
              transform: `scale(${scale})`,
              transformOrigin: 'top left',
            }}
          />
        </div>
      )}
    </div>
  )
}
