import { useEffect } from 'react'
import { Outlet, useLocation } from 'react-router-dom'
import PageShell from './PageShell'
import headerHtml from '../data/layout-header.html?raw'
import footerHtml from '../data/layout-footer.html?raw'
import WhatsAppButton from './WhatsAppButton'
import useThemeAssets from '../hooks/useThemeAssets'
import useLayoutInit from '../hooks/useLayoutInit'
import { PAGE_IDS } from '../config'

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

  useThemeAssets()
  useLayoutInit()

  useEffect(() => {
    let removed = false
    const removePreloader = () => {
      if (removed) return
      removed = true
      if (window.__removePreloader) {
        window.__removePreloader()
      }
    }
    const tryRemove = () => {
      if (window.__removePreloader && window.__cssReady && window.__layoutReady) {
        removePreloader()
        return true
      }
      return false
    }
    if (tryRemove()) return
    const onReady = () => tryRemove()
    document.addEventListener('css-ready', onReady)
    window.addEventListener('layout-ready', onReady)
    window.addEventListener('load', onReady)
    const fallback = setTimeout(removePreloader, 5000)
    return () => {
      document.removeEventListener('css-ready', onReady)
      window.removeEventListener('layout-ready', onReady)
      window.removeEventListener('load', onReady)
      clearTimeout(fallback)
    }
  }, [])

  useEffect(() => {
    window.scrollTo(0, 0)

    const path = pathname.replace(/\/$/, '') || '/'
    const pageId = PAGE_IDS[path] || 23
    const isHome = path === '/'

    if (window.elementorFrontendConfig) {
      window.elementorFrontendConfig.post = { id: pageId, title: 'Profen', excerpt: '', featuredImage: false }
    }

    document.body.className = [
      isHome ? 'home' : '',
      'wp-singular page-template page-template-template-builder page-template-template-builder-php',
      'page page-id-' + pageId,
      'wp-custom-logo wp-embed-responsive wp-theme-rakar theme-rakar',
      'woocommerce-no-js home-electrician',
      'elementor-default elementor-kit-2167 elementor-page elementor-page-' + pageId,
    ].filter(Boolean).join(' ')
  }, [pathname])


  return (
    <>
      <PageShell html={headerHtml} />
      <Outlet />
      <PageShell html={footerHtml} />
      <WhatsAppButton />
    </>
  )
}
