/* satellite.js – полностью CSP‑safe */
const UPDATE_INTERVAL_MINUTES = 30;
let countdownInterval;

function updateDOM(data) {
    document.getElementById('last-update').textContent = data.last_update;
    document.getElementById('aal-circle').textContent = data.aal + '.0';
    document.getElementById('aal-circle').style.background = data.aal_color;
    document.getElementById('aal-text').textContent = data.aal_text;
    document.getElementById('missions-value').textContent = data.active_missions;
    document.getElementById('stats-missions').textContent = data.active_missions;
    document.getElementById('sidebar-update').textContent = new Date().toTimeString().slice(0,5);

    const list = document.getElementById('mission-list');
    list.innerHTML = '';
    if (data.missions.length === 0) {
        const p = document.createElement('p');
        p.textContent = 'Нет активных миссий';
        p.style.cssText = 'text-align:center;color:#94a3b8;font-style:italic;';
        list.appendChild(p);
    } else {
        data.missions.forEach(m => {
            const div = document.createElement('div');
            div.className = 'incident-item';
            div.innerHTML = `
                <div class="incident-type">
                    <strong>${m.name}</strong>
                    <span style="margin-left:.5rem;font-size:.8rem;color:#94a3b8;">
                        ${m.orbit} • ${m.operator}
                    </span>
                </div>
                <div style="font-size:.9rem;color:#94a3b8;">${m.desc}</div>`;
            list.appendChild(div);
        });
    }

    document.getElementById('update-status').textContent = 'Обновлено!';
    setTimeout(() => document.getElementById('update-status').textContent = 'Обновление через 30:00', 3000);
}

async function fetchData() {
    try {
        await fetch('fetch_satellite.php?' + Date.now());
        const r = await fetch('satellite_cache.json?' + Date.now());
        const data = await r.json();
        updateDOM(data);
    } catch (e) { console.error(e); }
}

function startCountdown() {
    const now  = Date.now();
    const next = Math.ceil(now / (UPDATE_INTERVAL_MINUTES * 60 * 1000)) * (UPDATE_INTERVAL_MINUTES * 60 * 1000);
    let remaining = next - now;

    countdownInterval = setInterval(() => {
        remaining -= 1000;
        const min = String(Math.floor(remaining / 60000)).padStart(2,'0');
        const sec = String(Math.floor((remaining % 60000) / 1000)).padStart(2,'0');
        document.getElementById('countdown').textContent = `${min}:${sec}`;
        document.getElementById('next-update').textContent = new Date(next).toTimeString().slice(0,5);
        if (remaining <= 0) { clearInterval(countdownInterval); fetchData().then(startCountdown); }
    }, 1000);
}

document.addEventListener('DOMContentLoaded', () => {
    startCountdown();
    setTimeout(fetchData, 30000);
});