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

const App = (() => {
    // ===== 配置 =====
    const CONFIG = {
        apiBase: localStorage.getItem('api_base') || 'http://192.168.1.14:5000',
        soldierId: localStorage.getItem('soldier_id') || 'soldier_001',
        soldierName: localStorage.getItem('soldier_name') || '张三',
        soldierUnit: localStorage.getItem('soldier_unit') || '第3步兵师/1连',
        pollInterval: 5000
    };

    // ===== 状态 =====
    let currentPage = 'home';
    let pageStack = ['home'];
    let selectedDropPoint = null;
    let pollTimer = null;

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

    // ===== 初始化 =====
    function init() {
        // 绑定单选按钮
        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] || '个';
            });
        }

        // 启动轮询
        startPolling();

        // 更新士兵信息
        updateSoldierInfo();

        showToast('单兵终端已就绪');
    }

    // ===== 路由切换 =====
    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':
                loadDropPoints();
                break;
            case 'task':
                loadTaskInfo();
                break;
            case 'drone':
                loadDroneStatus();
                break;
            case 'location':
                refreshLocation();
                break;
        }
    }

    // ===== 更新士兵信息 =====
    function updateSoldierInfo() {
        document.getElementById('user-name').textContent = CONFIG.soldierName;
        document.getElementById('user-unit').textContent = '所属：' + CONFIG.soldierUnit;
        document.getElementById('profile-name').textContent = '前线士兵：' + CONFIG.soldierName;
        document.getElementById('profile-unit').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.BASE = url;
            updateSoldierInfo();
            showToast('服务器地址已更新');
        }
    }

    // ===== 更新首页位置 =====
    function updateHomeLocation() {
        const loc = LocationModule.getLastPosition();
        if (loc) {
            document.getElementById('home-loc').textContent = `${loc.lat.toFixed(4)}, ${loc.lng.toFixed(4)}`;
        }
    }

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

        if (!qty || qty < 1) {
            showToast('请输入有效数量');
            return;
        }

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

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

    // ===== 加载投放点 =====
    async function loadDropPoints() {
        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'}">
                        <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>
                        <button class="${isSafe ? 'select-btn' : 'avoid-btn'}" onclick="App.selectDropPoint(${i})">
                            ${isSafe ? '✅ 选择此点' : '❌ 避开此点'}
                        </button>
                    </div>
                `;
            }).join('');
        } catch (e) {
            list.innerHTML = '<div style="text-align:center;color:#999;padding:20px;">加载失败</div>';
        }
    }

    // ===== 选择投放点 =====
    function selectDropPoint(index) {
        API.getDropPoints().then(points => {
            const p = points[index];
            if (p.safety_score < 70) {
                showToast('已标记避开此点');
                return;
            }
            selectedDropPoint = p;
            showToast('已选择：' + p.name);
            router('demand');
            document.getElementById('demand-drop-display').textContent = p.name + '（安全系数' + p.safety_score + '%）';
        });
    }

    function confirmDropPoint() {
        if (!selectedDropPoint) {
            showToast('请先选择一个投放点');
            return;
        }
        router('demand');
    }

    // ===== 加载任务信息 =====
    async function loadTaskInfo() {
        try {
            const task = await API.getCurrentTask(CONFIG.soldierId);
            if (task) {
                document.getElementById('task-id').textContent = task.id || '#--';
                document.getElementById('task-status').textContent = task.status === '执行中' ? '🟢 执行中' : task.status;
                document.getElementById('task-eta').textContent = '预计到达：' + (task.eta || '--');
                document.getElementById('task-progress-text').textContent = '━━━━━━━━━━━━━━━━━━ ' + (task.progress || 0) + '%';
                document.getElementById('task-remain').textContent = '剩余时间：' + (task.remain_time || '--');
                document.getElementById('task-start').textContent = task.start_name || '后方阵地';
                document.getElementById('task-target').textContent = task.target_name || '目标位置';
                document.getElementById('task-risk').textContent = '安全系数: ' + (task.safety_score || '--') + '%';
            }
        } catch (e) {
            console.log('任务加载失败', e);
        }
    }

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

            const logs = await API.getDroneLogs();
            const logContainer = document.getElementById('drone-logs');
            if (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);
        }
    }

    // ===== 刷新位置 =====
    async function refreshLocation() {
        document.getElementById('loc-current').textContent = '定位中...';
        try {
            const pos = await LocationModule.getCurrentPosition();
            document.getElementById('loc-current').textContent = `${pos.lat.toFixed(6)}, ${pos.lng.toFixed(6)}`;
            document.getElementById('loc-offset').textContent = '计算中...';
            // 模拟偏移计算
            setTimeout(() => {
                document.getElementById('loc-offset').textContent = Math.floor(Math.random() * 100) + 'm';
                document.getElementById('loc-offset-time').textContent = '刚刚';
            }, 500);
        } catch (e) {
            document.getElementById('loc-current').textContent = '定位失败';
        }
    }

    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 || '网络错误'));
        }
    }

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

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

    // ===== 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);
        }
    }

    // ===== 暴露接口 =====
    return {
        init,
        router,
        back,
        submitDemand,
        selectDropPoint,
        confirmDropPoint,
        updateDropPoint,
        addAnnotate,
        triggerSOS,
        refreshLocation,
        showToast,
        showServerConfig,
        toggleSwitch,
        CONFIG
    };
})();

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