/**
 * 地图模块 - 支持多种地图源
 * 默认: OpenStreetMap (免费无需API Key)
 * 可选: 高德地图
 */

// 全局变量
let map = null;
let currentLayer = null;
let markers = [];
let userMarker = null;
let currentMapSource = 'amap';
let currentLocationData = null;

// 默认中心点（阳泉市中心）
const DEFAULT_CENTER = [37.857, 113.581];
const DEFAULT_ZOOM = 13;

// 地图图层配置
const mapLayers = {
    osm: {
        name: 'OpenStreetMap',
        url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19
    },
    // 高德地图瓦片
    amap: {
        name: '高德地图',
        url: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
        attribution: '&copy; 高德地图',
        subdomains: ['1', '2', '3', '4'],
        maxZoom: 18
    },
    // 高德地图卫星图
    amapSatellite: {
        name: '高德卫星',
        url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        attribution: '&copy; 高德地图',
        subdomains: ['1', '2', '3', '4'],
        maxZoom: 18
    },
    // Esri World Street Map（免费稳定）
    esri: {
        name: 'Esri地图',
        url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
        attribution: 'Tiles &copy; Esri',
        maxZoom: 18
    },
    // GeoQ地图（国内免费地图）
    geoq: {
        name: 'GeoQ地图',
        url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}',
        attribution: '&copy; GeoQ',
        maxZoom: 18
    }
};

/**
 * 初始化地图
 */
function initMap() {
    // 创建地图实例
    if (typeof L === 'undefined') {
        console.error('Leaflet地图库未加载');
        return;
    }
    map = L.map('map', {
        center: DEFAULT_CENTER,
        zoom: DEFAULT_ZOOM,
        zoomControl: false // 禁用默认缩放控件，使用自定义工具栏
    });

    // 添加默认图层（使用currentMapSource设置的默认地图源）
    switchMapLayer(currentMapSource);

    // 添加地图事件监听
    map.on('click', onMapClick);
    map.on('moveend', updateMapInfo);
    map.on('zoomend', updateMapInfo);

    // 初始化控件
    initControls();

    // 初始化预设地点点击事件
    initPresetLocations();

    // 更新地图信息
    updateMapInfo();

    // 尝试获取用户位置
    // locateUser();
}

/**
 * 切换地图图层
 */
function switchMapLayer(source) {
    if (currentLayer) {
        map.removeLayer(currentLayer);
    }

    const layerConfig = mapLayers[source];
    
    currentLayer = L.tileLayer(layerConfig.url, {
        attribution: layerConfig.attribution,
        maxZoom: layerConfig.maxZoom,
        subdomains: layerConfig.subdomains || 'abc'
    });

    currentLayer.addTo(map);
    currentMapSource = source;

    // 显示提示
    if (source === 'amap' && !AMAP_KEY) {
        showToast('高德地图瓦片加载中，部分功能可能受限', 'info');
    }
}

/**
 * 初始化控件事件
 */
function initControls() {
    // 地图源切换
    document.querySelectorAll('input[name="mapSource"]').forEach(radio => {
        radio.addEventListener('change', function() {
            switchMapLayer(this.value);
        });
    });

    // 搜索
    const searchInput = document.getElementById('mapSearchInput');
    const searchBtn = document.getElementById('mapSearchBtn');
    
    if (searchBtn && searchInput) {
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }

    // 定位按钮
    const locateBtn = document.getElementById('locateBtn');
    if (locateBtn) locateBtn.addEventListener('click', locateUser);

    // 工具栏按钮
    const zoomInBtn = document.getElementById('zoomInBtn');
    const zoomOutBtn = document.getElementById('zoomOutBtn');
    const resetViewBtn = document.getElementById('resetViewBtn');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    if (zoomInBtn) zoomInBtn.addEventListener('click', () => map.zoomIn());
    if (zoomOutBtn) zoomOutBtn.addEventListener('click', () => map.zoomOut());
    if (resetViewBtn) resetViewBtn.addEventListener('click', resetView);
    if (fullscreenBtn) fullscreenBtn.addEventListener('click', toggleFullscreen);

    // 清除标记按钮
    const clearMarkersBtn = document.getElementById('clearMarkersBtn');
    if (clearMarkersBtn) clearMarkersBtn.addEventListener('click', clearAllMarkers);

    // 弹窗关闭
    document.querySelectorAll('.modal-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal').classList.remove('active');
        });
    });

    // 点击弹窗外部关闭
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.remove('active');
            }
        });
    });

    // 导航按钮
    const navigateBtn = document.getElementById('navigateBtn');
    const saveMarkerBtn = document.getElementById('saveMarkerBtn');
    const shareLocationBtn = document.getElementById('shareLocationBtn');
    if (navigateBtn) navigateBtn.addEventListener('click', showNavigateOptions);
    if (saveMarkerBtn) saveMarkerBtn.addEventListener('click', saveCurrentMarker);
    if (shareLocationBtn) shareLocationBtn.addEventListener('click', shareLocation);
}

/**
 * 初始化预设地点点击事件
 */
function initPresetLocations() {
    document.querySelectorAll('.preset-item').forEach(item => {
        item.addEventListener('click', function() {
            const lat = parseFloat(this.dataset.lat);
            const lng = parseFloat(this.dataset.lng);
            const name = this.dataset.name;

            map.setView([lat, lng], 15);
            
            // 添加标记
            const marker = addMarker(lat, lng, name);
            
            // 打开弹窗
            marker.fire('click');
        });
    });
}

/**
 * 地图点击事件
 */
function onMapClick(e) {
    const { lat, lng } = e.latlng;
    
    // 逆地理编码获取地址
    reverseGeocode(lat, lng);
}

/**
 * 添加标记点
 */
function addMarker(lat, lng, title, address = '') {
    // 创建自定义图标
    const customIcon = L.divIcon({
        className: 'custom-marker',
        html: `<div class="marker-pin"><i class="fas fa-map-marker-alt"></i></div>`,
        iconSize: [30, 42],
        iconAnchor: [15, 42],
        popupAnchor: [0, -42]
    });

    const marker = L.marker([lat, lng], { icon: customIcon }).addTo(map);
    
    // 存储标记信息
    marker._locationData = { lat, lng, title, address };
    markers.push(marker);

    // 使用数据属性存储信息，避免字符串转义问题
    const popupContent = `
        <div class="map-popup">
            <h4>${escapeHtml(title)}</h4>
            ${address ? `<p>${escapeHtml(address)}</p>` : ''}
            <p>坐标: ${lat.toFixed(6)}, ${lng.toFixed(6)}</p>
            <button class="popup-btn">查看详情</button>
        </div>
    `;
    marker.bindPopup(popupContent);

    // 为弹窗按钮添加点击事件（使用一次性事件避免重复绑定）
    marker.on('popupopen', function() {
        const popupEl = document.querySelector('.leaflet-popup-content');
        if (popupEl) {
            const popupBtn = popupEl.querySelector('.popup-btn');
            if (popupBtn && !popupBtn._hasClickListener) {
                popupBtn._hasClickListener = true;
                popupBtn.addEventListener('click', function() {
                    const data = marker._locationData;
                    showLocationDetail(data.lat, data.lng, data.title, data.address);
                });
            }
        }
    });

    // 更新标记列表
    updateMarkerList();

    return marker;
}

/**
 * HTML转义函数，防止XSS和字符串转义问题
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * 更新标记列表
 */
function updateMarkerList() {
    const listContainer = document.getElementById('markerList');
    const clearBtn = document.getElementById('clearMarkersBtn');

    if (markers.length === 0) {
        listContainer.innerHTML = '<p class="empty-tip">点击地图添加标记点</p>';
        clearBtn.style.display = 'none';
        return;
    }

    clearBtn.style.display = 'block';
    
    let html = '';
    markers.forEach((marker, index) => {
        const data = marker._locationData;
        const safeTitle = escapeHtml(data.title);
        html += `
            <div class="marker-item" data-index="${index}">
                <span class="marker-name">${safeTitle}</span>
                <span class="delete-marker" data-delete="${index}">
                    <i class="fas fa-times"></i>
                </span>
            </div>
        `;
    });
    
    listContainer.innerHTML = html;

    // 为标记名称添加点击事件
    listContainer.querySelectorAll('.marker-name').forEach(item => {
        item.addEventListener('click', function() {
            const index = parseInt(this.closest('.marker-item').dataset.index);
            goToMarker(index);
        });
    });

    // 为删除按钮添加点击事件
    listContainer.querySelectorAll('.delete-marker').forEach(item => {
        item.addEventListener('click', function() {
            const index = parseInt(this.dataset.delete);
            deleteMarker(index);
        });
    });
}

/**
 * 跳转到标记
 */
function goToMarker(index) {
    const marker = markers[index];
    if (marker) {
        const data = marker._locationData;
        map.setView([data.lat, data.lng], 16);
        marker.openPopup();
    }
}

/**
 * 删除标记
 */
function deleteMarker(index) {
    const marker = markers[index];
    if (marker) {
        map.removeLayer(marker);
        markers.splice(index, 1);
        updateMarkerList();
    }
}

/**
 * 清除所有标记
 */
function clearAllMarkers() {
    markers.forEach(marker => map.removeLayer(marker));
    markers = [];
    updateMarkerList();
    showToast('已清除所有标记', 'success');
}

/**
 * 执行搜索
 */
async function performSearch() {
    const query = document.getElementById('mapSearchInput').value.trim();
    if (!query) {
        showToast('请输入搜索内容', 'warning');
        return;
    }

    const resultsContainer = document.getElementById('searchResults');
    resultsContainer.innerHTML = '<p style="text-align:center;padding:20px;color:#888;"><i class="fas fa-spinner fa-spin"></i> 搜索中...</p>';

    try {
        let data = null;
        
        // 优先使用高德地图API（如果有Key）
        if (AMAP_KEY) {
            // 先尝试地理编码搜索
            data = await searchWithAmap(query);
            
            // 如果地理编码没找到，尝试POI搜索
            if (!data || data.length === 0) {
                data = await searchWithAmapPOI(query);
            }
        }
        
        // 如果高德地图不可用或没有Key，使用OpenStreetMap
        if (!data || data.length === 0) {
            data = await searchWithOsm(query);
        }

        if (!data || data.length === 0) {
            resultsContainer.innerHTML = '<p style="text-align:center;padding:20px;color:#888;">未找到相关地点</p>';
            return;
        }

        let html = '';
        data.forEach(item => {
            const displayName = escapeHtml(item.display_name);
            const shortName = escapeHtml(item.short_name || item.display_name.split(',')[0]);
            html += `
                <div class="search-result-item" data-lat="${item.lat}" data-lng="${item.lon}" data-name="${displayName}">
                    <div class="name">${shortName}</div>
                    <div class="address">${displayName}</div>
                </div>
            `;
        });
        resultsContainer.innerHTML = html;

        // 为每个搜索结果添加点击事件
        resultsContainer.querySelectorAll('.search-result-item').forEach(item => {
            item.addEventListener('click', function() {
                selectSearchResult(
                    parseFloat(this.dataset.lat),
                    parseFloat(this.dataset.lng),
                    this.dataset.name
                );
            });
        });

    } catch (error) {
        console.error('搜索失败:', error);
        resultsContainer.innerHTML = '<p style="text-align:center;padding:20px;color:#dc3545;">搜索失败，请稍后重试</p>';
    }
}

/**
 * 使用高德地图API搜索
 */
async function searchWithAmap(query) {
    if (!AMAP_KEY) return null;
    
    try {
        // 不限制城市，扩大搜索范围
        const response = await fetch(`https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(query)}&key=${AMAP_KEY}`);
        const result = await response.json();
        
        if (result.status === '1' && result.geocodes && result.geocodes.length > 0) {
            return result.geocodes.map(item => ({
                lat: parseFloat(item.location.split(',')[1]),
                lon: parseFloat(item.location.split(',')[0]),
                display_name: item.formatted_address,
                short_name: item.address_component.district + (item.address_component.street || '') + (item.address_component.streetNumber || '')
            }));
        }
    } catch (error) {
        console.error('高德地图搜索失败:', error);
    }
    return null;
}

/**
 * 使用高德地图POI搜索
 */
async function searchWithAmapPOI(query) {
    if (!AMAP_KEY) return null;
    
    try {
        const response = await fetch(`https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(query)}&key=${AMAP_KEY}&city=0353&types=&offset=10&page=1&extensions=all`);
        const result = await response.json();
        
        if (result.status === '1' && result.pois && result.pois.length > 0) {
            return result.pois.map(item => ({
                lat: parseFloat(item.location.split(',')[1]),
                lon: parseFloat(item.location.split(',')[0]),
                display_name: item.address + item.name,
                short_name: item.name
            }));
        }
    } catch (error) {
        console.error('高德地图POI搜索失败:', error);
    }
    return null;
}

/**
 * 使用OpenStreetMap搜索
 */
async function searchWithOsm(query) {
    try {
        const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5&accept-language=zh`);
        return await response.json();
    } catch (error) {
        console.error('OpenStreetMap搜索失败:', error);
        return null;
    }
}

/**
 * 选择搜索结果
 */
function selectSearchResult(lat, lng, name) {
    map.setView([lat, lng], 15);
    
    // 提取简短名称
    const shortName = name.split(',')[0];
    const marker = addMarker(parseFloat(lat), parseFloat(lng), shortName, name);
    
    // 清空搜索结果
    document.getElementById('searchResults').innerHTML = '';
    document.getElementById('mapSearchInput').value = '';
    
    marker.openPopup();
}

/**
 * 逆地理编码（坐标转地址）
 */
async function reverseGeocode(lat, lng) {
    let address = null;
    let name = null;

    // 优先使用高德地图API（如果有Key）
    if (AMAP_KEY) {
        const result = await reverseGeocodeWithAmap(lat, lng);
        if (result) {
            address = result.address;
            name = result.name;
        }
    }

    // 如果高德地图不可用或没有Key，使用OpenStreetMap
    if (!address) {
        const result = await reverseGeocodeWithOsm(lat, lng);
        if (result) {
            address = result.address;
            name = result.name;
        }
    }

    // 添加标记
    const marker = addMarker(lat, lng, name || '标记点', address || `${lat.toFixed(6)}, ${lng.toFixed(6)}`);
    marker.openPopup();
}

/**
 * 使用高德地图API逆地理编码
 */
async function reverseGeocodeWithAmap(lat, lng) {
    if (!AMAP_KEY) return null;
    
    try {
        const response = await fetch(`https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${AMAP_KEY}`);
        const result = await response.json();
        
        if (result.status === '1' && result.regeocode) {
            return {
                address: result.regeocode.formatted_address,
                name: result.regeocode.addressComponent.district + result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber
            };
        }
    } catch (error) {
        console.error('高德地图逆地理编码失败:', error);
    }
    return null;
}

/**
 * 使用OpenStreetMap逆地理编码
 */
async function reverseGeocodeWithOsm(lat, lng) {
    try {
        const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=zh`);
        const data = await response.json();
        
        if (data && data.display_name) {
            return {
                address: data.display_name,
                name: data.display_name.split(',')[0]
            };
        }
    } catch (error) {
        console.error('OpenStreetMap逆地理编码失败:', error);
    }
    return null;
}

/**
 * 定位用户位置
 */
function locateUser() {
    const locationInfo = document.getElementById('currentLocation');
    locationInfo.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 正在定位...';

    if (!navigator.geolocation) {
        locationInfo.innerHTML = '<span style="color:#dc3545;">您的浏览器不支持定位功能</span>';
        return;
    }

    navigator.geolocation.getCurrentPosition(
        (position) => {
            const { latitude, longitude, accuracy } = position.coords;
            
            // 移除之前的用户标记
            if (userMarker) {
                map.removeLayer(userMarker);
            }

            // 添加用户位置标记
            const userIcon = L.divIcon({
                className: 'user-marker',
                html: `<div class="user-pin"><i class="fas fa-user"></i></div>`,
                iconSize: [30, 30],
                iconAnchor: [15, 15]
            });

            userMarker = L.marker([latitude, longitude], { icon: userIcon }).addTo(map);
            userMarker.bindPopup('<div class="map-popup"><h4>我的位置</h4><p>精度: ' + Math.round(accuracy) + '米</p></div>');

            // 移动到用户位置
            map.setView([latitude, longitude], 16);

            locationInfo.innerHTML = `
                <strong>当前位置:</strong><br>
                纬度: ${latitude.toFixed(6)}<br>
                经度: ${longitude.toFixed(6)}<br>
                精度: ${Math.round(accuracy)}米
            `;

            // 存储当前位置
            currentLocationData = { lat: latitude, lng: longitude };

        },
        (error) => {
            let errorMsg = '定位失败';
            let detailMsg = '';
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errorMsg = '<strong style="color:#dc3545;">定位权限被拒绝</strong>';
                    detailMsg = '<p style="font-size:12px;color:#666;margin-top:8px;">请按以下步骤开启定位权限：<br>1. 点击浏览器地址栏左侧的🔒图标<br>2. 在"位置"选项中选择"允许"<br>3. 刷新页面后重新定位</p>';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMsg = '<strong style="color:#dc3545;">无法获取位置信息</strong>';
                    detailMsg = '<p style="font-size:12px;color:#666;margin-top:8px;">建议检查网络连接或尝试手动搜索位置</p>';
                    break;
                case error.TIMEOUT:
                    errorMsg = '<strong style="color:#dc3545;">定位超时</strong>';
                    detailMsg = '<p style="font-size:12px;color:#666;margin-top:8px;">请点击"定位当前位置"按钮重试</p>';
                    break;
            }
            locationInfo.innerHTML = `${errorMsg}${detailMsg}`;
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
}

/**
 * 显示地点详情弹窗
 */
function showLocationDetail(lat, lng, name, address) {
    currentLocationData = { lat, lng, name, address };
    
    document.getElementById('modalTitle').textContent = '地点详情';
    document.getElementById('modalName').textContent = name;
    document.getElementById('modalAddress').textContent = address || '暂无详细地址';
    document.getElementById('modalCoords').textContent = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    
    document.getElementById('locationModal').classList.add('active');
}

/**
 * 显示导航选项
 */
function showNavigateOptions() {
    if (!currentLocationData) {
        showToast('请先选择一个地点', 'warning');
        return;
    }

    const { lat, lng, name } = currentLocationData;
    const encodedName = encodeURIComponent(name);

    // 设置各导航应用的链接
    document.getElementById('navAmap').href = `https://uri.amap.com/marker?position=${lng},${lat}&name=${encodedName}&coordinate=wgs84`;
    document.getElementById('navBaidu').href = `https://api.map.baidu.com/marker?location=${lat},${lng}&title=${encodedName}&output=html`;
    document.getElementById('navTencent').href = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${lat},${lng};title:${encodedName}`;
    document.getElementById('navApple').href = `https://maps.apple.com/?q=${encodedName}&ll=${lat},${lng}`;

    document.getElementById('navigateModal').classList.add('active');
}

/**
 * 保存当前标记
 */
function saveCurrentMarker() {
    if (!currentLocationData) {
        showToast('没有可保存的地点', 'warning');
        return;
    }

    // 保存到本地存储
    const savedMarkers = JSON.parse(localStorage.getItem('savedMapMarkers') || '[]');
    
    // 检查是否已存在
    const exists = savedMarkers.some(m => 
        m.lat === currentLocationData.lat && m.lng === currentLocationData.lng
    );

    if (exists) {
        showToast('该地点已保存', 'info');
        return;
    }

    savedMarkers.push({
        ...currentLocationData,
        savedAt: new Date().toISOString()
    });

    localStorage.setItem('savedMapMarkers', JSON.stringify(savedMarkers));
    showToast('地点已保存', 'success');
    
    document.getElementById('locationModal').classList.remove('active');
}

/**
 * 分享位置
 */
function shareLocation() {
    if (!currentLocationData) {
        showToast('没有可分享的地点', 'warning');
        return;
    }

    const { lat, lng, name } = currentLocationData;
    const shareText = `${name}\n坐标: ${lat.toFixed(6)}, ${lng.toFixed(6)}\nhttps://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=15/${lat}/${lng}`;

    if (navigator.share) {
        navigator.share({
            title: name,
            text: shareText,
            url: `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=15/${lat}/${lng}`
        }).catch(err => console.log('分享取消'));
    } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(shareText).then(() => {
            showToast('位置信息已复制到剪贴板', 'success');
        }).catch(() => {
            showToast('复制失败，请手动复制', 'error');
        });
    }
}

/**
 * 重置视图
 */
function resetView() {
    map.setView(DEFAULT_CENTER, DEFAULT_ZOOM);
}

/**
 * 切换全屏
 */
function toggleFullscreen() {
    const mapContainer = document.querySelector('.map-container');
    
    if (!document.fullscreenElement) {
        mapContainer.requestFullscreen().catch(err => {
            showToast('无法进入全屏模式', 'error');
        });
    } else {
        document.exitFullscreen();
    }
}

/**
 * 更新地图信息
 */
function updateMapInfo() {
    const center = map.getCenter();
    const zoom = map.getZoom();
    
    document.getElementById('mapCenter').textContent = `中心: ${center.lat.toFixed(4)}, ${center.lng.toFixed(4)}`;
    document.getElementById('mapZoom').textContent = `缩放: ${zoom}`;
}

/**
 * 显示提示消息
 */
function showToast(message, type = 'info') {
    // 移除已存在的toast
    const existingToast = document.querySelector('.map-toast');
    if (existingToast) {
        existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.className = 'map-toast';
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        padding: 12px 24px;
        border-radius: 8px;
        color: white;
        font-size: 14px;
        z-index: 3000;
        animation: fadeInOut 3s ease;
        ${type === 'success' ? 'background: #28a745;' : ''}
        ${type === 'error' ? 'background: #dc3545;' : ''}
        ${type === 'warning' ? 'background: #ffc107; color: #333;' : ''}
        ${type === 'info' ? 'background: #17a2b8;' : ''}
    `;
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => toast.remove(), 3000);
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
        15% { opacity: 1; transform: translateX(-50%) translateY(0); }
        85% { opacity: 1; transform: translateX(-50%) translateY(0); }
        100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
    }
    
    .custom-marker {
        display: flex;
        justify-content: center;
    }
    
    .marker-pin {
        width: 30px;
        height: 42px;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        color: #dc3545;
        font-size: 30px;
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
    }
    
    .user-marker .user-pin {
        width: 30px;
        height: 30px;
        background: #667eea;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: white;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.5);
        border: 3px solid white;
    }
`;
document.head.appendChild(style);