'use client'

import { useEffect, useRef, useState, type ReactNode } from 'react'

type Props = {
  children: ReactNode
  /** Wenn true: sofort mounten (ohne IntersectionObserver) */
  force?: boolean
  /** Vorladen bevor es wirklich sichtbar ist */
  rootMargin?: string
  /** Optional: Platzhalter bis mounted */
  placeholder?: ReactNode
  className?: string
}

export default function LazyMount({
  children,
  force = false,
  rootMargin = '300px',
  placeholder = null,
  className,
}: Props) {
  const ref = useRef<HTMLDivElement | null>(null)
  const [mounted, setMounted] = useState<boolean>(force)

  // Wenn force später true wird (z.B. inlinePlay startet) -> sofort mounten
  useEffect(() => {
    if (force && !mounted) setMounted(true)
  }, [force, mounted])

  useEffect(() => {
    if (mounted || force) return
    const el = ref.current
    if (!el) return

    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          setMounted(true)
          io.disconnect()
        }
      },
      { rootMargin }
    )

    io.observe(el)
    return () => io.disconnect()
  }, [mounted, force, rootMargin])

  return (
    <div ref={ref} className={className}>
      {mounted ? children : placeholder}
    </div>
  )
}
