(function () {
    const pageData = window.rvaPageData;
    if (!pageData) {
        return;
    }

    const apiBase = '/api/rva';
    const stationsByNumber = new Map((pageData.stations || []).map(station => [station.number, station]));

    const resultState = {
        mode: 'common',
        rows: []
    };

    function showAlert(message, type = 'danger') {
        const container = document.getElementById('rva-alert');
        if (!message) {
            container.innerHTML = '';
            return;
        }
        container.innerHTML = `<div class="alert alert-${type} mb-3" role="alert">${message}</div>`;
    }

    function formatDateTime(value) {
        return value ? PcpUtcTime.formatDateTime(value) : '';
    }

    function formatNumber(value, digits = 3) {
        const number = Number(value);
        if (!Number.isFinite(number)) {
            return '';
        }
        return number.toLocaleString('ru-RU', {
            minimumFractionDigits: 0,
            maximumFractionDigits: digits
        });
    }

    function selectedMode() {
        return document.querySelector('input[name="rva-mode"]:checked')?.value || 'common';
    }

    function selectedStations() {
        return Array.from(document.querySelectorAll('.rva-station-checkbox:checked'))
            .map(input => Number(input.dataset.number))
            .map(number => stationsByNumber.get(number))
            .filter(Boolean);
    }

    async function requestJson(url, payload) {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });

        const isJson = response.headers.get('content-type')?.includes('application/json');
        const body = isJson ? await response.json() : await response.text();

        if (!response.ok) {
            if (body && typeof body === 'object') {
                throw new Error(body.error || Object.values(body).join('; '));
            }
            throw new Error(body || `HTTP ${response.status}`);
        }

        return body;
    }

    function renderResults() {
        const head = document.getElementById('rva-results-head');
        const body = document.getElementById('rva-results-body');
        const meta = document.getElementById('rva-result-meta');
        const downloadButton = document.getElementById('rva-download');

        if (!resultState.rows.length) {
            head.innerHTML = '';
            body.innerHTML = '<tr><td class="text-center text-muted py-5">Нет результатов</td></tr>';
            meta.textContent = 'Выберите параметры и запустите расчет.';
            downloadButton.disabled = true;
            return;
        }

        if (resultState.mode === 'common') {
            head.innerHTML = `
                <tr>
                    <th>Станция</th>
                    <th>Виток</th>
                    <th>Начало</th>
                    <th>Максимум</th>
                    <th>Конец</th>
                    <th>Длительность, с</th>
                </tr>
            `;
            body.innerHTML = resultState.rows.map(row => `
                <tr>
                    <td>${row.stationId}</td>
                    <td>${row.revolution}</td>
                    <td>${formatDateTime(row.onStart.time)}</td>
                    <td>${formatDateTime(row.onMaximum.time)}</td>
                    <td>${formatDateTime(row.onStop.time)}</td>
                    <td>${row.duration}</td>
                </tr>
            `).join('');
        } else if (resultState.mode === 'merge') {
            head.innerHTML = `
                <tr>
                    <th>Начало</th>
                    <th>Конец</th>
                    <th>Длительность, с</th>
                </tr>
            `;
            body.innerHTML = resultState.rows.map(row => `
                <tr>
                    <td>${formatDateTime(row.begin)}</td>
                    <td>${formatDateTime(row.end)}</td>
                    <td>${row.durationSec}</td>
                </tr>
            `).join('');
        } else if (resultState.mode === 'merge-on-rev') {
            head.innerHTML = `
                <tr>
                    <th>Виток</th>
                    <th>Суммарная длительность, с</th>
                </tr>
            `;
            body.innerHTML = resultState.rows.map(row => `
                <tr>
                    <td>${row.revolution}</td>
                    <td>${formatNumber(row.durationSec, 1)}</td>
                </tr>
            `).join('');
        } else if (resultState.mode === 'average') {
            head.innerHTML = `
                <tr>
                    <th>№ППИ</th>
                    <th>Широта ППИ</th>
                    <th>Сред.кол-во</th>
                    <th>Сред.длит., с</th>
                </tr>
            `;
            body.innerHTML = resultState.rows.map(row => `
                <tr>
                    <td>${row.ppiNumber}</td>
                    <td>${formatNumber(row.ppiLatitude, 6)}</td>
                    <td>${formatNumber(row.averageCount, 3)}</td>
                    <td>${formatNumber(row.averageDurationSec, 1)}</td>
                </tr>
            `).join('');
        }

        meta.textContent = `Получено строк: ${resultState.rows.length}`;
        downloadButton.disabled = false;
    }

    function csvEscape(value) {
        const text = String(value ?? '');
        if (text.includes(';') || text.includes('"') || text.includes('\n')) {
            return `"${text.replace(/"/g, '""')}"`;
        }
        return text;
    }

    function downloadCsv() {
        if (!resultState.rows.length) {
            return;
        }

        let lines;
        if (resultState.mode === 'common') {
            lines = [
                ['stationId', 'revolution', 'onStart', 'onMaximum', 'onStop', 'duration'],
                ...resultState.rows.map(row => [
                    row.stationId,
                    row.revolution,
                    row.onStart.time,
                    row.onMaximum.time,
                    row.onStop.time,
                    row.duration
                ])
            ];
        } else if (resultState.mode === 'merge') {
            lines = [
                ['begin', 'end', 'durationSec'],
                ...resultState.rows.map(row => [
                    row.begin,
                    row.end,
                    row.durationSec
                ])
            ];
        } else if (resultState.mode === 'merge-on-rev') {
            lines = [
                ['revolution', 'durationSec'],
                ...resultState.rows.map(row => [
                    row.revolution,
                    row.durationSec
                ])
            ];
        } else {
            lines = [
                ['ppiNumber', 'ppiLatitude', 'averageCount', 'averageDurationSec'],
                ...resultState.rows.map(row => [
                    row.ppiNumber,
                    row.ppiLatitude,
                    row.averageCount,
                    row.averageDurationSec
                ])
            ];
        }

        const csv = lines.map(line => line.map(csvEscape).join(';')).join('\n');
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `rva-${resultState.mode}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }

    document.getElementById('rva-select-all').addEventListener('click', () => {
        document.querySelectorAll('.rva-station-checkbox').forEach(input => {
            input.checked = true;
        });
    });

    document.getElementById('rva-reset').addEventListener('click', () => {
        setTimeout(() => {
            showAlert('');
            resultState.rows = [];
            resultState.mode = selectedMode();
            renderResults();
        }, 0);
    });

    document.getElementById('rva-download').addEventListener('click', downloadCsv);

    document.getElementById('rva-form').addEventListener('submit', async event => {
        event.preventDefault();
        showAlert('');

        const satelliteId = Number(document.getElementById('rva-satellite').value);
        const duration = Number(document.getElementById('rva-duration').value);
        const mode = selectedMode();
        const stations = selectedStations();

        if (!satelliteId) {
            showAlert('Нужно выбрать спутник');
            return;
        }
        if (!duration || duration < 1) {
            showAlert('Горизонт расчета должен быть положительным');
            return;
        }
        if (!stations.length) {
            showAlert('Нужно выбрать хотя бы одну станцию');
            return;
        }

        const submitButton = event.submitter;
        submitButton.disabled = true;
        submitButton.textContent = 'Расчет...';

        try {
            const rows = await requestJson(`${apiBase}/${mode}/${satelliteId}/${duration}`, stations);
            resultState.mode = mode;
            resultState.rows = rows;
            renderResults();
            showAlert('Расчет выполнен', 'success');
        } catch (error) {
            showAlert(error.message || 'Не удалось выполнить расчет');
        } finally {
            submitButton.disabled = false;
            submitButton.textContent = 'Рассчитать';
        }
    });

    renderResults();
}());
