import { Navigate } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import { PageLoader } from '@/components/common/PageLoader'

/**
 * `/welcome` index — redirect to the next incomplete step (or `/` if done /
 * dismissed). Decision table:
 *
 *   onboarding_dismissed === true            → /home
 *   onboarding_step_completed >= 3           → /home
 *   onboarding_step_completed === null/0     → /welcome/step-1
 *   onboarding_step_completed === 1          → /welcome/step-2
 *   onboarding_step_completed === 2          → /welcome/step-3
 */
export function WelcomeRouter() {
  const user = useAuthStore((s) => s.user)

  // Auth gate sits above us — but if the user object is still loading, render
  // the page loader rather than racing past the redirect.
  if (!user) return <PageLoader />

  if (user.onboarding_dismissed) return <Navigate to="/home" replace />

  const completed = user.onboarding_step_completed ?? 0
  if (completed >= 3) return <Navigate to="/home" replace />
  if (completed === 2) return <Navigate to="/welcome/step-3" replace />
  if (completed === 1) return <Navigate to="/welcome/step-2" replace />
  return <Navigate to="/welcome/step-1" replace />
}

export default WelcomeRouter
