// Main application entry point
import { CONFIG } from './config.js';
import { hideLoading, showStatus } from './utils.js';
import { checkAuth } from './auth.js';
import { initializeMap } from './map-manager.js';
import { loadLocations } from './location-manager.js';
import { setupEventListeners } from './ui-controls.js';

// Application state
let refreshInterval = null;

// Initialize the application
document.addEventListener('DOMContentLoaded', async () => {
    console.log('DOM loaded, initializing application...');
    
    try {
        // First check authentication
        await checkAuth();
        
        // Then initialize the map
        await initializeMap();
        
        // Only load locations after map is ready
        await loadLocations();
        
        // Setup other features
        setupEventListeners();
        setupAutoRefresh();
        
    } catch (error) {
        console.error('Initialization error:', error);
        showStatus('Failed to initialize application', 'error');
    } finally {
        hideLoading();
    }
});

function setupAutoRefresh() {
    refreshInterval = setInterval(() => {
        loadLocations();
    }, CONFIG.REFRESH_INTERVAL);
}

// Clean up on page unload
window.addEventListener('beforeunload', () => {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});
