(function () {
    const pageRoot = document.getElementById('stations-page');
    if (!pageRoot) {
        return;
    }

    const state = {
        stations: [],
        selectedStationId: null
    };

    const tableBody = document.getElementById('stations-table-body');
    const searchInput = document.getElementById('stations-search');

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

    async function requestJson(url, options = {}) {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json'
            },
            ...options
        });

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

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

        return payload;
    }

    function formPayload() {
        const stationId = document.getElementById('station-id').value.trim();
        return {
            id: stationId || null,
            number: Number(document.getElementById('station-number').value),
            name: document.getElementById('station-name').value.trim(),
            position: {
                lat: Number(document.getElementById('station-lat').value),
                long: Number(document.getElementById('station-long').value),
                height: Number(document.getElementById('station-height').value)
            },
            elevationMin: Number(document.getElementById('station-elevation-min').value),
            elevationMax: Number(document.getElementById('station-elevation-max').value)
        };
    }

    function renderStations() {
        const query = searchInput.value.trim().toLowerCase();
        const items = state.stations.filter(station =>
            !query ||
            String(station.number).includes(query) ||
            station.name.toLowerCase().includes(query)
        );

        tableBody.innerHTML = '';
        if (!items.length) {
            tableBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted py-4">Станции не найдены</td></tr>';
            return;
        }

        items.forEach(station => {
            const row = document.createElement('tr');
            if (station.id === state.selectedStationId) {
                row.classList.add('table-active');
            }
            row.innerHTML = `
                <td>${station.number}</td>
                <td>${station.name}</td>
                <td>${station.elevationMin ?? ''}</td>
                <td>${station.elevationMax ?? ''}</td>
            `;
            row.addEventListener('click', () => selectStation(station));
            tableBody.appendChild(row);
        });
    }

    function resetForm() {
        document.getElementById('station-form').reset();
        document.getElementById('station-id').value = '';
        document.getElementById('station-form-title').textContent = 'Новая станция';
        state.selectedStationId = null;
        renderStations();
        showAlert('');
    }

    function selectStation(station) {
        state.selectedStationId = station.id ?? null;
        document.getElementById('station-id').value = station.id ?? '';
        document.getElementById('station-number').value = station.number;
        document.getElementById('station-name').value = station.name;
        document.getElementById('station-lat').value = station.position?.lat ?? '';
        document.getElementById('station-long').value = station.position?.long ?? '';
        document.getElementById('station-height').value = station.position?.height ?? '';
        document.getElementById('station-elevation-min').value = station.elevationMin;
        document.getElementById('station-elevation-max').value = station.elevationMax;
        document.getElementById('station-form-title').textContent = `Станция ${station.name}`;
        renderStations();
        showAlert('');
    }

    async function loadStations() {
        state.stations = await requestJson('/api/stations');
        renderStations();

        if (state.selectedStationId) {
            const selected = state.stations.find(station => station.id === state.selectedStationId);
            if (selected) {
                selectStation(selected);
                return;
            }
        }
        if (!document.getElementById('station-id').value) {
            resetForm();
        }
    }

    document.getElementById('stations-refresh').addEventListener('click', async () => {
        try {
            await loadStations();
        } catch (error) {
            showAlert(error.message);
        }
    });

    document.getElementById('stations-new').addEventListener('click', resetForm);
    document.getElementById('stations-reset').addEventListener('click', () => {
        window.setTimeout(resetForm, 0);
    });
    searchInput.addEventListener('input', renderStations);

    document.getElementById('station-form').addEventListener('submit', async event => {
        event.preventDefault();
        try {
            const saved = await requestJson('/api/stations', {
                method: 'POST',
                body: JSON.stringify(formPayload())
            });
            state.selectedStationId = saved.id ?? null;
            await loadStations();
            showAlert('Станция сохранена', 'success');
        } catch (error) {
            showAlert(error.message);
        }
    });

    document.getElementById('stations-delete').addEventListener('click', async () => {
        const stationId = document.getElementById('station-id').value.trim();
        if (!stationId) {
            showAlert('Сначала выберите станцию для удаления');
            return;
        }
        if (!window.confirm(`Удалить станцию ${stationId}?`)) {
            return;
        }
        try {
            await requestJson(`/api/stations/${stationId}`, { method: 'DELETE' });
            resetForm();
            await loadStations();
            showAlert('Станция удалена', 'success');
        } catch (error) {
            showAlert(error.message);
        }
    });

    loadStations().catch(error => showAlert(error.message));
})();
