import { nostrAuthService } from '@/lib/nostrAuth' export interface UseUnlockAccountControllerResult { handleWordChange: (index: number, value: string) => void handlePaste: () => void handleUnlock: () => void } export function useUnlockAccountController(params: { words: string[] setWords: (words: string[]) => void setLoading: (loading: boolean) => void setError: (error: string | null) => void onSuccess: () => void onClose: () => void }): UseUnlockAccountControllerResult { const handleWordChange = (index: number, value: string): void => { const nextWords = buildNextWords({ current: params.words, index, value }) params.setWords(nextWords) params.setError(null) } const handlePaste = (): void => { void pasteWordsFromClipboard({ setWords: params.setWords, setError: params.setError }) } const handleUnlock = (): void => { void unlockAccount({ words: params.words, setLoading: params.setLoading, setError: params.setError, onSuccess: params.onSuccess, onClose: params.onClose, }) } return { handleWordChange, handlePaste, handleUnlock } } function buildNextWords(params: { current: string[]; index: number; value: string }): string[] { const next = [...params.current] next[params.index] = normalizeWord(params.value) return next } function normalizeWord(value: string): string { return value.trim().toLowerCase() } async function pasteWordsFromClipboard(params: { setWords: (words: string[]) => void setError: (error: string | null) => void }): Promise { try { const text = await navigator.clipboard.readText() const words = text.trim().split(/\s+/).slice(0, 4).map(normalizeWord) if (words.length !== 4) { params.setError('Le presse-papiers ne contient pas 4 mots.') return } params.setWords(words) params.setError(null) } catch (e) { console.error('[UnlockAccountModal] Error reading clipboard:', e) params.setError('Impossible de lire le presse-papiers.') } } async function unlockAccount(params: { words: string[] setLoading: (loading: boolean) => void setError: (error: string | null) => void onSuccess: () => void onClose: () => void }): Promise { if (params.words.some((word) => !word)) { params.setError('Veuillez remplir tous les mots-clés') return } params.setLoading(true) params.setError(null) try { await nostrAuthService.unlockAccount(params.words) params.onSuccess() params.onClose() } catch (e) { console.error('[UnlockAccountModal] Error unlocking account:', e) params.setError(e instanceof Error ? e.message : 'Échec du déverrouillage. Vérifiez vos mots-clés.') } finally { params.setLoading(false) } }