/**
 * 单兵终端APP - 主应用模块
 * 路由、状态管理、页面交互逻辑
 */

const App = (() => {
    // ===== 配置 =====
    const CONFIG = {
        apiBase: localStorage.getItem('api_base') || 'http://121.41.216.243',
        soldierId: '',
        soldierName: '',
        soldierUnit: '',
        pollInterval: 5000
    };

    // ===== 状态 =====
    let currentPage = 'home';
    let pageStack = ['home'];
    let selectedDropPoint = null;
    let mapSelectedPoint = null;  // 地图选中的投放点
    let pollTimer = null;

    // ===== 页面映射（用于Tab导航显示控制） =====
    const TAB_PAGES = ['home', 'task', 'drone', 'profile'];

    // ===== 初始化 =====
    function init() {
        // 检查登录状态
        const saved = localStorage.getItem('soldier_session');
        if (saved) {
            try {
                const session = JSON.parse(saved);
                CONFIG.soldierId = session.soldier_id;
                CONFIG.soldierName = session.name;
                CONFIG.soldierUnit = session.unit;
                router('home');
                startPolling();
                startLocationReporting();
                updateSoldierInfo();
                showToast('欢迎回来，' + CONFIG.soldierName);
            } catch (e) {
                router('login');
            }
        } else {
            router('login');
        }

        // 绑定单选按钮
        document.querySelectorAll('.radio-group').forEach(group => {
            group.querySelectorAll('.radio-label').forEach(label => {
                label.addEventListener('click', () => {
                    group.querySelectorAll('.radio-label').forEach(l => l.classList.remove('active'));
                    label.classList.add('active');
                });
            });
        });

        // 物资类型切换单位
        const typeSelect = document.getElementById('demand-type');
        if (typeSelect) {
            typeSelect.addEventListener('change', (e) => {
                const unitMap = { '弹药': '发', '食物': '份', '医药': '箱', '饮水': '升' };
                document.getElementById('demand-unit').textContent = unitMap[e.target.value] || '个';
            });
        }
    }

    // ===== 启动GPS自动上报 =====
    function startLocationReporting() {
        if (!CONFIG.soldierId) return;
        LocationModule.startReporting(CONFIG.soldierId, CONFIG.soldierName, 10000);
    }

    // ===== 路由切换 =====
    function router(page) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
        // 显示目标页面
        const target = document.getElementById('page-' + page);
        if (target) target.classList.add('active');

        // 更新Tab导航高亮
        document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
        const tabItem = document.querySelector('.tab-item[data-page="' + page + '"]');
        if (tabItem) tabItem.classList.add('active');

        // 控制Tab栏显示（仅在Tab页面显示）
        const tabBar = document.getElementById('tab-bar');
        if (tabBar) {
            tabBar.style.display = TAB_PAGES.includes(page) ? 'flex' : 'none';
        }

        // 记录页面栈
        if (page !== currentPage) {
            pageStack.push(page);
            currentPage = page;
        }

        // 页面专属初始化
        onPageEnter(page);
    }

    // ===== 返回 =====
    function back() {
        if (pageStack.length > 1) {
            pageStack.pop();
            const prev = pageStack[pageStack.length - 1];
            document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
            const target = document.getElementById('page-' + prev);
            if (target) target.classList.add('active');

            document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
            const tabItem = document.querySelector('.tab-item[data-page="' + prev + '"]');
            if (tabItem) tabItem.classList.add('active');

            const tabBar = document.getElementById('tab-bar');
            if (tabBar) {
                tabBar.style.display = TAB_PAGES.includes(prev) ? 'flex' : 'none';
            }

            currentPage = prev;
        }
    }

    // ===== 页面进入回调 =====
    function onPageEnter(page) {
        switch (page) {
            case 'home':
                updateHomeLocation();
                break;
            case 'drop':
                // 延迟初始化，确保页面完全显示后再加载地图
                setTimeout(() => loadDropPoints(), 500);
                break;
            case 'task':
                loadTaskInfo();
                break;
            case 'drone':
                loadDroneStatus();
                break;
            case 'location':
                refreshLocation();
                break;
        }
    }

    // ===== 更新士兵信息 =====
    function updateSoldierInfo() {
        const un = document.getElementById('user-name');
        if (un) un.textContent = CONFIG.soldierName;
        const uu = document.getElementById('user-unit');
        if (uu) uu.textContent = '所属：' + CONFIG.soldierUnit;
        const pn = document.getElementById('profile-name');
        if (pn) pn.textContent = '前线士兵：' + CONFIG.soldierName;
        const pu = document.getElementById('profile-unit');
        if (pu) pu.textContent = '所属：' + CONFIG.soldierUnit + ' | 职位：狙击手';

        // 更新服务器地址显示
        const serverAddrEl = document.getElementById('server-addr');
        if (serverAddrEl) {
            serverAddrEl.textContent = CONFIG.apiBase.replace('http://', '').replace(':5000', '') + ' →';
        }
    }

    // ===== 服务器地址配置 =====
    function showServerConfig() {
        const current = CONFIG.apiBase;
        const input = prompt('请输入后端服务器地址（包含端口号）：\n示例: http://192.168.1.14:5000', current);
        if (input && input.trim()) {
            let url = input.trim();
            if (!url.startsWith('http')) url = 'http://' + url;
            CONFIG.apiBase = url;
            localStorage.setItem('api_base', url);
            API.setBase(url);
            updateSoldierInfo();
            showToast('服务器地址已更新');
        }
    }

    // ===== 登录 =====
    async function doLogin() {
        const id = document.getElementById('login-id').value.trim();
        const pwd = document.getElementById('login-pwd').value.trim();
        if (!id || !pwd) {
            showToast('请输入士兵编号和密码');
            return;
        }

        try {
            const result = await API.login(id, pwd);
            if (result.ok) {
                API.setToken(result.token);  // 保存认证令牌到前后端统一中心
                CONFIG.soldierId = result.soldier_id;
                CONFIG.soldierName = result.name;
                CONFIG.soldierUnit = result.unit;
                localStorage.setItem('soldier_session', JSON.stringify({
                    soldier_id: result.soldier_id,
                    name: result.name,
                    unit: result.unit,
                    role: result.role
                }));
                updateSoldierInfo();
                router('home');
                startPolling();
                startLocationReporting();
                showToast('登录成功，欢迎 ' + result.name);
            } else {
                showToast('登录失败：' + (result.error || '未知错误'));
            }
        } catch (e) {
            showToast('登录失败：' + (e.message || '网络错误') + '\n请确认后端已启动');
        }
    }

    // ===== 注册 =====
    async function doRegister() {
        const id = document.getElementById('reg-id').value.trim();
        const name = document.getElementById('reg-name').value.trim();
        const pwd = document.getElementById('reg-pwd').value.trim();
        const unit = document.getElementById('reg-unit').value.trim();
        const role = document.getElementById('reg-role').value.trim();

        if (!id || !name || !pwd) {
            showToast('请填写士兵编号、姓名和密码');
            return;
        }

        try {
            const result = await API.register({ soldier_id: id, password: pwd, name, unit, role });
            if (result.ok) {
                showToast('注册成功，请登录');
                setTimeout(() => router('login'), 800);
            } else {
                showToast('注册失败：' + (result.error || '未知错误'));
            }
        } catch (e) {
            showToast('注册失败：' + (e.message || '网络错误') + '\n请确认后端已启动');
        }
    }

    // ===== 填充演示账号 =====
    function fillLogin(id, pwd) {
        document.getElementById('login-id').value = id;
        document.getElementById('login-pwd').value = pwd;
        doLogin();
    }

    // ===== 退出登录 =====
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('soldier_session');
            API.setToken('');  // 清除认证令牌
            CONFIG.soldierId = '';
            CONFIG.soldierName = '';
            stopPolling();
            router('login');
            showToast('已退出登录');
        }
    }

    // ===== 更新首页位置 =====
    function updateHomeLocation() {
        const loc = LocationModule.getLastPosition();
        if (loc) {
            const locEl = document.getElementById('home-loc');
            if (locEl) locEl.textContent = `${loc.lat.toFixed(6)}, ${loc.lng.toFixed(6)}`;
            const accEl = document.getElementById('home-accuracy');
            if (accEl) {
                const sourceText = LocationModule.getSourceText ? LocationModule.getSourceText(loc.source) : '';
                accEl.textContent = LocationModule.formatAccuracy(loc.accuracy) + (sourceText ? ' · ' + sourceText : '');
            }
            const statusEl = document.getElementById('home-report-status');
            if (statusEl) {
                statusEl.textContent = '已上报';
                statusEl.style.color = '#52c41a';
            }
        }
    }

    // ===== 提交需求 =====
    async function submitDemand() {
        const type = document.getElementById('demand-type').value;
        const qty = document.getElementById('demand-qty').value;
        const urgencyEl = document.querySelector('#urgency-group .radio-label.active');
        const urgency = urgencyEl ? urgencyEl.dataset.value : '紧急';

        const num = parseInt(qty, 10);
        if (isNaN(num) || num < 1) {
            showToast('请输入有效数量');
            return;
        }

        showToast('正在上报...');

        // 构建投放点数据
        let dropPointData = null;
        if (selectedDropPoint) {
            dropPointData = {
                name: selectedDropPoint.name,
                lat: selectedDropPoint.lat,
                lng: selectedDropPoint.lng,
                safety_score: selectedDropPoint.safety_score
            };
        }

        const demand = {
            soldier_id: CONFIG.soldierId,
            soldier_name: CONFIG.soldierName,
            type: type,
            quantity: num,
            unit: document.getElementById('demand-unit').textContent,
            urgency: urgency,
            drop_point: dropPointData,
            status: '待处理',
            created_at: new Date().toISOString()
        };

        try {
            await API.postDemand(demand);
            showToast('✅ 需求上报成功！');
            selectedDropPoint = null;
            const dropDisplay = document.getElementById('demand-drop-display');
            if (dropDisplay) dropDisplay.textContent = '当前位置：A区街角12号';
            setTimeout(() => router('home'), 1000);
        } catch (e) {
            showToast('❌ 上报失败：' + (e.message || '网络错误'));
        }
    }

    // ===== 加载投放点（含地图选点） =====
    async function loadDropPoints() {
        // 初始化地图选点
        setTimeout(async () => {
            await LocationModule.initPickerMap('drop-map', (point) => {
                mapSelectedPoint = point;
                // 更新UI显示
                const nameEl = document.getElementById('drop-selected-name');
                const addrEl = document.getElementById('drop-selected-address');
                const coordEl = document.getElementById('drop-selected-coords');
                if (nameEl) nameEl.textContent = point.name;
                if (addrEl) addrEl.textContent = point.address;
                if (coordEl) coordEl.textContent = `${point.lat.toFixed(6)}, ${point.lng.toFixed(6)}`;
                showToast('📍 已选择：' + point.name);
            });
        }, 300);

        // 加载推荐列表
        const list = document.getElementById('drop-point-list');
        list.innerHTML = '<div style="text-align:center;color:#999;padding:20px;">加载中...</div>';

        try {
            const points = await API.getDropPoints();
            if (!points || points.length === 0) {
                list.innerHTML = '<div style="text-align:center;color:#999;padding:20px;">暂无推荐投放点</div>';
                return;
            }

            list.innerHTML = points.map((p, i) => {
                const isSafe = p.safety_score >= 70;
                return `
                    <div class="card drop-card ${isSafe ? 'safe' : 'danger'}" onclick="App.selectDropPoint(${i})" style="cursor:pointer;">
                        <div style="font-size:14px;color:#333;margin-bottom:5px;">📍 ${p.name}</div>
                        <div class="drop-info">
                            <span>安全系数: ${p.safety_score}%</span>
                            <span>距离: ${p.distance}m</span>
                        </div>
                        <div style="font-size:12px;color:#666;margin-bottom:10px;">${p.reason}</div>
                        <div style="font-size:12px;color:${isSafe ? '#52c41a' : '#ff4d4f'};">
                            ${isSafe ? '✅ 推荐投放' : '❌ 危险区域'}
                        </div>
                    </div>
                `;
            }).join('');
        } catch (e) {
            list.innerHTML = '<div style="text-align:center;color:#999;padding:20px;">加载失败</div>';
        }
    }

    // ===== 搜索地点 =====
    function searchDropPoint() {
        const input = document.getElementById('drop-search-input');
        const resultsDiv = document.getElementById('drop-search-results');
        const keyword = input ? input.value.trim() : '';
        if (!keyword) {
            showToast('请输入搜索关键词');
            return;
        }

        resultsDiv.innerHTML = '<div style="padding:8px;color:#999;font-size:12px;">搜索中...</div>';

        LocationModule.searchPlace(keyword, (err, pois) => {
            if (err || pois.length === 0) {
                resultsDiv.innerHTML = '<div style="padding:8px;color:#999;font-size:12px;">未找到相关地点</div>';
                return;
            }

            resultsDiv.innerHTML = pois.map((p, i) => `
                <div onclick="App.selectSearchResult(${i})" 
                     style="padding:8px 10px;border-bottom:1px solid #f0f0f0;cursor:pointer;"
                     data-name="${p.name}" data-address="${p.address}" data-lat="${p.lat}" data-lng="${p.lng}">
                    <div style="font-size:13px;color:#333;">${p.name}</div>
                    <div style="font-size:11px;color:#999;">${p.address}</div>
                </div>
            `).join('');

            // 存储搜索结果供点击使用
            window._searchResults = pois;
        });
    }

    // 选择搜索结果
    async function selectSearchResult(index) {
        const pois = window._searchResults || [];
        const p = pois[index];
        if (!p) return;

        // 在地图上定位
        await LocationModule.setPickerPosition(p.lat, p.lng, p.name, p.address);

        // 更新选中状态
        mapSelectedPoint = {
            lat: p.lat,
            lng: p.lng,
            name: p.name,
            address: p.address
        };

        // 更新UI
        const nameEl = document.getElementById('drop-selected-name');
        const addrEl = document.getElementById('drop-selected-address');
        const coordEl = document.getElementById('drop-selected-coords');
        if (nameEl) nameEl.textContent = p.name;
        if (addrEl) addrEl.textContent = p.address;
        if (coordEl) coordEl.textContent = `${p.lat.toFixed(6)}, ${p.lng.toFixed(6)}`;

        // 清空搜索结果
        const resultsDiv = document.getElementById('drop-search-results');
        if (resultsDiv) resultsDiv.innerHTML = '';

        showToast('📍 已定位：' + p.name);
    }

    // ===== 选择投放点（从列表） =====
    function selectDropPoint(index) {
        API.getDropPoints().then(async points => {
            const p = points[index];
            if (p.safety_score < 70) {
                showToast('⚠️ 该区域危险，建议选择其他投放点');
                return;
            }
            selectedDropPoint = p;

            // 同时在地图上标记
            await LocationModule.setPickerPosition(p.lat, p.lng, p.name, p.address);

            // 更新选中显示
            mapSelectedPoint = {
                lat: p.lat,
                lng: p.lng,
                name: p.name,
                address: p.address || p.name
            };
            const nameEl = document.getElementById('drop-selected-name');
            const addrEl = document.getElementById('drop-selected-address');
            const coordEl = document.getElementById('drop-selected-coords');
            if (nameEl) nameEl.textContent = p.name;
            if (addrEl) addrEl.textContent = p.address || '安全系数 ' + p.safety_score + '%';
            if (coordEl) coordEl.textContent = `${p.lat.toFixed(6)}, ${p.lng.toFixed(6)}`;

            showToast('已选择：' + p.name);
        });
    }

    function confirmDropPoint() {
        // 优先使用地图选中的点
        if (mapSelectedPoint) {
            selectedDropPoint = mapSelectedPoint;
            router('demand');
            const display = document.getElementById('demand-drop-display');
            if (display) display.textContent = mapSelectedPoint.name;
            showToast('✅ 已确认投放点：' + mapSelectedPoint.name);
            return;
        }
        // fallback到列表选中的点
        if (selectedDropPoint) {
            router('demand');
            const display = document.getElementById('demand-drop-display');
            if (display) display.textContent = selectedDropPoint.name;
            return;
        }
        showToast('请先点击地图或列表选择一个投放点');
    }

    // ===== 加载任务信息 =====
    async function loadTaskInfo() {
        try {
            const task = await API.getCurrentTask(CONFIG.soldierId);
            if (task) {
                const tid = document.getElementById('task-id');
                if (tid) tid.textContent = task.id || '#--';

                const tstatus = document.getElementById('task-status');
                if (tstatus) {
                    const statusMap = {
                        '执行中': { text: '🟢 执行中', cls: 'running' },
                        '已完成': { text: '✅ 已完成', cls: 'done' },
                        '无任务': { text: '⚪ 无任务', cls: '' }
                    };
                    const sm = statusMap[task.status] || { text: task.status, cls: '' };
                    tstatus.textContent = sm.text;
                    tstatus.className = 'task-status ' + sm.cls;
                }

                const teta = document.getElementById('task-eta');
                if (teta) teta.textContent = '预计到达：' + (task.eta || '--');

                const tprog = document.getElementById('task-progress-text');
                if (tprog) {
                    const prog = task.progress || 0;
                    const barLen = 20;
                    const filled = Math.round(barLen * prog / 100);
                    const bar = '█'.repeat(filled) + '░'.repeat(barLen - filled);
                    tprog.textContent = bar + ' ' + prog + '%';
                }

                const tremain = document.getElementById('task-remain');
                if (tremain) tremain.textContent = '剩余时间：' + (task.remain_time || '--');

                const tstart = document.getElementById('task-start');
                if (tstart) tstart.textContent = task.start_name || '后方阵地';

                const ttarget = document.getElementById('task-target');
                if (ttarget) ttarget.textContent = task.target_name || '目标位置';

                const trisk = document.getElementById('task-risk');
                if (trisk) trisk.textContent = '安全系数: ' + (task.safety_score || 0) + '%';
            }
        } catch (e) {
            console.log('任务加载失败', e);
        }
    }

    // ===== 加载无人机状态 =====
    // 安全设置 DOM 文本，避免元素不存在时崩溃
    function setText(id, value) {
        const el = document.getElementById(id);
        if (el) el.textContent = value;
    }

    async function loadDroneStatus() {
        try {
            const status = await API.getDroneStatus();
            if (status) {
                setText('drone-id', status.drone_id || '无人机-01');
                setText('drone-task-id', status.task_id || '#--');
                setText('drone-status', status.status || '待命');
                setText('drone-pos', status.position || '--');
                setText('drone-battery', (status.battery || '--') + '%');
                setText('drone-eta', status.eta || '--');
                setText('drone-speed', (status.speed || '--') + 'm/s');
                setText('drone-alt', (status.altitude || '--') + 'm');
                setText('drone-dist', (status.distance || '--') + 'm');
                setText('drone-temp', (status.temperature || '--') + '°C');
            }

            const logs = await API.getDroneLogs();
            const logContainer = document.getElementById('drone-logs');
            if (logContainer && logs && logs.length > 0) {
                logContainer.innerHTML = logs.map(l =>
                    `<div class="log-row"><span class="log-time">${l.time}</span> ${l.message}</div>`
                ).join('');
            }
        } catch (e) {
            console.log('无人机状态加载失败', e);
        }
    }

    // ===== 手动修正位置 =====
    function manualSetLocation() {
        const input = prompt('请输入您的坐标（格式：纬度,经度）\n示例：28.2280,112.9388\n长沙大约：28.2280,112.9388');
        if (!input) return;
        const parts = input.split(',').map(s => parseFloat(s.trim()));
        if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
            const pos = { lat: parts[0], lng: parts[1], accuracy: 10, source: 'manual' };
            LocationModule.lastPosition = pos;
            const curEl = document.getElementById('loc-current');
            if (curEl) curEl.textContent = `${pos.lat.toFixed(6)}, ${pos.lng.toFixed(6)}`;
            const accEl = document.getElementById('loc-accuracy');
            if (accEl) accEl.textContent = '手动设置 · 精确';
            updateHomeLocation();
            showToast('位置已手动修正');
            // 刷新地图
            const mapContainer = document.getElementById('loc-map');
            if (mapContainer) {
                mapContainer.innerHTML = '';
                setTimeout(() => LocationModule.showMap('loc-map', pos.lat, pos.lng), 100);
            }
        } else {
            showToast('格式错误，请使用：纬度,经度');
        }
    }

    // ===== 刷新位置 =====
    async function refreshLocation() {
        const curEl = document.getElementById('loc-current');
        if (curEl) curEl.textContent = '定位中...';

        try {
            const pos = await LocationModule.getCurrentPosition();
            const sourceText = LocationModule.getSourceText(pos.source);

            // 更新当前位置显示
            if (curEl) {
                if (pos.source === 'default') {
                    curEl.innerHTML = `<span style="color:#999">${pos.lat.toFixed(4)}, ${pos.lng.toFixed(4)}</span>`;
                } else if (pos.source === 'ip') {
                    curEl.innerHTML = `${pos.lat.toFixed(4)}, ${pos.lng.toFixed(4)} <span style="color:#1890ff;font-size:12px">(${sourceText})</span>`;
                } else {
                    curEl.textContent = `${pos.lat.toFixed(6)}, ${pos.lng.toFixed(6)}`;
                }
            }

            // 更新精度显示
            const accEl = document.getElementById('loc-accuracy');
            if (accEl) {
                let text = LocationModule.formatAccuracy(pos.accuracy) + ' · ' + sourceText;
                if (pos.source === 'default') {
                    text = '❌ 定位失败 · 使用默认坐标';
                } else if (pos.source === 'ip') {
                    text = '📡 ' + LocationModule.formatAccuracy(pos.accuracy) + ' · ' + sourceText + (pos.city ? ' (' + pos.city + ')' : '');
                }
                accEl.textContent = text;
            }

            // 更新上报时间
            const reportEl = document.getElementById('loc-last-report');
            if (reportEl) reportEl.textContent = new Date().toTimeString().split(' ')[0];

            // 更新偏移距离
            const offsetEl = document.getElementById('loc-offset');
            if (offsetEl) {
                offsetEl.textContent = '计算中...';
                setTimeout(() => {
                    if (offsetEl) offsetEl.textContent = Math.floor(Math.random() * 100) + 'm';
                    const timeEl = document.getElementById('loc-offset-time');
                    if (timeEl) timeEl.textContent = '刚刚';
                }, 500);
            }

            // 初始化/更新地图
            const mapContainer = document.getElementById('loc-map');
            if (mapContainer) {
                if (pos.source === 'default') {
                    // 定位完全失败，显示诊断信息
                    const reasons = await LocationModule.getLocationErrorReason();
                    mapContainer.innerHTML = `
                        <div style="text-align:center;color:#666;padding:15px;">
                            <div style="font-size:28px;margin-bottom:8px;">🚫</div>
                            <div style="font-size:14px;font-weight:bold;margin-bottom:8px;">定位失败</div>
                            <div style="font-size:12px;color:#999;text-align:left;display:inline-block;">
                                ${reasons.map(r => '• ' + r).join('<br>')}
                            </div>
                            <div style="font-size:12px;color:#1890ff;margin-top:10px;">
                                💡 建议：开启WiFi + GPS + 到窗边
                            </div>
                        </div>`;
                } else {
                    mapContainer.innerHTML = '';
                    mapContainer.style.border = 'none';
                    setTimeout(() => LocationModule.showMap('loc-map', pos.lat, pos.lng), 100);
                }
            }

            updateHomeLocation();

        } catch (e) {
            if (curEl) curEl.textContent = '定位异常';
            console.error('refreshLocation错误:', e);
        }
    }

    function updateDropPoint() {
        showToast('投放点已更新');
        setTimeout(() => router('task'), 500);
    }

    // ===== 标注 =====
    function addAnnotate() {
        showToast('标注功能开发中');
    }

    // ===== SOS求救 =====
    async function triggerSOS() {
        if (!confirm('确认发送求救信号？此操作将立即上报您的当前位置。')) return;
        try {
            const pos = await LocationModule.getCurrentPosition();
            await API.sendSOS({
                soldier_id: CONFIG.soldierId,
                soldier_name: CONFIG.soldierName,
                lat: pos.lat,
                lng: pos.lng,
                time: new Date().toISOString()
            });
            showToast('🚨 求救信号已发送！');
        } catch (e) {
            showToast('求救发送失败：' + (e.message || '网络错误'));
        }
    }

    // ===== Toggle开关切换 =====
    function toggleSwitch(el) {
        const toggle = el.querySelector('.menu-toggle');
        if (toggle) {
            toggle.classList.toggle('on');
            const label = el.querySelector('span:first-child').textContent;
            const state = toggle.classList.contains('on') ? '已开启' : '已关闭';
            showToast(label.replace(/[🌐🌙🔔📥🔐]/g, '').trim() + state);
        }
    }

    // ===== 轮询 =====
    function startPolling() {
        if (pollTimer) clearInterval(pollTimer);
        pollTimer = setInterval(() => {
            if (currentPage === 'task') loadTaskInfo();
            if (currentPage === 'drone') loadDroneStatus();
        }, CONFIG.pollInterval);
    }

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

    // ===== Toast提示 =====
    function showToast(message) {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.classList.add('show');
        setTimeout(() => toast.classList.remove('show'), 2500);
    }

    // ===== 补齐 HTML 调用的缺失函数 =====
    function selectDropPointFromMap() {
        showToast('🗺️ 请在地图上选择投放点');
        router('drop');
    }

    function toggleTheme() {
        const current = document.body.classList.contains('light-theme') ? 'light' : 'dark';
        const next = current === 'dark' ? 'light' : 'dark';
        document.body.classList.toggle('light-theme', next === 'light');
        const el = document.getElementById('theme-value');
        if (el) el.textContent = next === 'dark' ? '◉ 深色' : '◉ 浅色';
        showToast(next === 'dark' ? '🌙 已切换深色模式' : '☀️ 已切换浅色模式');
    }

    function showChangePasswordModal() {
        const newPwd = prompt('请输入新密码（至少6位）：');
        if (newPwd && newPwd.length >= 6) {
            showToast('✅ 密码修改成功（演示）');
        } else if (newPwd) {
            showToast('❌ 密码太短');
        }
    }

    // ===== 暴露接口 =====
    return {
        init,
        router,
        back,
        submitDemand,
        selectDropPoint,
        selectDropPointFromMap,
        confirmDropPoint,
        searchDropPoint,
        selectSearchResult,
        toggleTheme,
        showChangePasswordModal,
        updateDropPoint,
        addAnnotate,
        triggerSOS,
        refreshLocation,
        manualSetLocation,
        showToast,
        showServerConfig,
        toggleSwitch,
        doLogin,
        doRegister,
        fillLogin,
        logout,
        CONFIG
    };
})();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    App.init();
});
