import { useState, useEffect } from 'react'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { ConnectedUserMenu } from './ConnectedUserMenu'
import { CreateAccountModal } from './CreateAccountModal'
import { UnlockAccountModal } from './UnlockAccountModal'
import type { NostrProfile } from '@/types/nostr'
function ConnectForm({
onCreateAccount,
onUnlock,
loading,
error,
}: {
onCreateAccount: () => void
onUnlock: () => void
loading: boolean
error: string | null
}) {
return (
{error &&
{error}
}
)
}
function useAutoConnect(accountExists: boolean | null, pubkey: string | null, showCreateModal: boolean, showUnlockModal: boolean, connect: () => Promise) {
useEffect(() => {
if (accountExists === true && !pubkey && !showCreateModal && !showUnlockModal) {
void connect()
}
}, [accountExists, pubkey, showCreateModal, showUnlockModal, connect])
}
function ConnectedState({ pubkey, profile, loading, disconnect }: { pubkey: string; profile: NostrProfile | null; loading: boolean; disconnect: () => Promise }) {
return (
{
void disconnect()
}}
loading={loading}
/>
)
}
function UnlockState({ loading, error, onUnlock, onClose }: { loading: boolean; error: string | null; onUnlock: () => void; onClose: () => void }) {
return (
<>
{}}
onUnlock={onUnlock}
loading={loading}
error={error}
/>
>
)
}
function DisconnectedModals({
showCreateModal,
showUnlockModal,
setShowCreateModal,
setShowUnlockModal,
}: {
showCreateModal: boolean
showUnlockModal: boolean
setShowCreateModal: (show: boolean) => void
setShowUnlockModal: (show: boolean) => void
}) {
return (
<>
{showCreateModal && (
{
setShowCreateModal(false)
setShowUnlockModal(true)
}}
onClose={() => setShowCreateModal(false)}
/>
)}
{showUnlockModal && (
setShowUnlockModal(false)}
onClose={() => setShowUnlockModal(false)}
/>
)}
>
)
}
function DisconnectedState({
loading,
error,
showCreateModal,
showUnlockModal,
setShowCreateModal,
setShowUnlockModal,
}: {
loading: boolean
error: string | null
showCreateModal: boolean
showUnlockModal: boolean
setShowCreateModal: (show: boolean) => void
setShowUnlockModal: (show: boolean) => void
}) {
return (
<>
setShowCreateModal(true)}
onUnlock={() => setShowUnlockModal(true)}
loading={loading}
error={error}
/>
>
)
}
export function ConnectButton() {
const { connected, pubkey, profile, loading, error, connect, disconnect, accountExists, isUnlocked } = useNostrAuth()
const [showCreateModal, setShowCreateModal] = useState(false)
const [showUnlockModal, setShowUnlockModal] = useState(false)
useAutoConnect(accountExists, pubkey, showCreateModal, showUnlockModal, connect)
if (connected && pubkey && isUnlocked) {
return
}
if (accountExists === true && pubkey && !isUnlocked && !showUnlockModal && !showCreateModal) {
return (
setShowUnlockModal(true)}
onClose={() => setShowUnlockModal(false)}
/>
)
}
return (
)
}