"use client"

import * as React from "react"

import { cn } from "@/lib/utils"

import { readHostThemeMode, useStudioEmbedTheme } from "./use-studio-embed-theme"

export type StudioEmbed = { url: string; origin: string }

/**
 * One Extraction Studio document, framed.
 *
 * Wears the host theme (see `useStudioEmbedTheme`) and reports when a reviewer saves a
 * correction inside Studio, so the host can re-read the result.
 */
export function StudioEmbedFrame({
  embed,
  onCorrected,
  className,
}: {
  embed: StudioEmbed
  onCorrected?: () => void
  className?: string
}) {
  const frameRef = React.useRef<HTMLIFrameElement>(null)

  // The mode rides in the URL so the first paint already matches; later changes are pushed by
  // useStudioEmbedTheme, which must not reload the frame.
  const src = React.useMemo(
    () =>
      `${embed.url}&parent_origin=${encodeURIComponent(window.location.origin)}&theme=${readHostThemeMode()}`,
    [embed.url],
  )
  useStudioEmbedTheme(frameRef, embed.origin)

  React.useEffect(() => {
    if (!onCorrected) return
    const onMessage = (event: MessageEvent) => {
      if (event.origin !== embed.origin || event.source !== frameRef.current?.contentWindow) return
      const data = event.data as { source?: string; type?: string } | null
      if (data?.source === "extraction-studio" && data.type === "corrected") onCorrected()
    }
    window.addEventListener("message", onMessage)
    return () => window.removeEventListener("message", onMessage)
  }, [embed.origin, onCorrected])

  return (
    <iframe
      ref={frameRef}
      key={src}
      src={src}
      title="Extraction Studio"
      className={cn("min-h-0 w-full flex-1 border-0", className)}
    />
  )
}
