import { useNostrAuth } from '@/hooks/useNostrAuth'
import { ConnectedUserMenu } from './ConnectedUserMenu'
import { RecoveryStep } from './CreateAccountModalSteps'
import { UnlockAccountModal } from './UnlockAccountModal'
import type { NostrProfile } from '@/types/nostr'
import { Button } from './ui'
import { t } from '@/lib/i18n'
import { getConnectButtonMode } from './connectButton/connectButtonMode'
import { useAutoConnect, useConnectButtonUiState } from './connectButton/useConnectButtonUiState'
function ConnectForm({
onCreateAccount,
onUnlock,
loading,
error,
}: {
onCreateAccount: () => void
onUnlock: () => void
loading: boolean
error: string | null
}): React.ReactElement {
return (
{error &&
{error}
}
)
}
function ConnectedState({ pubkey, profile, loading, disconnect }: { pubkey: string; profile: NostrProfile | null; loading: boolean; disconnect: () => Promise }): React.ReactElement {
return (
{
void disconnect()
}}
loading={loading}
/>
)
}
function UnlockState({ loading, error, onUnlock, onClose }: { loading: boolean; error: string | null; onUnlock: () => void; onClose: () => void }): React.ReactElement {
return (
<>
>
)
}
function noop(): void {
// Intentionally empty: UnlockState must render ConnectForm but "create account" is not available in this mode.
}
function DisconnectedState({
loading,
error,
showUnlockModal,
setShowUnlockModal,
onCreateAccount,
}: {
loading: boolean
error: string | null
showUnlockModal: boolean
setShowUnlockModal: (show: boolean) => void
onCreateAccount: () => void
}): React.ReactElement {
return (
<>
setShowUnlockModal(true)}
loading={loading}
error={error}
/>
{showUnlockModal && (
setShowUnlockModal(false)}
onClose={() => setShowUnlockModal(false)}
/>
)}
>
)
}
export function ConnectButton(): React.ReactElement {
const { connected, pubkey, profile, loading, error, connect, disconnect, accountExists, isUnlocked } = useNostrAuth()
const ui = useConnectButtonUiState()
useAutoConnect({
accountExists,
pubkey,
showRecoveryStep: ui.showRecoveryStep,
showUnlockModal: ui.showUnlockModal,
connect,
})
const mode = getConnectButtonMode({
connected,
pubkey,
isUnlocked,
accountExists,
showUnlockModal: ui.showUnlockModal,
})
if (mode === 'connected') {
return
}
if (mode === 'unlock_required') {
return
}
return (
<>
{ui.showRecoveryStep && (
)}
{ui.showUnlockModal && }
>
)
}
function requirePubkey(pubkey: string | null): string {
if (!pubkey) {
const error = new Error('Invariant violation: pubkey is required when ConnectButton mode is "connected"')
console.error(error.message, { pubkey })
throw error
}
return pubkey
}