// entry point
(async function () {
    InfoPanel.init();
    DataExplorer.init();

    const viz = new NetworkViz('viz-container');

    // Set up layer system
    const layerManager = new LayerManager(viz);
    layerManager.register('chain', new PropagationLayer(viz));
    layerManager.register('carrier', new CarrierLayer(viz));
    layerManager.register('predict', new PredictLayer(viz));
    const controls = new Controls(viz, layerManager);

    // Load summary stats for header
    try {
        const stats = await API.getStats();
        const el = document.getElementById('summary-stats');
        el.innerHTML = `
            <span>${(stats.total_airports || 0).toLocaleString()} airports</span>
            <span>${(stats.total_routes || 0).toLocaleString()} routes</span>
            <span>${(stats.total_flights || 0).toLocaleString()} flights</span>
            <span>Avg delay: ${stats.avg_delay_minutes || 0} min</span>
        `;
    } catch (e) {
        console.error('Failed to load stats:', e);
        document.getElementById('summary-stats').textContent = '';
    }

    // Load initial network data
    await viz.loadData(controls.getDefaults());

    // Click on background to deselect — or detect edge clicks
    document.getElementById('node-svg').addEventListener('click', (e) => {
        if (e.target.tagName !== 'circle') {
            // Check if active layer handles edge clicks
            if (viz.activeLayer && viz.activeLayer.edgeClickEnabled) {
                const edge = viz._findNearestEdge(e.clientX, e.clientY);
                if (edge) {
                    viz.activeLayer.onEdgeClick(edge);
                    return;
                }
            }
            // Let active layer suppress background clear (e.g. chain layer mid-flow)
            if (viz.activeLayer && viz.activeLayer.onBackgroundClick()) {
                return;
            }
            viz.clearSelection();
            InfoPanel.clear();
        }
    });

    // Debounced resize
    let resizeTimer;
    window.addEventListener('resize', () => {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(() => viz.resize(), 250);
    });
})();
