class Controls {
    constructor(viz, layerManager) {
        this.viz = viz;
        this.layerManager = layerManager;
        this.panel = document.getElementById('controls-panel');
        this._render();
    }

    _render() {
        this.panel.innerHTML = `
            <div id="layer-toggle" class="control-group">
                <h3>Analysis Layers</h3>
                <div class="layer-row">
                    <div>
                        <div class="layer-row-label">Propagation Chain</div>
                        <div class="layer-row-sub">Best time to book by route</div>
                    </div>
                    <label class="layer-switch">
                        <input type="checkbox" id="layer-chain-toggle">
                        <span class="layer-switch-track"></span>
                    </label>
                </div>
                <div class="layer-row">
                    <div>
                        <div class="layer-row-label">Carrier Reliability</div>
                        <div class="layer-row-sub">Compare airlines on your route</div>
                    </div>
                    <label class="layer-switch">
                        <input type="checkbox" id="layer-carrier-toggle">
                        <span class="layer-switch-track"></span>
                    </label>
                </div>
                <div class="layer-row">
                    <div>
                        <div class="layer-row-label">Delay Predictor</div>
                        <div class="layer-row-sub">ML-powered delay prediction</div>
                    </div>
                    <label class="layer-switch">
                        <input type="checkbox" id="layer-predict-toggle">
                        <span class="layer-switch-track"></span>
                    </label>
                </div>
            </div>

            <div id="layer-legend" class="control-group" style="display:none"></div>

            <h2>Filters</h2>

            <div class="control-group">
                <label>Min Route Flights: <strong id="route-val">500</strong></label>
                <input type="range" id="min-flights" min="100" max="5000" step="100" value="500">
            </div>

            <div class="control-group">
                <label>Min Airport Flights: <strong id="airport-val">10,000</strong></label>
                <input type="range" id="min-airport-flights" min="1000" max="200000" step="1000" value="10000">
            </div>

            <div class="control-group">
                <label>Delay Severity:</label>
                <label><input type="checkbox" name="risk" value="low" checked> Low</label>
                <label><input type="checkbox" name="risk" value="medium" checked> Medium</label>
                <label><input type="checkbox" name="risk" value="high" checked> High</label>
                <label><input type="checkbox" name="risk" value="severe" checked> Severe</label>
            </div>

            <button id="apply-filters">Apply Filters</button>

            <div id="default-legend" class="control-group">
                <h3>Legend</h3>
                <div><span class="legend-dot" style="background:var(--risk-low)"></span> Low (&lt;15% delayed)</div>
                <div><span class="legend-dot" style="background:var(--risk-medium)"></span> Medium (15-25%)</div>
                <div><span class="legend-dot" style="background:var(--risk-high)"></span> High (25-40%)</div>
                <div><span class="legend-dot" style="background:var(--risk-severe)"></span> Severe (&gt;40%)</div>
            </div>
        `;

        this.panel.querySelector('#min-flights').addEventListener('input', (e) => {
            this.panel.querySelector('#route-val').textContent = Number(e.target.value).toLocaleString();
        });
        this.panel.querySelector('#min-airport-flights').addEventListener('input', (e) => {
            this.panel.querySelector('#airport-val').textContent = Number(e.target.value).toLocaleString();
        });
        this.panel.querySelector('#apply-filters').addEventListener('click', () => this._applyFilters());

        this.panel.querySelector('#layer-chain-toggle').addEventListener('change', (e) => {
            if (e.target.checked) {
                const ct = this.panel.querySelector('#layer-carrier-toggle');
                if (ct) ct.checked = false;
                const pt = this.panel.querySelector('#layer-predict-toggle');
                if (pt) pt.checked = false;
                this._switchLayer('chain');
            } else {
                this._switchLayer('default');
            }
        });

        this.panel.querySelector('#layer-carrier-toggle').addEventListener('change', (e) => {
            if (e.target.checked) {
                const ct = this.panel.querySelector('#layer-chain-toggle');
                if (ct) ct.checked = false;
                const pt = this.panel.querySelector('#layer-predict-toggle');
                if (pt) pt.checked = false;
                this._switchLayer('carrier');
            } else {
                this._switchLayer('default');
            }
        });

        this.panel.querySelector('#layer-predict-toggle').addEventListener('change', (e) => {
            if (e.target.checked) {
                const ct = this.panel.querySelector('#layer-chain-toggle');
                if (ct) ct.checked = false;
                const cr = this.panel.querySelector('#layer-carrier-toggle');
                if (cr) cr.checked = false;
                this._switchLayer('predict');
            } else {
                this._switchLayer('default');
            }
        });

    }

    _switchLayer(name) {
        if (!this.layerManager) return;

        this.layerManager.activate(name);
        this._updateLayerLegend();
    }

    _updateLayerLegend() {
        const defaultLeg = this.panel.querySelector('#default-legend');
        const layerLeg = this.panel.querySelector('#layer-legend');
        
        const active = this.layerManager ? this.layerManager.getActive() : null;

        if (active) {
            defaultLeg.style.display = 'none';
            layerLeg.style.display = '';
            layerLeg.innerHTML = active.getLegendHTML();
            if (active.setupLegendInteraction) active.setupLegendInteraction();
        } else {
            defaultLeg.style.display = '';
            layerLeg.style.display = 'none';
            layerLeg.innerHTML = '';
        }
    }

    _applyFilters() {
        const minFlights = this.panel.querySelector('#min-flights').value;
        const minAirportFlights = this.panel.querySelector('#min-airport-flights').value;
        const riskChecks = this.panel.querySelectorAll('input[name="risk"]:checked');
        const riskValues = Array.from(riskChecks).map(c => c.value).join(',');

        this.viz.loadData({
            min_flights: minFlights,
            min_airport_flights: minAirportFlights,
            delay_risk: riskValues || undefined,
        });
    }

    getDefaults() {
        return {
            min_flights: 500,
            min_airport_flights: 10000,
        };
    }
}
