/* pm.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('meetings-value').textContent = data.total_meetings;
    document.getElementById('stats-total').textContent = data.total_meetings;
    document.getElementById('sidebar-update').textContent = new Date().toTimeString().slice(0,5);

    const list = document.getElementById('meeting-list');
    list.innerHTML = '';
    data.meetings.forEach(m => {
        const statusText = m.status === 'completed' ? 'Завершено' : 'Запланировано';
        const div = document.createElement('div');
        div.className = 'incident-item';
        div.innerHTML = `
            <div class="incident-type">
                <strong>${m.title}</strong>
                <span class="status-badge status-${m.status}">${statusText}</span>
            </div>
            <div style="font-size:.9rem;color:#94a3b8;">
                ${m.desc}<br>
                <small>${m.time}</small>
            </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_pm.php?' + Date.now());
        const r = await fetch('pm_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);
});