import React, { lazy, Suspense } from 'react'
import { createRoot } from 'react-dom/client'

// Sub-section components — lazy-loaded so only the hero blocks the initial bundle
import HomeHero from './HomeHero'

const HomeTrending  = lazy(() => import('./HomeTrending'))
const HomeFresh     = lazy(() => import('./HomeFresh'))
const HomeTags      = lazy(() => import('./HomeTags'))
const HomeCreators  = lazy(() => import('./HomeCreators'))
const HomeNews      = lazy(() => import('./HomeNews'))

function SectionFallback() {
  return (
    <div className="mt-14 h-48 animate-pulse rounded-xl bg-nova-800 mx-4 sm:mx-6 lg:mx-8" />
  )
}

function HomePage({ hero, trending, fresh, tags, creators, news }) {
  return (
    <div className="pb-24">
      {/* Hero — above-fold, eager */}
      <HomeHero artwork={hero} />

      {/* Below-fold sections — lazy */}
      <Suspense fallback={<SectionFallback />}>
        <HomeTrending items={trending} />
      </Suspense>

      <Suspense fallback={<SectionFallback />}>
        <HomeFresh items={fresh} />
      </Suspense>

      <Suspense fallback={<SectionFallback />}>
        <HomeTags tags={tags} />
      </Suspense>

      <Suspense fallback={<SectionFallback />}>
        <HomeCreators creators={creators} />
      </Suspense>

      <Suspense fallback={<SectionFallback />}>
        <HomeNews items={news} />
      </Suspense>
    </div>
  )
}

// Auto-mount when the Blade view provides #homepage-root
const mountEl = document.getElementById('homepage-root')
if (mountEl) {
  let props = {}
  try {
    const propsEl = document.getElementById('homepage-props')
    props = propsEl ? JSON.parse(propsEl.textContent || '{}') : {}
  } catch {
    props = {}
  }

  createRoot(mountEl).render(<HomePage {...props} />)
}

export default HomePage
