// Block Explorer Service v1.3.1
class BlockExplorer {
    constructor() {
        this.lastBlock = null;
        this.subscribers = new Map();
    }

    async getLatestBlock() {
        try {
            const response = await fetch('https://api.binance.org/api/v1/blocks/latest');
            const data = await response.json();
            this.lastBlock = {
                number: data.height,
                hash: data.hash,
                timestamp: data.time,
                transactions: data.num_txs
            };
            return this.lastBlock;
        } catch (error) {
            console.error('Latest block fetch failed:', error);
            return null;
        }
    }

    async getBlockByNumber(number) {
        try {
            const response = await fetch(`https://api.binance.org/api/v1/blocks/${number}`);
            return await response.json();
        } catch (error) {
            console.error('Block fetch failed:', error);
            return null;
        }
    }

    subscribeToNewBlocks(callback) {
        const id = Date.now().toString();
        this.subscribers.set(id, callback);
        return id;
    }

    unsubscribe(id) {
        return this.subscribers.delete(id);
    }

    async _notifySubscribers(block) {
        this.subscribers.forEach(callback => {
            try {
                callback(block);
            } catch (error) {
                console.error('Subscriber notification failed:', error);
            }
        });
    }
}

export const blockExplorer = new BlockExplorer();