/**
 * 热成像威胁检测模块
 * 负责: 接收热成像检测结果、在地图上标注威胁、更新威胁列表UI
 */

const ThermalModule = (() => {
    let threats = [];
    let pollTimer = null;
    const POLL_INTERVAL = 3000; // ms

    function init() {
        // 自动轮询模式 (如果有后端API)
        // startPolling('http://localhost:5000/api/threats');
    }

    /**
     * 开始轮询后端威胁数据
     * @param {string} apiUrl - 后端热成像API地址
     */
    function startPolling(apiUrl) {
        stopPolling();
        pollTimer = setInterval(() => fetchThreats(apiUrl), POLL_INTERVAL);
        fetchThreats(apiUrl);
    }

    function stopPolling() {
        if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
    }

    /**
     * 从后端获取最新威胁数据
     */
    async function fetchThreats(apiUrl) {
        try {
            const resp = await fetch(apiUrl);
            if (!resp.ok) return;
            const data = await resp.json();
            if (data.threats && Array.isArray(data.threats)) {
                processThreats(data.threats);
            }
        } catch (e) {
            // 静默忽略网络错误
        }
    }

    /**
     * 直接传入威胁数据 (用于手动推送或模拟)
     * @param {Array} newThreats - 威胁数组 [{lat, lng, level, description, time}]
     */
    function processThreats(newThreats) {
        // 清除旧威胁标记
        MapModule.clearThreats();
        threats = newThreats;

        // 在地图上添加标记
        newThreats.forEach(t => {
            MapModule.addThreatMarker(t.lat, t.lng, t.level, t.description);
        });

        // 更新威胁列表UI
        renderThreatList();
    }

    /**
     * 添加单个威胁
     */
    function addThreat(threat) {
        threats.push(threat);
        MapModule.addThreatMarker(threat.lat, threat.lng, threat.level, threat.description);
        renderThreatList();

        if (threat.level === 'high') {
            UIModule.addLog('error', `热成像告警: ${threat.description} (${threat.lat.toFixed(4)}, ${threat.lng.toFixed(4)})`);
        } else {
            UIModule.addLog('warning', `威胁检测: ${threat.description}`);
        }
    }

    function renderThreatList() {
        const container = document.getElementById('threat-list');
        if (!container) return;

        if (threats.length === 0) {
            container.innerHTML = '<div class="empty-hint">暂无威胁检测</div>';
            return;
        }

        container.innerHTML = threats.map(t => `
            <div class="threat-item level-${t.level}">
                <span class="threat-dot ${t.level}"></span>
                <span class="threat-text">${t.description}</span>
                <span class="threat-time">${t.time || '--'}</span>
            </div>
        `).join('');
    }

    function getThreats() {
        return threats;
    }

    function clearThreats() {
        threats = [];
        MapModule.clearThreats();
        renderThreatList();
    }

    /**
     * 模拟威胁数据 (用于演示)
     */
    function simulateThreats() {
        const baseLat = 30.0;
        const baseLng = 120.0;

        const demo = [
            { lat: baseLat + 0.0008, lng: baseLng - 0.0005, level: 'high', description: '热源: 人员活动', time: '14:32' },
            { lat: baseLat - 0.0012, lng: baseLng + 0.001, level: 'medium', description: '热源: 车辆引擎', time: '14:28' },
            { lat: baseLat + 0.0003, lng: baseLng + 0.0018, level: 'low', description: '热源: 动物', time: '14:25' }
        ];

        processThreats(demo);
        UIModule.addLog('info', '已加载模拟威胁数据 (3个热源)');
    }

    return {
        init,
        startPolling,
        stopPolling,
        processThreats,
        addThreat,
        getThreats,
        clearThreats,
        simulateThreats
    };
})();
