// Main application entry point
import { CONFIG } 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 { MkDocsSearch } from './mkdocs-search.js';

// Application state
let refreshInterval = null;
let mkdocsSearch = 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 {
        // 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 MkDocs search
        await initializeMkDocsSearch();
        
    } 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 MkDocs search
async function initializeMkDocsSearch() {
    try {
        // Get config from server
        const configResponse = await fetch('/api/config');
        const config = await configResponse.json();
        
        mkdocsSearch = new MkDocsSearch({
            mkdocsUrl: config.mkdocsUrl || 'http://localhost:4002',
            minSearchLength: 2
        });
        
        const initialized = await mkdocsSearch.initialize();
        
        if (initialized) {
            // Bind to search input
            const searchInput = document.getElementById('docs-search-input');
            const searchResults = document.getElementById('docs-search-results');
            
            if (searchInput && searchResults) {
                mkdocsSearch.bindToInput(searchInput, searchResults);
                console.log('Documentation search ready');
            }
        } else {
            console.warn('Documentation search could not be initialized');
        }
    } catch (error) {
        console.error('Error setting up documentation search:', error);
    }
}
