import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

export default function useLayoutInit() {
  const { pathname } = useLocation()

  useEffect(() => {
    let destroyed = false
    let rafId = null

    function tryInit() {
      if (destroyed) return false
      if (typeof window.rakar_content_load_scripts === 'function') {
        window.rakar_content_load_scripts()
        window.__layoutReady = true
        window.dispatchEvent(new Event('layout-ready'))
        return true
      }
      return false
    }

    // Immediate attempt
    if (tryInit()) return

    // Poll with requestAnimationFrame for efficiency
    function poll() {
      if (!destroyed && !tryInit()) {
        rafId = requestAnimationFrame(poll)
      }
    }
    rafId = requestAnimationFrame(poll)

    // Fallback timeout (3 seconds)
    const fallback = setTimeout(() => {
      if (!destroyed) {
        window.__layoutReady = true
        window.dispatchEvent(new Event('layout-ready'))
        destroyed = true
        if (rafId) cancelAnimationFrame(rafId)
      }
    }, 3000)

    return () => {
      destroyed = true
      if (rafId) cancelAnimationFrame(rafId)
      clearTimeout(fallback)
    }
  }, [pathname])
}
