"use client"

import { useEffect, useState } from "react"
import { usePathname } from "next/navigation"

import { useUserProfile } from "@/hooks/use-user-profile"
import { useVersionedRouter } from "@/hooks/use-versioned-router"

export const WELCOME_PATH = "/welcome"

/** Sent by the welcome screen once the name is saved (the gate lives in the shared layout and keeps its profile). */
export const NAME_SAVED_EVENT = "rangook:name-saved"

/** Until the learner has a name, every signed-in screen leads to «اسمت چیست؟». */
export default function NameGate() {
  const profile = useUserProfile()
  const pathname = usePathname().replace(/\/$/, "")
  const router = useVersionedRouter()
  const [named, setNamed] = useState(false)

  useEffect(() => {
    const saved = () => setNamed(true)
    window.addEventListener(NAME_SAVED_EVENT, saved)
    return () => window.removeEventListener(NAME_SAVED_EVENT, saved)
  }, [])

  useEffect(() => {
    if (profile?.needs_name && !named && pathname !== WELCOME_PATH) router.replace(WELCOME_PATH)
  }, [profile?.needs_name, named, pathname, router])

  return null
}
