/**
 * Main Admin Panel Coordinator
 * This refactored admin.js coordinates all admin modules while maintaining functionality
 * Modules: core, auth, map, walksheet, shifts, shift-volunteers, users, email, integration
 */

/**
 * Main Event Listener Setup
 * Coordinates event listeners across all modules
 */
function setupAllEventListeners() {
    // Setup authentication listeners
    if (window.adminAuth && typeof window.adminAuth.setupAuthEventListeners === 'function') {
        window.adminAuth.setupAuthEventListeners();
    }
    
    // Setup map listeners  
    if (window.adminMap && typeof window.adminMap.setupMapEventListeners === 'function') {
        window.adminMap.setupMapEventListeners();
    }
    
    // Setup walk sheet listeners
    if (window.adminWalkSheet && typeof window.adminWalkSheet.setupWalkSheetEventListeners === 'function') {
        window.adminWalkSheet.setupWalkSheetEventListeners();
    }
    
    // Setup shift listeners
    if (window.adminShifts && typeof window.adminShifts.setupShiftEventListeners === 'function') {
        window.adminShifts.setupShiftEventListeners();
    }
    
    // Setup shift volunteer listeners with retry mechanism
    const setupVolunteerModule = () => {
        if (window.adminShiftVolunteers && typeof window.adminShiftVolunteers.setupVolunteerModalEventListeners === 'function') {
            console.log('Setting up volunteer modal event listeners...');
            window.adminShiftVolunteers.setupVolunteerModalEventListeners();
            
            // Load users for volunteer management
            if (typeof window.adminShiftVolunteers.loadAllUsers === 'function') {
                console.log('Loading users for volunteer management...');
                window.adminShiftVolunteers.loadAllUsers();
            }
            return true;
        }
        return false;
    };
    
    // Try to setup immediately
    if (!setupVolunteerModule()) {
        console.log('adminShiftVolunteers not ready, waiting for ready event...');
        // Listen for the ready event
        window.addEventListener('adminShiftVolunteersReady', (e) => {
            console.log('adminShiftVolunteersReady event received:', e.detail);
            if (setupVolunteerModule()) {
                console.log('✅ Volunteer module setup completed after ready event');
            }
        });
        
        // Also add a backup timer
        let retryCount = 0;
        const maxRetries = 10;
        const retrySetup = setInterval(() => {
            retryCount++;
            if (setupVolunteerModule()) {
                clearInterval(retrySetup);
                console.log('✅ Volunteer module setup completed after', retryCount, 'retries');
            } else if (retryCount >= maxRetries) {
                clearInterval(retrySetup);
                console.warn('⚠️ Failed to setup volunteer module after', maxRetries, 'retries');
            }
        }, 200);
    }
    
    // Setup user listeners
    if (window.adminUsers && typeof window.adminUsers.setupUserEventListeners === 'function') {
        window.adminUsers.setupUserEventListeners();
    }
    
    // Setup email listeners
    if (window.adminEmail && typeof window.adminEmail.setupEmailEventListeners === 'function') {
        window.adminEmail.setupEmailEventListeners();
    }
}

// Main admin initialization when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, initializing admin modules...');
    
    // Initialize core functionality
    if (window.adminCore && typeof window.adminCore.initializeAdminCore === 'function') {
        window.adminCore.initializeAdminCore();
    }
    
    // Initialize authentication
    if (window.adminAuth && typeof window.adminAuth.checkAdminAuth === 'function') {
        window.adminAuth.checkAdminAuth();
    }
    
    // Initialize admin map
    if (window.adminMap && typeof window.adminMap.initializeAdminMap === 'function') {
        window.adminMap.initializeAdminMap();
    }
    
    // Load current start location
    if (window.adminMap && typeof window.adminMap.loadCurrentStartLocation === 'function') {
        window.adminMap.loadCurrentStartLocation();
    }
    
    // Check module loading status with detailed info
    console.log('📊 Module loading status:', {
        adminCore: !!window.adminCore,
        adminAuth: !!window.adminAuth,
        adminMap: !!window.adminMap,
        adminShifts: !!window.adminShifts,
        adminShiftVolunteers: !!window.adminShiftVolunteers,
        adminUsers: !!window.adminUsers,
        adminEmail: !!window.adminEmail
    });
    
    // Detailed check for adminShiftVolunteers
    if (window.adminShiftVolunteers) {
        console.log('📋 adminShiftVolunteers details:', {
            exists: true,
            functions: Object.keys(window.adminShiftVolunteers),
            showShiftUserModal: typeof window.adminShiftVolunteers.showShiftUserModal,
            moduleVersion: window.adminShiftVolunteers.moduleVersion,
            loadedAt: window.adminShiftVolunteers.loadedAt
        });
    } else {
        console.warn('⚠️ adminShiftVolunteers module not found');
    }
    
    // Setup all event listeners
    setupAllEventListeners();
    
    // Initialize integrations with a small delay to ensure DOM is ready
    setTimeout(() => {
        if (window.adminWalkSheet && typeof window.adminWalkSheet.loadWalkSheetConfig === 'function') {
            window.adminWalkSheet.loadWalkSheetConfig();
        }
        if (window.adminIntegration && typeof window.adminIntegration.initializeAllIntegrations === 'function') {
            window.adminIntegration.initializeAllIntegrations();
        }
    }, 100);
    
    // Check if URL has a hash to show specific section
    const hash = window.location.hash;
    if (hash === '#walk-sheet') {
        if (window.adminCore && typeof window.adminCore.showSection === 'function') {
            window.adminCore.showSection('walk-sheet');
        }
        if (window.adminWalkSheet && typeof window.adminWalkSheet.checkAndLoadWalkSheetConfig === 'function') {
            window.adminWalkSheet.checkAndLoadWalkSheetConfig();
        }
    } else if (hash === '#convert-data') {
        if (window.adminCore && typeof window.adminCore.showSection === 'function') {
            window.adminCore.showSection('convert-data');
        }
    } else if (hash === '#cuts') {
        if (window.adminCore && typeof window.adminCore.showSection === 'function') {
            window.adminCore.showSection('cuts');
        }
    } else {
        // Default to dashboard
        if (window.adminCore && typeof window.adminCore.showSection === 'function') {
            window.adminCore.showSection('dashboard');
        }
        // Dashboard loading is handled by admin-core.js showSection/loadSectionData
        // No need to manually load here to avoid duplicates
    }
});

/**
 * Legacy Dashboard Functions - DEPRECATED
 * These are kept for backward compatibility but should not be used
 * Use the dashboard.js module functions instead
 */
async function loadAdminDashboardData() {
    try {
        const response = await fetch('/api/admin/dashboard');
        const data = await response.json();
        
        if (data.success) {
            // This was the old function that only loaded user/shift stats
            // Now deprecated in favor of the full dashboard.js implementation
            document.getElementById('total-users').textContent = data.stats.totalUsers;
            document.getElementById('total-shifts').textContent = data.stats.totalShifts;
            document.getElementById('total-signups').textContent = data.stats.totalSignups;
            document.getElementById('this-month-users').textContent = data.stats.thisMonthUsers;
        }
    } catch (error) {
        console.error('Failed to load admin dashboard data:', error);
    }
}

/**
 * Legacy function redirects for backward compatibility
 * These ensure existing functionality continues to work
 */
window.loadAdminDashboardData = loadAdminDashboardData;

// Export dashboard function for module coordination
if (typeof window.adminDashboard === 'undefined') {
    window.adminDashboard = {
        loadAdminDashboardData: loadAdminDashboardData
    };
}
