import { useState, useEffect, useCallback } from 'react'; import { CashuMint, CashuWalletError } from './types'; export interface UseCashuMintsReturn { mints: CashuMint[]; isLoading: boolean; error: CashuWalletError | null; refreshMints: () => Promise; getMints: () => Promise; addMint: (mintUrl: string) => Promise; removeMint: (mintUrl: string) => Promise; getCleanMintLabel: (mint: { name?: string; url: string }) => string; } export function useCashuMints(manager: unknown | null): UseCashuMintsReturn { const [mints, setMints] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const refreshMints = useCallback(async () => { if (!manager) return; try { const mintList = await (manager as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); const formattedMints = mintList .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ url: mint.mintUrl, // Map mintUrl to url for consistency name: mint.name, info: mint.mintInfo })); // If no mints exist, add the default mint if (formattedMints.length === 0) { console.log('🔧 No mints found, adding default mint: mint.chorus.community'); try { await (manager as { mint: { addMint: (mintUrl: string) => Promise } }).mint.addMint('https://mint.chorus.community'); // The mint:added event will trigger refreshMints again, so we don't need to set mints here return; } catch (err) { console.warn('⚠️ Failed to add default mint:', err); // Continue with empty mints if default mint fails } } setMints(formattedMints); } catch (err) { console.error('Failed to refresh mints:', err); const errorMessage = err instanceof Error ? err.message : 'Failed to refresh mints'; setError(new CashuWalletError(errorMessage, 'MINT_REFRESH_ERROR', { originalError: err })); } }, [manager]); const getMints = useCallback(async (): Promise => { if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); try { setIsLoading(true); setError(null); const mintList = await (manager as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); return mintList .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ url: mint.mintUrl, // Map mintUrl to url for consistency name: mint.name, info: mint.mintInfo })); } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to get mints'; const cashuError = new CashuWalletError(errorMessage, 'GET_MINTS_ERROR', { originalError: err }); setError(cashuError); throw cashuError; } finally { setIsLoading(false); } }, [manager]); const addMint = useCallback(async (mintUrl: string) => { if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); try { setIsLoading(true); setError(null); await (manager as { mint: { addMint: (mintUrl: string) => Promise } }).mint.addMint(mintUrl); // No need to manually refresh - events will handle it automatically } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to add mint'; const cashuError = new CashuWalletError(errorMessage, 'ADD_MINT_ERROR', { mintUrl, originalError: err }); setError(cashuError); throw cashuError; } finally { setIsLoading(false); } }, [manager]); const removeMint = useCallback(async (mintUrl: string) => { if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); try { setIsLoading(true); setError(null); // Access the mintService directly through the manager to use deleteMint // The manager has a private mintService property that we can access const mintService = (manager as any).mintService; if (!mintService || typeof mintService.deleteMint !== 'function') { throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR'); } await mintService.deleteMint(mintUrl); // No need to manually refresh - events will handle it automatically console.log('✅ Mint removed successfully:', mintUrl); } catch (err) { const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint'; const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err }); setError(cashuError); throw cashuError; } finally { setIsLoading(false); } }, [manager]); // Set up event listeners for automatic mint updates using coco events useEffect(() => { if (!manager) return; const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('mint:added', () => { console.log('➕ Mint added, refreshing mints...'); refreshMints(); }); const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('mint:updated', () => { console.log('🔄 Mint updated, refreshing mints...'); refreshMints(); }); return () => { unsubscribeMintAdded(); unsubscribeMintUpdated(); }; }, [manager, refreshMints]); // Initial mints load useEffect(() => { if (manager && mints.length === 0) { refreshMints(); } }, [manager, mints.length, refreshMints]); const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => { if (mint.name && mint.name.trim().length > 0) { // If name looks like a URL, strip protocol as well return mint.name.replace(/^https?:\/\//, ''); } try { return new URL(mint.url).host; // host excludes protocol and preserves port if any } catch { // Fallback: manual strip return mint.url.replace(/^https?:\/\//, ''); } }, []); return { mints, isLoading, error, refreshMints, getMints, addMint, removeMint, getCleanMintLabel, }; }