import { type ReactNode, Suspense, useState, useEffect } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { PageLoader } from './PageLoader'

// Mounts only once Suspense has resolved (chunk is ready).
// Signals the parent to hide the loader and reveal content.
function ContentReady({ onReady }: { onReady: () => void }) {
  useEffect(() => {
    onReady()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return null
}

type Props = { children: ReactNode }

export function ProtectedRoute({ children }: Props) {
  const { user, loading } = useAuth()
  const location = useLocation()

  // On page refresh: loading starts true → contentReady=false → loader shows throughout.
  // On in-app navigation: loading is already false → contentReady=true → no loader shown.
  const [contentReady, setContentReady] = useState(() => !loading)

  if (!loading && !user) {
    return <Navigate to="/" state={{ from: location }} replace />
  }

  const showLoader = loading || !contentReady

  return (
    <>
      {showLoader && <PageLoader />}
      {!loading && user && (
        <div style={{ display: contentReady ? 'contents' : 'none' }}>
          <Suspense fallback={null}>
            <ContentReady onReady={() => setContentReady(true)} />
            {children}
          </Suspense>
        </div>
      )}
    </>
  )
}
