// Data explorer modal - raw metrics + routes + CSV export
const DataExplorer = {
    overlay: null,
    modal: null,
    body: null,
    data: null,
    currentTab: 'airport',
    page: 0,
    perPage: 10,

    init() {
        // build modal DOM once
        this.overlay = document.createElement('div');
        this.overlay.className = 'de-overlay';
        this.overlay.addEventListener('click', (e) => {
            if (e.target === this.overlay) this.close();
        });

        this.modal = document.createElement('div');
        this.modal.className = 'de-modal';
        this.modal.innerHTML = `
            <div class="de-header">
                <h2 class="de-title"></h2>
                <button class="de-close">&times;</button>
            </div>
            <div class="de-tabs">
                <button class="de-tab active" data-tab="airport">Airport</button>
                <button class="de-tab" data-tab="routes">Routes</button>
            </div>
            <div class="de-body"></div>
            <div class="de-footer">
                <div class="de-pagination"></div>
                <button class="de-export">Export CSV</button>
            </div>
        `;

        this.overlay.appendChild(this.modal);
        document.body.appendChild(this.overlay);

        this.body = this.modal.querySelector('.de-body');

        // close btn
        this.modal.querySelector('.de-close').addEventListener('click', () => this.close());

        // tabs
        this.modal.querySelectorAll('.de-tab').forEach(btn => {
            btn.addEventListener('click', () => this.showTab(btn.dataset.tab));
        });

        // export
        this.modal.querySelector('.de-export').addEventListener('click', () => this.exportCSV());

        // esc to close
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.overlay.classList.contains('visible')) {
                this.close();
            }
        });
    },

    async open(iata) {
        this.overlay.classList.add('visible');
        this.modal.querySelector('.de-title').textContent = iata + ' Data';
        this.body.innerHTML = '<p class="de-loading">Loading...</p>';
        this.page = 0;

        try {
            this.data = await API.getDiagnostics(iata);
            this.showTab('airport');
        } catch (err) {
            this.body.innerHTML = '<p class="de-loading">Failed to load data</p>';
            console.error('DataExplorer:', err);
        }
    },

    close() {
        this.overlay.classList.remove('visible');
        this.data = null;
    },

    showTab(name) {
        this.currentTab = name;
        this.page = 0;

        // update active tab button
        this.modal.querySelectorAll('.de-tab').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === name);
        });

        if (name === 'airport') {
            this._renderAirport();
            this.modal.querySelector('.de-pagination').innerHTML = '';
        } else {
            this._renderRoutes();
        }
    },

    _renderAirport() {
        const a = this.data.airport;
        const pct = (v) => (v * 100).toFixed(1) + '%';

        this.body.innerHTML = `
            <table class="de-table">
                <tr><th>IATA</th><td>${a.iata}</td></tr>
                <tr><th>Name</th><td>${a.name || ''}</td></tr>
                <tr><th>Location</th><td>${a.city || ''}, ${a.state || ''}</td></tr>
                <tr><th>Coordinates</th><td>${a.lat}, ${a.lon}</td></tr>
                <tr class="de-section"><td colspan="2">Flight Volume</td></tr>
                <tr><th>Total Flights</th><td>${a.total_flights.toLocaleString()}</td></tr>
                <tr><th>Departures</th><td>${a.total_departures.toLocaleString()}</td></tr>
                <tr><th>Arrivals</th><td>${a.total_arrivals.toLocaleString()}</td></tr>
                <tr class="de-section"><td colspan="2">Delay Metrics</td></tr>
                <tr><th>Avg Arrival Delay</th><td>${a.avg_arr_delay} min</td></tr>
                <tr><th>Avg Departure Delay</th><td>${a.avg_dep_delay} min</td></tr>
                <tr><th>% Delayed (&gt;15 min)</th><td>${pct(a.pct_delayed)}</td></tr>
                <tr><th>Delay Score</th><td>${a.delay_score}</td></tr>
                <tr class="de-section"><td colspan="2">Delay Causes (%)</td></tr>
                <tr><th>Carrier</th><td>${a.carrier_pct}%</td></tr>
                <tr><th>Weather</th><td>${a.weather_pct}%</td></tr>
                <tr><th>NAS</th><td>${a.nas_pct}%</td></tr>
                <tr><th>Late Aircraft</th><td>${a.late_aircraft_pct}%</td></tr>
                <tr class="de-section"><td colspan="2">Data Sources</td></tr>
                ${a.data_sources.map(s => `<tr><td colspan="2">${s}</td></tr>`).join('')}
            </table>
        `;
    },

    _renderRoutes() {
        const routes = this.data.routes;
        const total = routes.length;
        const start = this.page * this.perPage;
        const end = Math.min(start + this.perPage, total);
        const slice = routes.slice(start, end);

        let html = `<table class="de-table de-routes-table">
            <thead>
                <tr>
                    <th>Origin</th><th>Dest</th><th>Flights</th>
                    <th>Avg Delay</th><th>Median</th><th>Std Dev</th>
                    <th>% Delayed</th><th>Distance</th><th>Risk</th>
                </tr>
            </thead><tbody>`;

        slice.forEach(r => {
            html += `<tr>
                <td>${r.origin}</td>
                <td>${r.dest}</td>
                <td>${r.flight_count.toLocaleString()}</td>
                <td>${r.avg_delay} min</td>
                <td>${r.median_delay} min</td>
                <td>${r.std_delay}</td>
                <td>${(r.pct_delayed * 100).toFixed(1)}%</td>
                <td>${r.avg_distance} mi</td>
                <td><span class="route-risk risk-${r.delay_risk}">${r.delay_risk}</span></td>
            </tr>`;
        });

        html += '</tbody></table>';
        this.body.innerHTML = html;

        // pagination controls
        const totalPages = Math.ceil(total / this.perPage);
        const pag = this.modal.querySelector('.de-pagination');
        if (totalPages <= 1) {
            pag.innerHTML = '';
            return;
        }
        pag.innerHTML = `
            <button class="de-page-btn" ${this.page === 0 ? 'disabled' : ''} onclick="DataExplorer.prevPage()">Prev</button>
            <span>${this.page + 1} / ${totalPages}</span>
            <button class="de-page-btn" ${this.page >= totalPages - 1 ? 'disabled' : ''} onclick="DataExplorer.nextPage()">Next</button>
        `;
    },

    prevPage() {
        if (this.page > 0) {
            this.page--;
            this._renderRoutes();
        }
    },

    nextPage() {
        const totalPages = Math.ceil(this.data.routes.length / this.perPage);
        if (this.page < totalPages - 1) {
            this.page++;
            this._renderRoutes();
        }
    },

    exportCSV() {
        if (!this.data) return;

        let csv = '';
        if (this.currentTab === 'airport') {
            const a = this.data.airport;
            csv = 'metric,value\n';
            csv += `IATA,${a.iata}\n`;
            csv += `Name,"${a.name}"\n`;
            csv += `City,"${a.city}"\n`;
            csv += `State,${a.state}\n`;
            csv += `Total Flights,${a.total_flights}\n`;
            csv += `Departures,${a.total_departures}\n`;
            csv += `Arrivals,${a.total_arrivals}\n`;
            csv += `Avg Arrival Delay,${a.avg_arr_delay}\n`;
            csv += `Avg Departure Delay,${a.avg_dep_delay}\n`;
            csv += `Pct Delayed,${a.pct_delayed}\n`;
            csv += `Delay Score,${a.delay_score}\n`;
            csv += `Carrier Delay %,${a.carrier_pct}\n`;
            csv += `Weather Delay %,${a.weather_pct}\n`;
            csv += `NAS Delay %,${a.nas_pct}\n`;
            csv += `Late Aircraft %,${a.late_aircraft_pct}\n`;
        } else {
            csv = 'origin,dest,flights,avg_delay,median_delay,std_delay,pct_delayed,distance,risk\n';
            this.data.routes.forEach(r => {
                csv += `${r.origin},${r.dest},${r.flight_count},${r.avg_delay},${r.median_delay},${r.std_delay},${r.pct_delayed},${r.avg_distance},${r.delay_risk}\n`;
            });
        }

        const blob = new Blob([csv], { type: 'text/csv' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${this.data.airport.iata}_${this.currentTab}.csv`;
        link.click();
        URL.revokeObjectURL(url);
    },
};
