"use client"

import { usePersistHydrated } from "@/hooks/use-persist-hydrated"
import { useAuthStore } from "@/lib/api/auth-store"
import { useCurrentUser } from "@/lib/api/hooks/use-current-user"
import { useAccountStore, useActiveAccount } from "@/lib/stores/account-store"
import { DEMO_USER } from "@/components/demo/demo-mail-data"
import { useIsDemoApp } from "@/lib/demo/use-is-demo-app"

/** Identity shown in header avatar / account menu (OIDC user, else active mail account). */
export function useChromeIdentity(): {
  name: string
  email: string
  firstName: string
  avatarUrl?: string
} | null {
  const isDemoApp = useIsDemoApp()
  const authHydrated = usePersistHydrated(useAuthStore)
  const accountHydrated = usePersistHydrated(useAccountStore)
  const platformUser = useAuthStore((s) => s.user)
  const mailAccount = useActiveAccount()
  const { data: currentUser } = useCurrentUser()

  if (isDemoApp) {
    return {
      name: DEMO_USER.name,
      email: DEMO_USER.email,
      firstName: DEMO_USER.name.split(/\s+/)[0] ?? DEMO_USER.name,
    }
  }

  // Keep SSR and first client render identical until persist stores rehydrate.
  if (!authHydrated) return null
  if (!platformUser && !accountHydrated) return null

  if (platformUser) {
    return {
      name: platformUser.name,
      email: platformUser.email,
      firstName: platformUser.firstName,
      avatarUrl: currentUser?.avatar_url,
    }
  }

  if (mailAccount) {
    const firstName = mailAccount.name.split(/\s+/)[0] ?? mailAccount.name
    return {
      name: mailAccount.name,
      email: mailAccount.email,
      firstName,
      avatarUrl: mailAccount.avatarUrl,
    }
  }

  return null
}
