/**
 * UI 交互模块 — 智途投送电脑端
 * 实机直连模式: 浏览器 ──roslibjs──► rosbridge ──MAVROS──► MAVLink ──► PX4
 * 功能: 任务调度、无人机监控、士兵位置追踪、危险区域标记、闪光检测
 */

const UIModule = (() => {
    // ---- 状态 ----
    let droneConnected = false;
    let missionRunning = false;
    let missionPaused = false;
    let mapInited = false;
    let currentPage = 'dashboard';
    let flashDetectionEnabled = false;
    let flashAvoidanceEnabled = false;

    // ---- 调度数据 ----
    const BASE_LOCATION = { lat: 30.0000, lng: 120.0000, name: '补给基地' };
    let pendingTasks = [];
    let activeTasks = [
        { id: 'TSK-001', soldier: '赵六', type: '弹药补给', drone: '无人机-02', endLat: 30.0030, endLng: 120.0060 }
    ];
    let completedCount = 128;
    let selectedTask = null;

    // ---- 士兵/危险区域 ----
    let knownSoldiers = {};
    let dangerZones = [];
    let droneLastPos = { lat: 0, lng: 0 };

    // =============== 初始化 ===============

    function init() {
        // 导航
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', () => switchPage(item.dataset.page));
        });

        // 弹窗
        document.getElementById('modal-close').addEventListener('click', closeModal);
        document.getElementById('modal-reject').addEventListener('click', onReject);
        document.getElementById('modal-dispatch').addEventListener('click', onDispatch);
        document.getElementById('modal-task').addEventListener('click', (e) => {
            if (e.target === e.currentTarget) closeModal();
        });

        // 监控页控制
        document.getElementById('btn-pause').addEventListener('click', () => {
            if (WsModule.isConnected()) WsModule.pauseMission();
        });
        document.getElementById('btn-resume').addEventListener('click', () => {
            if (WsModule.isConnected()) WsModule.resumeMission();
        });
        document.getElementById('btn-rth').addEventListener('click', () => {
            if (WsModule.isConnected()) {
                WsModule.returnHome();
                addLog('warning', '返航指令已发送...');
            }
            updateMonitorControls();
            updateDashboardStats();
        });
        document.getElementById('btn-mark-destroyed').addEventListener('click', markDroneDestroyed);
        document.getElementById('btn-clear-log').addEventListener('click', () => {
            document.getElementById('log-content').innerHTML = '';
        });

        // 连接按钮
        document.getElementById('btn-connect').addEventListener('click', onConnect);

        // 闪光检测按钮
        document.getElementById('btn-flash-enable').addEventListener('click', onEnableFlashDetection);
        document.getElementById('btn-avoidance-enable').addEventListener('click', onEnableFlashAvoidance);
        document.getElementById('btn-avoidance-disable').addEventListener('click', onDisableFlashAvoidance);

        // 初始化 WsModule
        WsModule.init();

        // 时钟
        setInterval(updateClock, 1000);
        updateClock();

        // 渲染
        renderPendingList();
        renderActiveList();
        updateDashboardStats();

        // 士兵位置轮询 (5秒)
        setInterval(fetchSoldiers, 5000);
        fetchSoldiers();

        // 需求列表轮询 (5秒) — 从后端获取APP上报的需求
        setInterval(fetchDemands, 5000);
        fetchDemands();

        // 加载已有危险区域
        fetchDangerZones();

        addLog('info', '系统就绪 — 实机连接模式');
        addLog('info', '请确保电脑已连接 P600 的 WiFi 数传，rosbridge 需在机载电脑上运行');
    }

    // ===== 从后端获取需求列表 =====
    async function fetchDemands() {
        try {
            const resp = await fetch('/api/demands');
            if (!resp.ok) return;
            const data = await resp.json();
            if (data.demands && Array.isArray(data.demands)) {
                // 转换后端数据格式为电脑端格式
                const newTasks = data.demands.map(d => ({
                    id: d.id,
                    soldier: d.soldier_name,
                    unit: d.soldier_id,
                    type: d.type,
                    items: d.items,
                    urgency: d.urgency,
                    lat: d.lat || BASE_LOCATION.lat,
                    lng: d.lng || BASE_LOCATION.lng,
                    _raw: d
                }));
                // 只更新新增的需求（避免覆盖正在操作的任务）
                const currentIds = new Set(pendingTasks.map(t => t.id));
                const added = newTasks.filter(t => !currentIds.has(t.id));
                if (added.length > 0) {
                    pendingTasks = [...pendingTasks, ...added];
                    renderPendingList();
                    updateDashboardStats();
                    addLog('success', '收到 ' + added.length + ' 条新的物资需求');
                }
            }
        } catch (e) { /* 后端未启动时静默失败 */ }
    }

    // =============== 连接管理 ===============

    function onConnect() {
        const url = document.getElementById('drone-url').value.trim();
        if (!url) {
            addLog('error', '请输入 rosbridge 连接地址');
            return;
        }
        if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
            addLog('error', '地址格式错误，应以 ws:// 开头 (例如 ws://192.168.1.14:9090)');
            return;
        }

        addLog('info', '正在连接 ' + url + ' ...');
        WsModule.connectDrone(url);
    }

    // =============== 页面路由 ===============

    function switchPage(page) {
        currentPage = page;
        document.querySelectorAll('.nav-item').forEach(i => i.classList.toggle('active', i.dataset.page === page));
        document.querySelectorAll('.page-content').forEach(s => s.classList.remove('active'));
        document.getElementById('page-' + page).classList.add('active');

        if (page === 'monitor' && !mapInited) {
            setTimeout(() => {
                MapModule.init();
                mapInited = true;
                addLog('info', '地图已加载');
            }, 50);
        }
    }

    // =============== 调度台渲染 ===============

    function renderPendingList() {
        const c = document.getElementById('pending-list');
        document.getElementById('pending-count').textContent = pendingTasks.length;
        if (pendingTasks.length === 0) { c.innerHTML = '<div class="empty-hint">暂无待处理需求</div>'; return; }
        c.innerHTML = pendingTasks.map(t => {
            const uc = t.urgency === '紧急' ? 'priority-urgent' : t.urgency === '高' ? 'priority-high' : 'priority-normal';
            return '<div class="task-item" data-id="' + t.id + '">' +
                '<span class="task-priority ' + uc + '">' + t.urgency + '</span>' +
                '<div class="task-info">' +
                    '<div class="task-name">' + t.type + ' — ' + t.soldier + ' (' + t.unit + ')</div>' +
                    '<div class="task-desc">' + t.items + '</div>' +
                '</div>' +
                '<span class="task-arrow">></span>' +
            '</div>';
        }).join('');
        c.querySelectorAll('.task-item').forEach(item => {
            item.addEventListener('click', () => {
                const t = pendingTasks.find(x => x.id === item.dataset.id);
                if (t) openModal(t);
            });
        });
    }

    function renderActiveList() {
        const c = document.getElementById('active-list');
        document.getElementById('active-count').textContent = activeTasks.length;
        if (activeTasks.length === 0) { c.innerHTML = '<div class="empty-hint">暂无飞行中任务</div>'; return; }
        c.innerHTML = activeTasks.map(t =>
            '<div class="task-item">' +
                '<span class="task-priority priority-high">飞行中</span>' +
                '<div class="task-info">' +
                    '<div class="task-name">' + t.type + ' → ' + t.soldier + ' | ' + t.drone + '</div>' +
                    '<div class="task-desc">目标: (' + t.endLat.toFixed(4) + ', ' + t.endLng.toFixed(4) + ')</div>' +
                '</div>' +
                '<span class="task-arrow">></span>' +
            '</div>'
        ).join('');
        c.querySelectorAll('.task-item').forEach(item => {
            item.addEventListener('click', () => switchPage('monitor'));
        });
    }

    function updateDashboardStats() {
        document.getElementById('stat-pending').textContent = pendingTasks.length;
        document.getElementById('stat-active').textContent = activeTasks.length;
        document.getElementById('stat-done').textContent = completedCount;
    }

    // =============== 弹窗 ===============

    function openModal(task) {
        selectedTask = task;
        const uc = task.urgency === '紧急' ? 'priority-urgent' : task.urgency === '高' ? 'priority-high' : 'priority-normal';
        document.getElementById('modal-body').innerHTML =
            '<div class="detail-row"><span class="detail-label">任务编号</span><span class="detail-value">' + task.id + '</span></div>' +
            '<div class="detail-row"><span class="detail-label">请求士兵</span><span class="detail-value">' + task.soldier + ' (' + task.unit + ')</span></div>' +
            '<div class="detail-row"><span class="detail-label">物资类型</span><span class="detail-value">' + task.type + '</span></div>' +
            '<div class="detail-row"><span class="detail-label">物资清单</span><span class="detail-value">' + task.items + '</span></div>' +
            '<div class="detail-row"><span class="detail-label">紧急程度</span><span class="detail-value"><span class="task-priority ' + uc + '">' + task.urgency + '</span></span></div>' +
            '<div class="detail-section">' +
                '<div class="detail-section-title">航线设置</div>' +
                '<div class="coord-group">' +
                    '<div class="coord-label">起点（起飞位置）</div>' +
                    '<div class="coord-inputs">' +
                        '<label>纬度 <input type="number" step="0.0001" id="start-lat" value="' + BASE_LOCATION.lat.toFixed(4) + '" /></label>' +
                        '<label>经度 <input type="number" step="0.0001" id="start-lng" value="' + BASE_LOCATION.lng.toFixed(4) + '" /></label>' +
                    '</div>' +
                    '<div class="coord-hint">' + BASE_LOCATION.name + '</div>' +
                '</div>' +
                '<div class="coord-group">' +
                    '<div class="coord-label">终点（投送位置）</div>' +
                    '<div class="coord-inputs">' +
                        '<label>纬度 <input type="number" step="0.0001" id="end-lat" value="' + task.lat.toFixed(4) + '" /></label>' +
                        '<label>经度 <input type="number" step="0.0001" id="end-lng" value="' + task.lng.toFixed(4) + '" /></label>' +
                    '</div>' +
                    '<div class="coord-hint">' + task.soldier + ' 的位置</div>' +
                '</div>' +
            '</div>' +
            '<div class="detail-section">' +
                '<div class="detail-section-title">分配无人机</div>' +
                '<div class="dispatch-option selected" onclick="this.parentElement.querySelectorAll(\'.dispatch-option\').forEach(o=>o.classList.remove(\'selected\'));this.classList.add(\'selected\')">' +
                    '<input type="radio" name="drone" value="01" checked /><label>无人机-01 (可用)</label>' +
                '</div>' +
            '</div>';
        document.getElementById('modal-task').style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('modal-task').style.display = 'none';
        selectedTask = null;
    }

    function onReject() {
        if (!selectedTask) return;
        addLog('info', '已拒绝需求: ' + selectedTask.id);
        pendingTasks = pendingTasks.filter(t => t.id !== selectedTask.id);
        renderPendingList();
        updateDashboardStats();
        closeModal();
    }

    async function onDispatch() {
        if (!selectedTask) return;

        const startLat = parseFloat(document.getElementById('start-lat').value) || BASE_LOCATION.lat;
        const startLng = parseFloat(document.getElementById('start-lng').value) || BASE_LOCATION.lng;
        const endLat = parseFloat(document.getElementById('end-lat').value) || selectedTask.lat;
        const endLng = parseFloat(document.getElementById('end-lng').value) || selectedTask.lng;

        // 向后端创建任务
        try {
            await fetch('/api/task/dispatch', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    demand_id: selectedTask.id,
                    soldier_id: selectedTask._raw ? selectedTask._raw.soldier_id : 'unknown',
                    soldier_name: selectedTask.soldier,
                    type: selectedTask.type,
                    start_name: BASE_LOCATION.name,
                    target_name: selectedTask.soldier + ' 的位置',
                    start_lat: startLat,
                    start_lng: startLng,
                    end_lat: endLat,
                    end_lng: endLng,
                    safety_score: 92
                })
            });
        } catch (e) {
            addLog('warning', '后端任务同步失败（后端可能未启动）');
        }

        if (!mapInited) {
            switchPage('monitor');
            setTimeout(() => startTask(selectedTask, startLat, startLng, endLat, endLng), 200);
        } else {
            startTask(selectedTask, startLat, startLng, endLat, endLng);
        }

        activeTasks.push({
            id: 'TSK-' + String(activeTasks.length + 1).padStart(3, '0'),
            soldier: selectedTask.soldier,
            type: selectedTask.type,
            drone: '无人机-01',
            endLat, endLng
        });
        pendingTasks = pendingTasks.filter(t => t.id !== selectedTask.id);

        addLog('success', '已调度: ' + selectedTask.type + ' → ' + selectedTask.soldier);
        addLog('info', '航线: (' + startLat.toFixed(4) + ',' + startLng.toFixed(4) + ') → (' + endLat.toFixed(4) + ',' + endLng.toFixed(4) + ')');

        renderPendingList();
        renderActiveList();
        updateDashboardStats();
        closeModal();
    }

    // =============== 任务启动 ===============

    function startTask(task, startLat, startLng, endLat, endLng) {
        MapModule.clearWaypoints();
        MapModule.addWaypoint(startLat, startLng);
        MapModule.addWaypoint(endLat, endLng);
        MapModule.updateDronePosition(startLat, startLng, 0);
        MapModule.centerOnDrone(startLat, startLng);

        document.getElementById('monitor-task').textContent = task.type;
        document.getElementById('monitor-soldier').textContent = task.soldier;
        document.getElementById('monitor-status').textContent = '飞行中';
        document.getElementById('monitor-status').className = 'tag tag-success';
        document.getElementById('monitor-flight-tag').textContent = '飞行中';
        document.getElementById('monitor-flight-tag').className = 'tag tag-success';

        missionRunning = true;
        missionPaused = false;

        if (WsModule.isConnected()) {
            WsModule.uploadMission([
                { lat: startLat, lng: startLng, alt: 15, hold_time: 0 },
                { lat: endLat, lng: endLng, alt: 15, hold_time: 0 }
            ]);
            addLog('success', '航线上传至飞控系统，准备起飞...');
            setTimeout(() => {
                WsModule.startMission();
                addLog('success', '任务已启动');
            }, 1000);

            document.getElementById('conn-dot').classList.add('connected');
            document.getElementById('conn-text').textContent = '飞行中';
        } else {
            addLog('warning', '无人机未连接，请先连接后再调度');
            document.getElementById('monitor-status').textContent = '等待连接';
            document.getElementById('monitor-status').className = 'tag tag-warning';
        }

        updateMonitorControls();
    }

    function updateMonitorControls() {
        const connected = WsModule.isConnected();
        document.getElementById('btn-pause').disabled = !connected || !missionRunning;
        document.getElementById('btn-resume').disabled = !connected || !missionPaused;
        document.getElementById('btn-rth').disabled = !connected;
        document.getElementById('btn-mark-destroyed').disabled = !droneConnected;
    }

    // =============== 士兵位置追踪 ===============

    async function fetchSoldiers() {
        try {
            const resp = await fetch('/api/soldiers');
            if (!resp.ok) return;
            const data = await resp.json();
            if (data.soldiers && Array.isArray(data.soldiers)) {
                const currentIds = new Set(data.soldiers.map(s => s.id));
                for (const id of Object.keys(knownSoldiers)) {
                    if (!currentIds.has(id)) {
                        if (mapInited) MapModule.removeSoldierMarker(id);
                        delete knownSoldiers[id];
                    }
                }
                data.soldiers.forEach(s => {
                    if (mapInited) MapModule.updateSoldierMarker(s.id, s.name, s.lat, s.lng);
                    knownSoldiers[s.id] = s;
                });
                renderSoldierList(data.soldiers);
            }
        } catch (e) { /* server not running */ }
    }

    function renderSoldierList(soldiers) {
        const container = document.getElementById('soldier-list');
        if (!container) return;
        const countEl = document.getElementById('soldier-count');
        if (countEl) countEl.textContent = soldiers.length;

        if (soldiers.length === 0) {
            container.innerHTML = '<div class="empty-hint">暂无在线士兵</div>';
            return;
        }
        container.innerHTML = soldiers.map(s =>
            '<div class="soldier-item" data-id="' + s.id + '">' +
                '<span class="soldier-dot"></span>' +
                '<div class="soldier-info">' +
                    '<div class="soldier-name">' + s.name + '</div>' +
                    '<div class="soldier-coord">(' + s.lat.toFixed(4) + ', ' + s.lng.toFixed(4) + ')</div>' +
                '</div>' +
            '</div>'
        ).join('');
        container.querySelectorAll('.soldier-item').forEach(el => {
            el.addEventListener('click', () => {
                const s = soldiers.find(x => x.id === el.dataset.id);
                if (s && mapInited) MapModule.panTo(s.lat, s.lng);
            });
        });
    }

    // =============== 危险区域管理 ===============

    async function fetchDangerZones() {
        try {
            const resp = await fetch('/api/danger-zones');
            if (!resp.ok) return;
            const data = await resp.json();
            if (data.danger_zones && Array.isArray(data.danger_zones)) {
                dangerZones = data.danger_zones;
                if (mapInited) {
                    dangerZones.forEach(dz => {
                        MapModule.addDangerZone(dz.lat, dz.lng, dz.radius || 50, dz.description);
                    });
                }
                renderDangerZoneList();
            }
        } catch (e) { /* server not running */ }
    }

    async function markDroneDestroyed() {
        if (droneLastPos.lat === 0 && droneLastPos.lng === 0) {
            addLog('error', '无法标记: 无人机位置未知');
            return;
        }

        const lat = droneLastPos.lat;
        const lng = droneLastPos.lng;
        const radius = 50;
        const description = '无人机被摧毁';

        try {
            const resp = await fetch('/api/danger-zones', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ lat, lng, radius, description })
            });
            if (resp.ok) {
                const data = await resp.json();
                addLog('error', '已标记危险区域: (' + lat.toFixed(4) + ', ' + lng.toFixed(4) + ') 半径' + radius + 'm');
                if (mapInited) MapModule.addDangerZone(lat, lng, radius, description);
                dangerZones.push({ lat, lng, radius, description, id: data.id });
                renderDangerZoneList();

                missionRunning = false;
                missionPaused = false;
                document.getElementById('monitor-status').textContent = '已摧毁';
                document.getElementById('monitor-status').className = 'tag tag-danger';
                document.getElementById('monitor-flight-tag').textContent = '已摧毁';
                document.getElementById('monitor-flight-tag').className = 'tag tag-danger';
                updateMonitorControls();
            }
        } catch (e) {
            addLog('error', '标记危险区域失败: 网络错误');
        }
    }

    function renderDangerZoneList() {
        const container = document.getElementById('danger-zone-list');
        if (!container) return;
        const countEl = document.getElementById('danger-count');
        if (countEl) countEl.textContent = dangerZones.length;

        if (dangerZones.length === 0) {
            container.innerHTML = '<div class="empty-hint">暂无危险区域</div>';
            return;
        }
        container.innerHTML = dangerZones.map(dz =>
            '<div class="danger-item">' +
                '<span class="danger-icon">&#9888;</span>' +
                '<div class="danger-info">' +
                    '<div class="danger-desc">' + (dz.description || '危险区域') + '</div>' +
                    '<div class="danger-coord">(' + dz.lat.toFixed(4) + ', ' + dz.lng.toFixed(4) + ') R' + (dz.radius || 50) + 'm</div>' +
                '</div>' +
            '</div>'
        ).join('');
    }

    // =============== 闪光检测功能 ===============

    function onEnableFlashDetection() {
        if (!droneConnected) {
            addLog('warning', '请先连接无人机');
            return;
        }

        // 初始化闪光检测模块
        if (typeof FlashDetectorModule !== 'undefined') {
            FlashDetectorModule.init(WsModule.getRos(), {
                onFlashDetected: (detected) => {
                    const statusEl = document.getElementById('flash-status');
                    if (detected) {
                        statusEl.className = 'tag tag-danger';
                        statusEl.textContent = '检测到闪光';
                    }
                },
                onDetectionData: (data) => {
                    // 更新闪光位置显示
                    document.getElementById('flash-position').textContent = '(' + data.cx.toFixed(0) + ', ' + data.cy.toFixed(0) + ')';
                    document.getElementById('flash-area').textContent = data.area.toFixed(0);

                    // 如果启用了避闪光，处理检测数据
                    if (flashAvoidanceEnabled && typeof FlashAvoidanceModule !== 'undefined') {
                        const avoidanceCmd = FlashAvoidanceModule.processDetection(data);
                        if (avoidanceCmd) {
                            executeFlashAvoidance(avoidanceCmd);
                        }
                    }
                }
            });

            flashDetectionEnabled = true;
            document.getElementById('btn-flash-enable').classList.add('hidden');
            document.getElementById('flash-status').className = 'tag tag-success';
            document.getElementById('flash-status').textContent = '已启用';
            document.getElementById('btn-avoidance-enable').disabled = false;

            addLog('success', '闪光检测已启用');
        } else {
            addLog('error', '闪光检测模块未加载');
        }
    }

    function onEnableFlashAvoidance() {
        if (!flashDetectionEnabled) {
            addLog('warning', '请先启用闪光检测');
            return;
        }

        if (typeof FlashAvoidanceModule !== 'undefined') {
            FlashAvoidanceModule.init({
                wsModule: WsModule,
                onStatusUpdate: (data) => addLog(data.type, data.message)
            });

            FlashAvoidanceModule.setStatusCallback((data) => addLog(data.type, data.message));
            FlashAvoidanceModule.setEnabled(true);

            flashAvoidanceEnabled = true;
            document.getElementById('btn-avoidance-enable').classList.add('hidden');
            document.getElementById('btn-avoidance-disable').disabled = false;

            addLog('success', '避闪光已启用');
        }
    }

    function onDisableFlashAvoidance() {
        if (typeof FlashAvoidanceModule !== 'undefined') {
            FlashAvoidanceModule.setEnabled(false);
            flashAvoidanceEnabled = false;
            document.getElementById('btn-avoidance-enable').classList.remove('hidden');
            document.getElementById('btn-avoidance-disable').disabled = true;
            addLog('info', '避闪光已禁用');
        }
    }

    function executeFlashAvoidance(avoidanceCmd) {
        // 获取当前无人机位置
        const currentPos = WsModule.getLocalPosition ? WsModule.getLocalPosition() : { x: 0, y: 0, z: 0 };

        // 计算避闪光目标位置
        const targetPos = {
            x: currentPos.x + avoidanceCmd.avoidX,
            y: currentPos.y + avoidanceCmd.avoidY,
            z: currentPos.z + avoidanceCmd.avoidZ
        };

        // 发布新的位置设定值
        WsModule.publishSetpoint(targetPos.x, targetPos.y, targetPos.z);

        addLog('warning', '执行避闪光: 移动到 (' + targetPos.x.toFixed(1) + ', ' + targetPos.y.toFixed(1) + ', ' + targetPos.z.toFixed(1) + ')');

        // 2秒后返回原位置或继续任务
        setTimeout(() => {
            FlashAvoidanceModule.endAvoidance();
            addLog('info', '避闪光完成，返回正常控制');
        }, 2000);
    }

    // =============== WsModule 回调 ===============

    function onTelemetry(data) {
        if (data.type === 'telemetry') {
            document.getElementById('mon-lat').textContent = data.lat.toFixed(6);
            document.getElementById('mon-lng').textContent = data.lng.toFixed(6);
            document.getElementById('mon-heading').textContent = data.heading.toFixed(0) + '°';
            document.getElementById('mon-battery').textContent = data.battery.toFixed(0) + '%';
            document.getElementById('mon-speed').textContent = data.speed.toFixed(1) + ' m/s';
            document.getElementById('mon-alt').textContent = data.alt.toFixed(1) + ' m';
            document.getElementById('mon-gps').textContent = data.gps_status;
            if (mapInited && (data.lat !== 0 || data.alt > 0.1)) {
                MapModule.updateDronePosition(data.lat, data.lng, data.heading);
            }
            // 追踪无人机最后位置
            if (data.lat && data.lat !== 0) {
                droneLastPos.lat = data.lat;
                droneLastPos.lng = data.lng;
            }
        }

        if (data.type === 'mission_progress') {
            document.getElementById('mon-dist').textContent =
                '航点 ' + data.current + '/' + data.total;
        }
    }

    function onStatus(data) {
        addLog(data.type, data.message);

        const msg = data.message;

        if (msg.includes('无人机已连接') || msg.includes('飞控已就绪')) {
            droneConnected = true;
            document.getElementById('conn-dot').classList.add('connected');
            document.getElementById('conn-text').textContent = '已连接';
            document.getElementById('btn-connect').textContent = '已连接';
            document.getElementById('btn-connect').disabled = true;
            document.getElementById('monitor-status').textContent = '待命';
            document.getElementById('monitor-status').className = 'tag tag-success';
            document.getElementById('btn-flash-enable').disabled = false;
            updateMonitorControls();
        }

        if (msg.includes('任务完成') || msg.includes('所有航点已到达')) {
            missionRunning = false;
            missionPaused = false;
            document.getElementById('monitor-status').textContent = '已到达';
            document.getElementById('monitor-status').className = 'tag tag-info';
            document.getElementById('monitor-flight-tag').textContent = '已到达';
            document.getElementById('monitor-flight-tag').className = 'tag tag-info';
            completedCount++;
            updateDashboardStats();
            updateMonitorControls();
        }

        if (msg.includes('起飞完成') || msg.includes('巡航')) {
            missionRunning = true;
            missionPaused = false;
            updateMonitorControls();
        }

        if (msg.includes('降落')) {
            missionRunning = false;
            missionPaused = false;
            document.getElementById('monitor-status').textContent = '降落中';
            document.getElementById('monitor-status').className = 'tag tag-warning';
            document.getElementById('monitor-flight-tag').textContent = '降落中';
            document.getElementById('monitor-flight-tag').className = 'tag tag-warning';
            updateMonitorControls();
        }
    }

    function onDroneDisconnected() {
        droneConnected = false;
        missionRunning = false;
        missionPaused = false;
        flashDetectionEnabled = false;
        flashAvoidanceEnabled = false;

        document.getElementById('conn-dot').classList.remove('connected');
        document.getElementById('conn-text').textContent = '未连接';
        document.getElementById('btn-connect').textContent = '连接';
        document.getElementById('btn-connect').disabled = false;
        document.getElementById('monitor-status').textContent = '离线';
        document.getElementById('monitor-status').className = 'tag tag-danger';
        document.getElementById('btn-flash-enable').disabled = true;
        document.getElementById('btn-flash-enable').classList.remove('hidden');
        document.getElementById('btn-avoidance-enable').disabled = true;
        document.getElementById('btn-avoidance-enable').classList.remove('hidden');
        document.getElementById('btn-avoidance-disable').disabled = true;
        document.getElementById('flash-status').className = 'tag tag-secondary';
        document.getElementById('flash-status').textContent = '未启用';
        document.getElementById('flash-position').textContent = '--';
        document.getElementById('flash-area').textContent = '--';

        // 关闭闪光检测模块
        if (typeof FlashDetectorModule !== 'undefined') {
            FlashDetectorModule.shutdown();
        }
        if (typeof FlashAvoidanceModule !== 'undefined') {
            FlashAvoidanceModule.reset();
        }

        updateMonitorControls();
        addLog('error', '无人机连接断开');
    }

    // =============== 日志 ===============

    function addLog(type, message) {
        const c = document.getElementById('log-content');
        if (!c) return;
        const time = new Date().toTimeString().split(' ')[0];
        const entry = document.createElement('div');
        entry.className = 'log-entry ' + type;
        entry.innerHTML = '<span class="time">[' + time + ']</span>' + message;
        c.appendChild(entry);
        c.scrollTop = c.scrollHeight;
        while (c.children.length > 200) c.removeChild(c.firstChild);
    }

    function updateClock() {
        const now = new Date().toTimeString().split(' ')[0];
        const el1 = document.getElementById('chip-time');
        const el2 = document.getElementById('chip-time-mon');
        if (el1) el1.textContent = now;
        if (el2) el2.textContent = now;
    }

    // 航点列表（保留接口，map.js 回调用）
    function updateWaypointList() {}
    function updateButtons() {}

    return {
        init,
        onTelemetry,
        onStatus,
        onDroneDisconnected,
        updateWaypointList,
        updateButtons,
        addLog
    };
})();

document.addEventListener('DOMContentLoaded', () => {
    UIModule.init();
});
