// Main application entry point
import { CONFIG, loadDomainConfig } from './config.js';
import { hideLoading, showStatus, setViewportDimensions } 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';
import { UnifiedSearchManager } from './search-manager.js';

// Application state
let refreshInterval = null;
let unifiedSearchManager = null;

// Initialize the application
document.addEventListener('DOMContentLoaded', async () => {
    // Set initial viewport dimensions and listen for resize events
    setViewportDimensions();
    window.addEventListener('resize', setViewportDimensions);
    window.addEventListener('orientationchange', () => {
        // Add a small delay for orientation change to complete
        setTimeout(setViewportDimensions, 100);
    });
    
    console.log('DOM loaded, initializing application...');
    
    try {
        // Load domain configuration first
        await loadDomainConfig();
        
        // 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();
        
        // Initialize Unified Search
        await initializeUnifiedSearch();
        
    } 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);
    }
});

// Initialize Unified Search
async function initializeUnifiedSearch() {
    try {
        // Get config from server
        const configResponse = await fetch('/api/config');
        const config = await configResponse.json();
        
        unifiedSearchManager = new UnifiedSearchManager({
            mkdocsUrl: config.mkdocsUrl || 'http://localhost:4002',
            minSearchLength: 2
        });
        
        const initialized = await unifiedSearchManager.initialize();
        
        if (initialized) {
            // Bind to search container
            const searchContainer = document.querySelector('.unified-search-container');
            
            if (searchContainer) {
                const bound = unifiedSearchManager.bindToElements(searchContainer);
                if (bound) {
                    console.log('Unified search ready');
                } else {
                    console.warn('Failed to bind unified search to elements');
                }
            } else {
                console.warn('Unified search container not found');
            }
        } else {
            console.warn('Unified search could not be initialized');
        }
    } catch (error) {
        console.error('Error setting up unified search:', error);
    }
}
