/**
 * 地图模块 - 基于 Leaflet.js
 * 负责: 地图初始化、航点管理、航线绘制、无人机位置显示
 */

const MapModule = (() => {
    let map = null;
    let waypoints = [];       // 航点数据数组
    let markers = [];         // 航点 Leaflet Marker 对象
    let polyline = null;      // 航线折线
    let droneMarker = null;   // 无人机位置标记
    let trailLine = null;     // 飞行轨迹
    let trailCoords = [];     // 轨迹坐标历史
    let soldierMarkers = {};  // { soldierId: L.marker }
    let soldierLayerGroup = null;
    let dangerZoneItems = []; // [ { circle, marker } ]
    let dangerLayerGroup = null;

    const DEFAULT_LAT = 30.0;
    const DEFAULT_LNG = 120.0;
    const DEFAULT_ZOOM = 16;

    function init() {
        map = L.map('map', {
            center: [DEFAULT_LAT, DEFAULT_LNG],
            zoom: DEFAULT_ZOOM,
            zoomControl: true
        });

        // OpenStreetMap 底图（免费，无需 Key）
        L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap',
            maxZoom: 19
        }).addTo(map);

        // 点击地图添加航点
        map.on('click', onMapClick);

        // 初始化航线（空折线）
        polyline = L.polyline([], {
            color: '#007aff',
            weight: 2,
            opacity: 0.7,
            dashArray: '8, 6'
        }).addTo(map);

        // 初始化飞行轨迹
        trailLine = L.polyline([], {
            color: '#ff4d4f',
            weight: 2,
            opacity: 0.6
        }).addTo(map);

        // 创建无人机图标
        const droneIcon = L.divIcon({
            className: 'drone-icon',
            html: '<div class="drone-icon-inner" id="drone-arrow"></div>',
            iconSize: [24, 24],
            iconAnchor: [12, 12]
        });

        droneMarker = L.marker([DEFAULT_LAT, DEFAULT_LNG], {
            icon: droneIcon,
            visible: false
        }).addTo(map);

        // 士兵位置图层
        soldierLayerGroup = L.layerGroup().addTo(map);
        // 危险区域图层
        dangerLayerGroup = L.layerGroup().addTo(map);

        // 图层切换控件
        L.control.layers(null, {
            "士兵位置": soldierLayerGroup,
            "危险区域": dangerLayerGroup
        }, { collapsed: false }).addTo(map);
    }

    function onMapClick(e) {
        addWaypoint(e.latlng.lat, e.latlng.lng);
    }

    function addWaypoint(lat, lng) {
        const defaultAlt = parseInt(document.getElementById('default-alt').value) || 15;
        const defaultHold = parseInt(document.getElementById('default-hold').value) || 0;
        const index = waypoints.length + 1;

        const wp = {
            id: Date.now(),
            lat: parseFloat(lat.toFixed(6)),
            lng: parseFloat(lng.toFixed(6)),
            alt: defaultAlt,
            hold_time: defaultHold
        };
        waypoints.push(wp);

        // 添加地图标记
        const marker = L.marker([wp.lat, wp.lng], {
            draggable: true
        }).addTo(map);

        marker.bindPopup(`<b>航点 ${index}</b><br>高度: ${wp.alt}m<br>悬停: ${wp.hold_time}s`);

        // 拖拽更新航点坐标
        marker.on('dragend', function () {
            const pos = marker.getLatLng();
            const wpIdx = markers.indexOf(marker);
            if (wpIdx >= 0) {
                waypoints[wpIdx].lat = parseFloat(pos.lat.toFixed(6));
                waypoints[wpIdx].lng = parseFloat(pos.lng.toFixed(6));
                marker.setPopupContent(`<b>航点 ${wpIdx + 1}</b><br>高度: ${waypoints[wpIdx].alt}m`);
                updatePolyline();
                UIModule.updateWaypointList();
            }
        });

        markers.push(marker);
        updatePolyline();
        UIModule.updateWaypointList();
        UIModule.updateButtons();
    }

    function removeWaypoint(index) {
        if (index < 0 || index >= waypoints.length) return;

        waypoints.splice(index, 1);
        const marker = markers.splice(index, 1)[0];
        map.removeLayer(marker);

        // 重新编号弹窗
        markers.forEach((m, i) => {
            m.setPopupContent(`<b>航点 ${i + 1}</b><br>高度: ${waypoints[i].alt}m`);
        });

        updatePolyline();
        UIModule.updateWaypointList();
        UIModule.updateButtons();
    }

    function clearWaypoints() {
        markers.forEach(m => map.removeLayer(m));
        waypoints = [];
        markers = [];
        updatePolyline();
        UIModule.updateWaypointList();
        UIModule.updateButtons();
    }

    function updatePolyline() {
        const coords = waypoints.map(wp => [wp.lat, wp.lng]);
        polyline.setLatLngs(coords);
    }

    function updateDronePosition(lat, lng, heading) {
        if (!droneMarker) return;
        droneMarker.setLatLng([lat, lng]);
        if (!droneMarker.visible) {
            droneMarker.visible = true;
        }

        // 旋转无人机图标（航向）
        const arrow = document.getElementById('drone-arrow');
        if (arrow) {
            arrow.style.transform = `rotate(${heading}deg)`;
        }

        // 记录轨迹
        trailCoords.push([lat, lng]);
        if (trailCoords.length > 500) trailCoords.shift();
        trailLine.setLatLngs(trailCoords);
    }

    function centerOnDrone(lat, lng) {
        map.setView([lat, lng], map.getZoom());
    }

    function panTo(lat, lng) {
        map.panTo([lat, lng]);
    }

    function getWaypoints() {
        return waypoints.map(wp => ({
            lat: wp.lat,
            lng: wp.lng,
            alt: wp.alt,
            hold_time: wp.hold_time
        }));
    }

    function getWaypointCount() {
        return waypoints.length;
    }

    function updateWaypointAlt(index, alt) {
        if (index >= 0 && index < waypoints.length) {
            waypoints[index].alt = alt;
            markers[index].setPopupContent(
                `<b>航点 ${index + 1}</b><br>高度: ${alt}m<br>悬停: ${waypoints[index].hold_time}s`
            );
        }
    }

    // ---- 士兵标记 ----

    function updateSoldierMarker(id, name, lat, lng) {
        if (soldierMarkers[id]) {
            soldierMarkers[id].setLatLng([lat, lng]);
            return;
        }
        const icon = L.divIcon({
            className: 'soldier-marker',
            html: '<div class="soldier-marker-dot"></div><div class="soldier-marker-name">' + name + '</div>',
            iconSize: [40, 40],
            iconAnchor: [20, 20]
        });
        const marker = L.marker([lat, lng], { icon: icon })
            .bindPopup('<b>' + name + '</b><br>(' + lat.toFixed(4) + ', ' + lng.toFixed(4) + ')')
            .addTo(soldierLayerGroup);
        soldierMarkers[id] = marker;
    }

    function removeSoldierMarker(id) {
        if (soldierMarkers[id]) {
            soldierLayerGroup.removeLayer(soldierMarkers[id]);
            delete soldierMarkers[id];
        }
    }

    function clearAllSoldiers() {
        soldierLayerGroup.clearLayers();
        soldierMarkers = {};
    }

    // ---- 危险区域 ----

    function addDangerZone(lat, lng, radius, description) {
        const circle = L.circle([lat, lng], {
            radius: radius,
            color: '#ff4d4f',
            fillColor: '#ff4d4f',
            fillOpacity: 0.15,
            weight: 2,
            dashArray: '5, 5'
        }).addTo(dangerLayerGroup);

        const icon = L.divIcon({
            className: 'danger-zone-marker',
            html: '<div class="danger-zone-icon">&#9888;</div>',
            iconSize: [24, 24],
            iconAnchor: [12, 12]
        });
        const marker = L.marker([lat, lng], { icon: icon })
            .bindPopup('<b style="color:#ff4d4f">' + (description || '危险区域') + '</b><br>(' + lat.toFixed(4) + ', ' + lng.toFixed(4) + ')<br>半径: ' + radius + 'm')
            .addTo(dangerLayerGroup);

        dangerZoneItems.push({ circle, marker });
    }

    function clearAllDangerZones() {
        dangerLayerGroup.clearLayers();
        dangerZoneItems = [];
    }

    return {
        init,
        addWaypoint,
        removeWaypoint,
        clearWaypoints,
        updateDronePosition,
        centerOnDrone,
        panTo,
        getWaypoints,
        getWaypointCount,
        updateWaypointAlt,
        updateSoldierMarker,
        removeSoldierMarker,
        clearAllSoldiers,
        addDangerZone,
        clearAllDangerZones,
        DEFAULT_LAT,
        DEFAULT_LNG
    };
})();
