import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { usePlatformAuth } from '../../auth/platform-auth'
import { buildLoginRedirectTarget } from '../../auth/route-guard'
import { buildSupportPath } from '../../site-routes'
import { HyperTwistButtonLink } from '../ui/HyperTwistButton'
import { GeneralPageLoader } from '../ui/Skeletons'

export function ProtectedRoute() {
  const { isAuthenticated, isLoading } = usePlatformAuth()
  const location = useLocation()
  const loginRedirectTarget = buildLoginRedirectTarget(location)

  if (isLoading) {
    return (
      <GeneralPageLoader
        title="Loading your account..."
        eyebrow="Signed-in website access"
        description="Checking your saved session, download access, and desktop pairing so your dashboard opens in the right state."
        fullscreen
        showBrand
      >
        <div className="button-row general-page-loader-actions">
          <HyperTwistButtonLink tone="ghost" to={loginRedirectTarget}>
            Open sign-in
          </HyperTwistButtonLink>
          <HyperTwistButtonLink tone="ghost" to={buildSupportPath('operator-access')}>
            Open support
          </HyperTwistButtonLink>
        </div>
      </GeneralPageLoader>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to={loginRedirectTarget} replace />
  }

  return <Outlet />
}
