'use client'

import { createContext, useContext } from 'react'

export interface AccountUser {
  id: string
  name: string
  email: string
  phone: string | null
  emailVerified: boolean
}

const AccountUserContext = createContext<AccountUser | null>(null)

// Seeded once, server-side, by (root)/[locale]/account/layout.tsx — every
// page under /account reads the already-validated session's user from here
// instead of each doing its own `/api/frontend/auth/me` fetch (the old
// per-page pattern AccountLayout.tsx used to do, which is also what caused
// the brief loading-spinner flash before the real server-side redirect
// this layout now does).
export function AccountUserProvider({ user, children }: { user: AccountUser; children: React.ReactNode }) {
  return <AccountUserContext.Provider value={user}>{children}</AccountUserContext.Provider>
}

export function useAccountUser(): AccountUser {
  const ctx = useContext(AccountUserContext)
  if (!ctx) throw new Error('useAccountUser must be used within an /account route (AccountUserProvider)')
  return ctx
}
