const InfoPanel = {
    panel: null,

    init() {
        this.panel = document.getElementById('info-content');
    },

    async showAirport(iata) {
        this.panel.innerHTML = '<p class="info-placeholder">Loading...</p>';

        try {
            const [airport, routeData] = await Promise.all([
                API.getAirport(iata),
                API.getRoutes({ origin: iata, limit: 20, sort_by: 'flight_count' }),
            ]);

            if (!airport || !airport.iata) {
                this.panel.innerHTML = '<p class="info-placeholder">Airport not found</p>';
                return;
            }

            const routes = routeData.routes || routeData;
            const pctDisplay = airport.pct_delayed != null
                ? (airport.pct_delayed * 100).toFixed(1) + '%'
                : 'N/A';

            this.panel.innerHTML = `
                <h2>${airport.iata} - ${airport.name || ''}</h2>
                <p>${airport.city || ''}, ${airport.state || ''}</p>

                <div class="stat-grid">
                    <div class="stat">
                        <span class="stat-value">${(airport.total_flights || 0).toLocaleString()}</span>
                        <span class="stat-label">Total Flights</span>
                    </div>
                    <div class="stat">
                        <span class="stat-value">${airport.avg_arr_delay != null ? airport.avg_arr_delay.toFixed(1) + ' min' : 'N/A'}</span>
                        <span class="stat-label">Avg Arrival Delay</span>
                    </div>
                    <div class="stat">
                        <span class="stat-value">${airport.avg_dep_delay != null ? airport.avg_dep_delay.toFixed(1) + ' min' : 'N/A'}</span>
                        <span class="stat-label">Avg Departure Delay</span>
                    </div>
                    <div class="stat">
                        <span class="stat-value">${pctDisplay}</span>
                        <span class="stat-label">Flights Delayed</span>
                    </div>
                </div>

                <h3>Delay Causes</h3>
                <div id="delay-causes-chart"></div>

                <h3>Top Routes from ${airport.iata}</h3>
                <ul class="route-list">
                    ${(routes || []).map(r => `
                        <li>
                            <span class="route-dest">${r.dest}</span>
                            <span class="route-flights">${(r.flight_count || 0).toLocaleString()} flights</span>
                            <span class="route-risk risk-${r.delay_risk || 'low'}">${r.delay_risk || '?'}</span>
                        </li>
                    `).join('')}
                </ul>

                <div class="data-actions">
                    <button class="view-data-btn" onclick="DataExplorer.open('${airport.iata}')">View Data</button>
                </div>
            `;

            this._renderDelayCauses(airport);
        } catch (err) {
            this.panel.innerHTML = `<p class="info-placeholder">Error loading airport data</p>`;
            console.error('InfoPanel error:', err);
        }
    },

    _renderDelayCauses(airport) {
        const container = document.getElementById('delay-causes-chart');
        if (!container) return;

        const causes = [
            { label: 'Carrier', value: airport.carrier_pct || 0 },
            { label: 'Weather', value: airport.weather_pct || 0 },
            { label: 'NAS', value: airport.nas_pct || 0 },
            { label: 'Late Aircraft', value: airport.late_aircraft_pct || 0 },
        ];

        const maxVal = d3.max(causes, d => d.value) || 1;
        const barHeight = 22;
        const labelWidth = 90;
        const barMaxWidth = 160;

        const svg = d3.select(container).append('svg')
            .attr('width', labelWidth + barMaxWidth + 40)
            .attr('height', causes.length * (barHeight + 4));

        const y = d3.scaleBand()
            .domain(causes.map(d => d.label))
            .range([0, causes.length * (barHeight + 4)])
            .padding(0.15);

        const x = d3.scaleLinear()
            .domain([0, maxVal])
            .range([0, barMaxWidth]);

        const g = svg.selectAll('g').data(causes).enter().append('g')
            .attr('transform', d => `translate(0, ${y(d.label)})`);

        g.append('text')
            .attr('x', labelWidth - 5)
            .attr('y', y.bandwidth() / 2)
            .attr('text-anchor', 'end')
            .attr('dominant-baseline', 'middle')
            .attr('font-size', '11px')
            .text(d => d.label);

        g.append('rect')
            .attr('x', labelWidth)
            .attr('y', 0)
            .attr('width', d => x(d.value))
            .attr('height', y.bandwidth())
            .attr('fill', '#64748b')
            .attr('rx', 2);

        g.append('text')
            .attr('x', d => labelWidth + x(d.value) + 5)
            .attr('y', y.bandwidth() / 2)
            .attr('dominant-baseline', 'middle')
            .attr('font-size', '10px')
            .text(d => d.value.toFixed(1) + '%');
    },

    clear() {
        if (this.panel) {
            this.panel.innerHTML = '<p class="info-placeholder">Click an airport to see details</p>';
        }
    },
};
