import { useState } from 'react' import { nostrAuthService } from '@/lib/nostrAuth' import { RecoveryStep, ImportStep, ChooseStep } from './CreateAccountModalSteps' interface CreateAccountModalProps { onSuccess: (npub: string) => void onClose: () => void } type Step = 'choose' | 'import' | 'recovery' async function createAccountWithKey(key?: string) { return await nostrAuthService.createAccount(key) } async function handleAccountCreation( key: string | undefined, setLoading: (loading: boolean) => void, setError: (error: string | null) => void, setRecoveryPhrase: (phrase: string[]) => void, setNpub: (npub: string) => void, setStep: (step: Step) => void, errorMessage: string ) { if (key !== undefined && !key.trim()) { setError('Please enter a private key') return } setLoading(true) setError(null) try { const result = await createAccountWithKey(key?.trim()) setRecoveryPhrase(result.recoveryPhrase) setNpub(result.npub) setStep('recovery') } catch (e) { setError(e instanceof Error ? e.message : errorMessage) } finally { setLoading(false) } } function useAccountCreation() { const [step, setStep] = useState('choose') const [importKey, setImportKey] = useState('') const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const [recoveryPhrase, setRecoveryPhrase] = useState([]) const [npub, setNpub] = useState('') const handleGenerate = async () => { await handleAccountCreation(undefined, setLoading, setError, setRecoveryPhrase, setNpub, setStep, 'Failed to create account') } const handleImport = async () => { await handleAccountCreation(importKey, setLoading, setError, setRecoveryPhrase, setNpub, setStep, 'Failed to import key') } return { step, setStep, importKey, setImportKey, loading, error, setError, recoveryPhrase, npub, handleGenerate, handleImport, } } function handleImportBack(setStep: (step: Step) => void, setError: (error: string | null) => void, setImportKey: (key: string) => void) { setStep('choose') setError(null) setImportKey('') } function renderStep( step: Step, recoveryPhrase: string[], npub: string, importKey: string, setImportKey: (key: string) => void, loading: boolean, error: string | null, handleContinue: () => void, handleImport: () => void, setStep: (step: Step) => void, setError: (error: string | null) => void, handleGenerate: () => void, onClose: () => void ) { if (step === 'recovery') { return } if (step === 'import') { return ( handleImportBack(setStep, setError, setImportKey)} /> ) } return ( setStep('import')} onClose={onClose} /> ) } export function CreateAccountModal({ onSuccess, onClose }: CreateAccountModalProps) { const { step, setStep, importKey, setImportKey, loading, error, setError, recoveryPhrase, npub, handleGenerate, handleImport, } = useAccountCreation() const handleContinue = () => { onSuccess(npub) onClose() } return renderStep( step, recoveryPhrase, npub, importKey, setImportKey, loading, error, handleContinue, handleImport, setStep, setError, handleGenerate, onClose ) }