"use client"

import { useEffect, useRef } from "react"

interface Props {
  html: string
}

export default function VideoPlayerEmbed({ html }: Props) {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!html || !containerRef.current) return

    const container = containerRef.current
    container.innerHTML = ""

    const wrapper = document.createElement("div")
    wrapper.innerHTML = html

    const scripts = wrapper.querySelectorAll("script")

    const cloned = wrapper.cloneNode(true) as HTMLElement
    cloned.querySelectorAll("script").forEach(s => s.remove())

    if (cloned.innerHTML.trim()) container.appendChild(cloned)

    scripts.forEach(oldScript => {
      const newScript = document.createElement("script")
      Array.from(oldScript.attributes).forEach(attr => {
        newScript.setAttribute(attr.name, attr.value)
      })
      newScript.text = oldScript.text
      container.appendChild(newScript)
    })
  }, [html])

  return (
    <div className="relative w-full rounded-xl overflow-hidden min-h-[200px]">

      <div
        className="absolute inset-0 flex flex-col items-center justify-center px-4 text-center text-white text-shadow-lg pointer-events-none select-none bg-cover bg-center"
        style={{
          zIndex: 10,
          backgroundImage: 'url("/images/video/video_cover.jpg")'
        }}
      >
        <span>
          لطفا تا بارگذاری ویدیو صبور باشید
        </span>
        <span>
          و حداقل ۱ دقیقه به دلیل شرایط اینترنت در صفحه بمانید
        </span>
      </div>

      <div ref={containerRef} className="relative z-20 w-full h-full" />
    </div>
  )
}
