/**
 * UI 交互模块
 * 负责: 按钮事件绑定、状态管理、航点列表渲染、日志输出
 */

const UIModule = (() => {
    // 应用状态
    let droneConnected = false;
    let missionUploaded = false;
    let missionRunning = false;
    let missionPaused = false;
    let connectionMode = 'sim';  // 'sim' 仿真 | 'real' 实机

    // 连接预设 (rosbridge WebSocket 地址)
    const PRESETS = {
        sim:  { url: 'ws://localhost:9090',             label: '仿真 rosbridge',  desc: 'Prometheus SITL 仿真 (本地 rosbridge 端口 9090)' },
        real: { url: 'ws://192.168.1.31:9090',          label: '实机 rosbridge',  desc: 'P600 实机 WiFi 数传 (rosbridge 192.168.1.31:9090)' }
    };

    function init() {
        // 初始化地图
        MapModule.init();

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

        // 绑定按钮事件
        document.getElementById('btn-connect').addEventListener('click', onConnect);
        document.getElementById('btn-upload').addEventListener('click', onUpload);
        document.getElementById('btn-start').addEventListener('click', onStart);
        document.getElementById('btn-pause').addEventListener('click', onPause);
        document.getElementById('btn-resume').addEventListener('click', onResume);
        document.getElementById('btn-rth').addEventListener('click', onReturnHome);
        document.getElementById('btn-land').addEventListener('click', onLand);
        document.getElementById('btn-clear').addEventListener('click', onClear);
        document.getElementById('btn-clear-log').addEventListener('click', onClearLog);

        // 绑定连接模式切换
        document.getElementById('btn-mode-sim').addEventListener('click', () => switchMode('sim'));
        document.getElementById('btn-mode-real').addEventListener('click', () => switchMode('real'));

        // 连接地址输入框变化时更新标签
        document.getElementById('drone-url').addEventListener('input', onUrlInput);

        updateButtons();
        addLog('info', '系统就绪，当前模式: 仿真 (rosbridge)');
        addLog('info', '提示: 浏览器通过 roslibjs 直接连接 rosbridge_server，无需 MAVSDK 后端');
    }

    // ---------- 连接模式切换 ----------

    function switchMode(mode) {
        if (droneConnected) {
            addLog('warning', '请先断开当前连接再切换模式');
            return;
        }
        connectionMode = mode;
        const preset = PRESETS[mode];

        // 更新按钮状态
        document.getElementById('btn-mode-sim').classList.toggle('active', mode === 'sim');
        document.getElementById('btn-mode-real').classList.toggle('active', mode === 'real');

        // 自动填入预设地址
        document.getElementById('drone-url').value = preset.url;
        document.getElementById('conn-mode-tag').textContent = preset.label;

        addLog('info', `已切换到${preset.label}模式: ${preset.desc}`);

        if (mode === 'sim') {
            addLog('info', '仿真模式说明: 先启动 Prometheus SITL (roslaunch prometheus_gazebo sitl.launch)，再启动 rosbridge (roslaunch rosbridge_server rosbridge_websocket.launch)');
        } else {
            addLog('info', '实机模式说明: 请确保电脑已连接 P600 的 WiFi 数传，rosbridge 需在机载电脑上运行');
        }
    }

    function onUrlInput() {
        const url = document.getElementById('drone-url').value.trim();
        const tag = document.getElementById('conn-mode-tag');
        if (url.startsWith('ws://')) {
            tag.textContent = 'rosbridge';
        } else if (url.startsWith('wss://')) {
            tag.textContent = 'rosbridge (SSL)';
        } else {
            tag.textContent = '未知';
        }
    }

    // ---------- 按钮事件处理 ----------

    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://localhost:9090)');
            return;
        }
        WsModule.connectDrone(url);
    }

    function onUpload() {
        const waypoints = MapModule.getWaypoints();
        if (waypoints.length === 0) {
            addLog('error', '请先在地图上添加航点');
            return;
        }
        WsModule.uploadMission(waypoints);
    }

    function onStart() {
        WsModule.startMission();
    }

    function onPause() {
        WsModule.pauseMission();
    }

    function onResume() {
        WsModule.resumeMission();
    }

    function onReturnHome() {
        WsModule.returnHome();
    }

    function onLand() {
        WsModule.land();
    }

    function onClear() {
        MapModule.clearWaypoints();
        missionUploaded = false;
        updateButtons();
        addLog('info', '已清除所有航点');
    }

    function onClearLog() {
        document.getElementById('log-content').innerHTML = '';
    }

    // ---------- 状态回调（由 WsModule 触发） ----------

    function onTelemetry(data) {
        if (data.type === 'telemetry') {
            // 更新顶栏数据
            document.getElementById('battery').textContent = data.battery.toFixed(0) + '%';
            document.getElementById('speed').textContent = data.speed.toFixed(1) + ' m/s';
            document.getElementById('altitude').textContent = data.alt.toFixed(1) + ' m';
            document.getElementById('gps-status').textContent = data.gps_status;
            document.getElementById('flight-mode').textContent = data.flight_mode;

            // 更新右侧数据面板
            document.getElementById('data-lat').textContent = data.lat.toFixed(6);
            document.getElementById('data-lng').textContent = data.lng.toFixed(6);
            document.getElementById('data-heading').textContent = data.heading.toFixed(0) + '°';
            document.getElementById('data-wp').textContent = data.current_wp;

            // 更新无人机位置 — 只要坐标有效就更新
            if (droneConnected && (data.lat !== 0 || data.alt > 0.1)) {
                MapModule.updateDronePosition(data.lat, data.lng, data.heading);
            }
        }

        if (data.type === 'mission_progress') {
            document.getElementById('data-wp').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-status').className = 'tag tag-success';
            document.getElementById('conn-status').textContent = '已连接';
            document.getElementById('btn-connect').textContent = '已连接';
            document.getElementById('btn-connect').disabled = true;
            updateButtons();
        }

        if (msg.includes('上传成功')) {
            missionUploaded = true;
            updateButtons();
        }

        if (msg.includes('任务已开始')) {
            missionRunning = true;
            missionPaused = false;
            updateButtons();
        }

        if (msg.includes('已暂停')) {
            missionRunning = false;
            missionPaused = true;
            updateButtons();
        }

        if (msg.includes('已继续')) {
            missionRunning = true;
            missionPaused = false;
            updateButtons();
        }

        if (msg.includes('返航') || msg.includes('降落') || msg.includes('失败')) {
            if (msg.includes('返航') || msg.includes('降落')) {
                missionRunning = false;
                missionPaused = false;
                updateButtons();
            }
        }

        if (msg.includes('任务完成')) {
            missionRunning = false;
            missionPaused = false;
            missionUploaded = false;
            updateButtons();
        }
    }

    function onDroneDisconnected() {
        droneConnected = false;
        missionUploaded = false;
        missionRunning = false;
        missionPaused = false;
        document.getElementById('conn-status').className = 'tag tag-danger';
        document.getElementById('conn-status').textContent = '未连接';
        document.getElementById('btn-connect').textContent = '连接无人机';
        document.getElementById('btn-connect').disabled = false;
        updateButtons();
        addLog('error', '无人机连接断开');
    }

    // ---------- 按钮状态管理 ----------

    function updateButtons() {
        const wpCount = MapModule.getWaypointCount();

        setBtn('btn-upload', droneConnected && wpCount > 0 && !missionRunning && !missionPaused);
        setBtn('btn-start', droneConnected && missionUploaded && !missionRunning && !missionPaused);
        setBtn('btn-pause', droneConnected && missionRunning);
        setBtn('btn-resume', droneConnected && missionPaused);
        setBtn('btn-rth', droneConnected);
        setBtn('btn-land', droneConnected);
    }

    function setBtn(id, enabled) {
        document.getElementById(id).disabled = !enabled;
    }

    // ---------- 航点列表渲染 ----------

    function updateWaypointList() {
        const container = document.getElementById('waypoint-list');
        const waypoints = MapModule.getWaypoints();

        document.getElementById('wp-count').textContent = waypoints.length + ' 个航点';

        if (waypoints.length === 0) {
            container.innerHTML = '<div class="empty-hint">在地图上点击以添加航点</div>';
            return;
        }

        container.innerHTML = waypoints.map((wp, i) => `
            <div class="wp-item" data-index="${i}">
                <span class="wp-index">${i + 1}</span>
                <div class="wp-info">
                    <div class="wp-coord">${wp.lat}, ${wp.lng}</div>
                    <div class="wp-alt">${wp.alt}m | 悬停 ${wp.hold_time}s</div>
                </div>
                <button class="wp-delete" data-index="${i}" title="删除">&times;</button>
            </div>
        `).join('');

        // 绑定点击定位事件
        container.querySelectorAll('.wp-item').forEach(item => {
            item.addEventListener('click', (e) => {
                if (e.target.classList.contains('wp-delete')) return;
                const idx = parseInt(item.dataset.index);
                const wps = MapModule.getWaypoints();
                if (wps[idx]) {
                    MapModule.panTo(wps[idx].lat, wps[idx].lng);
                }
            });
        });

        // 绑定删除事件
        container.querySelectorAll('.wp-delete').forEach(btn => {
            btn.addEventListener('click', () => {
                MapModule.removeWaypoint(parseInt(btn.dataset.index));
            });
        });
    }

    // ---------- 日志输出 ----------

    function addLog(type, message) {
        const container = document.getElementById('log-content');
        const now = new Date();
        const time = now.toTimeString().split(' ')[0];

        const entry = document.createElement('div');
        entry.className = 'log-entry ' + type;
        entry.innerHTML = `<span class="time">[${time}]</span>${message}`;
        container.appendChild(entry);

        // 自动滚动到底部
        container.scrollTop = container.scrollHeight;

        // 限制日志条数
        while (container.children.length > 200) {
            container.removeChild(container.firstChild);
        }
    }

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

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