// Gestion du localStorage pour la page de diagnostic
function initLocalStorageDiagnostic() {
    const localStorageInfo = document.getElementById('local-storage-info');
    const clearLocalStorageBtn = document.getElementById('clear-localstorage');
    
    function updateLocalStorageInfo() {
        let html = '<ul class="list-unstyled mb-0">';
        
        // Vérifier les favoris
        try {
            const favoritesData = localStorage.getItem('favmastokey_favorites');
            if (favoritesData) {
                const favorites = JSON.parse(favoritesData);
                html += '<li><strong>Favoris stockés:</strong> ' + (Array.isArray(favorites) ? favorites.length : '?') + ' URLs</li>';
            } else {
                html += '<li><strong>Favoris stockés:</strong> <span class="text-muted">Aucun</span></li>';
            }
        } catch (e) {
            html += '<li><strong>Favoris stockés:</strong> <span class="text-danger">Erreur</span></li>';
        }
        
        // Vérifier la migration
        try {
            const migrationData = localStorage.getItem('favmastokey_migration');
            if (migrationData) {
                const migration = JSON.parse(migrationData);
                html += '<li><strong>État de la migration:</strong> ' + (migration.status || 'Non défini') + '</li>';
                
                if (migration.progress) {
                    html += '<li><strong>Progression:</strong> ' + 
                        migration.progress.current + '/' + 
                        migration.progress.total + ' (' + 
                        (migration.progress.percentage || 0).toFixed(1) + '%)</li>';
                }
                
                if (migration.lastUpdateTime) {
                    const date = new Date(migration.lastUpdateTime);
                    html += '<li><strong>Dernière mise à jour:</strong> ' + date.toLocaleString() + '</li>';
                }
            } else {
                html += '<li><strong>État de la migration:</strong> <span class="text-muted">Aucune migration en cours</span></li>';
            }
        } catch (e) {
            html += '<li><strong>État de la migration:</strong> <span class="text-danger">Erreur</span></li>';
        }
        
        // Autres données
        const additionalKeys = [
            {key: 'favmastokey_federated_cache', label: 'Cache fédéré'},
            {key: 'favmastokey_ratelimit_queue', label: 'File d\'attente rate-limit'}, 
            {key: 'favmastokey_api_performance', label: 'Statistiques API'}, 
            {key: 'favmastokey_multitoken_migration', label: 'Migration mode filou'}
        ];
        
        for (const item of additionalKeys) {
            try {
                const dataStr = localStorage.getItem(item.key);
                if (dataStr) {
                    const data = JSON.parse(dataStr);
                    const size = typeof data === 'object' ? 
                        (Array.isArray(data) ? data.length : Object.keys(data).length) : 1;
                    html += `<li><strong>${item.label}:</strong> ${size} entrées</li>`;
                }
            } catch (e) {
                // Ignorer les erreurs
            }
        }
        
        html += '</ul>';
        localStorageInfo.innerHTML = html;
    }
    
    // Mettre à jour au chargement
    updateLocalStorageInfo();
    
    // Gérer le bouton d'effacement
    if (clearLocalStorageBtn) {
        clearLocalStorageBtn.addEventListener('click', function() {
            if (confirm('Êtes-vous sûr de vouloir effacer toutes les données de migration stockées localement ?')) {
                // Liste des clés connues
                const keysToRemove = [
                    'favmastokey_favorites',
                    'favmastokey_migration',
                    'favmastokey_federated_cache',
                    'favmastokey_ratelimit_queue',
                    'favmastokey_api_performance',
                    'favmastokey_multitoken_migration'
                ];
                
                // Supprimer toutes les clés connues
                keysToRemove.forEach(key => localStorage.removeItem(key));
                
                // Rechercher d'autres clés potentielles
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key && key.startsWith('favmastokey_')) {
                        localStorage.removeItem(key);
                    }
                }
                
                updateLocalStorageInfo();
                alert('Données localStorage effacées avec succès.');
            }
        });
    }
}

// Exécuter après chargement du DOM
document.addEventListener('DOMContentLoaded', initLocalStorageDiagnostic);