<template>
  <el-card class="map-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>设备分布地图</span>
        <div>
          <el-button type="primary" size="small" icon="Refresh" @click="refreshMap" :loading="loading">刷新</el-button>
          <el-button type="success" size="small" icon="Location" @click="centerToCurrentLocation">定位到我的位置</el-button>
        </div>
      </div>
    </template>
    <div v-loading="loading" class="map-container">
      <!-- 高德地图容器 -->
      <div id="amap-container" class="amap-container"></div>
      
      <!-- 无数据提示 -->
      <div v-if="devicePoints.length === 0 && !loading" class="no-data">
        <el-empty description="暂无设备坐标数据" />
      </div>
      
      <!-- 拖动加载提示 -->
      <div v-if="isDragging" class="drag-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载当前区域设备...</span>
      </div>

      <!-- 图例 -->
      <div class="map-legend">
        <div class="legend-item">
          <div class="legend-color current-location"></div>
          <span>我的位置</span>
        </div>
        <div class="legend-item">
          <div class="legend-color device-normal"></div>
          <span>正常设备</span>
        </div>
        <div class="legend-item">
          <div class="legend-color device-warning"></div>
          <span>告警设备</span>
        </div>
        <div class="legend-item">
          <div class="legend-color device-offline"></div>
          <span>离线设备</span>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { getDeviceCoordinate } from '@/api/device/device'
import AMapLoader from '@amap/amap-jsapi-loader'

// 响应式数据
const loading = ref(false)
const devicePoints = ref([])
const visibleDevicePoints = ref([])
const currentLocation = ref(null)
const mapCenter = ref([114.06, 22.54])
const mapZoom = ref(12)
const mapInstance = ref(null)
const isDragging = ref(false)

// 标记和信息窗口相关
const markers = ref([])
const infoWindow = ref(null)
const currentLocationMarker = ref(null)

// 图标尺寸配置（增大尺寸）
const iconSize = {
  current: [48, 48],      // 当前位置图标尺寸
  device: [36, 36],       // 设备图标尺寸
  cluster: [40, 40]       // 聚合图标尺寸
}

// 设备状态颜色配置
const deviceStatusColors = {
  normal: '#67C23A',     // 正常 - 绿色
  warning: '#E6A23C',    // 告警 - 橙色
  offline: '#909399',    // 离线 - 灰色
  error: '#F56C6C'       // 故障 - 红色
}

onUnmounted(() => {
  if (mapInstance.value) {
    mapInstance.value.destroy()
    mapInstance.value = null
  }
})

// 防抖函数
const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 检查设备是否在当前可视区域内
const isDeviceInViewport = (device, bounds) => {
  if (!bounds || !device.lng || !device.lat) return false
  
  const { southWest, northEast } = bounds
  return device.lng >= southWest.lng && 
         device.lng <= northEast.lng && 
         device.lat >= southWest.lat && 
         device.lat <= northEast.lat
}

// 更新可见设备列表
const updateVisibleDevices = () => {
  if (!mapInstance.value) {
    visibleDevicePoints.value = devicePoints.value
    return
  }

  try {
    const bounds = mapInstance.value.getBounds()
    if (!bounds) {
      visibleDevicePoints.value = devicePoints.value
      return
    }

    const boundsObj = {
      southWest: { lng: bounds.southWest.lng, lat: bounds.southWest.lat },
      northEast: { lng: bounds.northEast.lng, lat: bounds.northEast.lat }
    }

    visibleDevicePoints.value = devicePoints.value.filter(device => 
      isDeviceInViewport(device, boundsObj)
    )

    console.log(`可视区域内设备数量: ${visibleDevicePoints.value.length}/${devicePoints.value.length}`)
    
    updateMarkersVisibility()
  } catch (error) {
    console.warn('更新可见设备列表失败:', error)
    visibleDevicePoints.value = devicePoints.value
  }
}

// 更新标记的显示状态
const updateMarkersVisibility = () => {
  if (!mapInstance.value) return
  
  markers.value.forEach(marker => {
    const device = marker.getExtData()
    const isVisible = visibleDevicePoints.value.some(visibleDevice => 
      visibleDevice.lng === device.lng && visibleDevice.lat === device.lat
    )
    
    if (isVisible) {
      marker.show()
    } else {
      marker.hide()
    }
  })
}

// 防抖的更新函数
const debouncedUpdateVisibleDevices = debounce(() => {
  updateVisibleDevices()
  isDragging.value = false
}, 300)

// 获取用户当前位置
const getCurrentPosition = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          const location = [position.coords.longitude, position.coords.latitude]
          console.log('获取到当前位置(WGS84):', location)
          resolve(location)
        },
        error => {
          console.warn('获取当前位置失败:', error)
          resolve([114.026153, 22.621125])
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 300000
        }
      )
    } else {
      console.warn('浏览器不支持地理位置获取')
      resolve([114.026153, 22.621125])
    }
  })
}

// 使用高德地图官方坐标转换API
const transformCoordinateWithAMap = async (lng, lat) => {
  return new Promise((resolve) => {
    if (!window.AMap) {
      console.warn('高德地图未加载，使用本地转换')
      resolve(transformWGS84ToGCJ02(lng, lat))
      return
    }
    
    AMap.convertFrom([lng, lat], 'gps', (status, result) => {
      if (status === 'complete' && result.info === 'ok') {
        const converted = result.locations[0]
        console.log(`坐标转换成功: ${lng},${lat} -> ${converted.lng},${converted.lat}`)
        resolve([converted.lng, converted.lat])
      } else {
        console.warn('高德坐标转换失败，使用本地转换:', status)
        resolve(transformWGS84ToGCJ02(lng, lat))
      }
    })
  })
}

// 获取设备状态颜色
const getDeviceStatusColor = (device) => {
  // 根据设备状态返回对应颜色
  if (device.status === 'offline') return deviceStatusColors.offline
  if (device.status === 'warning') return deviceStatusColors.warning
  if (device.status === 'error') return deviceStatusColors.error
  return deviceStatusColors.normal
}

// 创建设备SVG图标（更大更醒目）
const createDeviceSvgIcon = (color, status = 'normal') => {
  const size = iconSize.device
  const width = size[0]
  const height = size[1]
  
  // 根据状态添加不同的图标样式
  let iconPath = ''
  switch (status) {
    case 'warning':
      // 警告图标 - 感叹号
      iconPath = `
        <circle cx="${width/2}" cy="${height/2}" r="${width/2 - 2}" fill="${color}" stroke="#fff" stroke-width="2"/>
        <path d="M${width/2} ${height/4} L${width/2} ${height*2/3} M${width/2} ${height*3/4} L${width/2} ${height*3/4}" stroke="#fff" stroke-width="2" stroke-linecap="round"/>
        <circle cx="${width/2}" cy="${height*3/4}" r="1" fill="#fff"/>
      `
      break
    case 'offline':
      // 离线图标 - 带斜线的圆圈
      iconPath = `
        <circle cx="${width/2}" cy="${height/2}" r="${width/2 - 2}" fill="${color}" stroke="#fff" stroke-width="2"/>
        <line x1="${width/4}" y1="${height/4}" x2="${width*3/4}" y2="${height*3/4}" stroke="#fff" stroke-width="2"/>
      `
      break
    case 'error':
      // 错误图标 - 叉号
      iconPath = `
        <circle cx="${width/2}" cy="${height/2}" r="${width/2 - 2}" fill="${color}" stroke="#fff" stroke-width="2"/>
        <line x1="${width/3}" y1="${height/3}" x2="${width*2/3}" y2="${height*2/3}" stroke="#fff" stroke-width="2"/>
        <line x1="${width*2/3}" y1="${height/3}" x2="${width/3}" y2="${height*2/3}" stroke="#fff" stroke-width="2"/>
      `
      break
    default:
      // 正常图标 - 定位针
      iconPath = `
        <path d="M${width/2} ${height/6} C${width*2/3} ${height/6} ${width*5/6} ${height/3} ${width*5/6} ${height/2} C${width*5/6} ${height*2/3} ${width/2} ${height*5/6} ${width/2} ${height*5/6} C${width/2} ${height*5/6} ${width/6} ${height*2/3} ${width/6} ${height/2} C${width/6} ${height/3} ${width/3} ${height/6} ${width/2} ${height/6} Z" fill="${color}"/>
        <circle cx="${width/2}" cy="${height/2}" r="${width/6}" fill="#fff"/>
        <circle cx="${width/2}" cy="${height/2}" r="${width/8}" fill="${color}"/>
      `
  }
  
  const svg = `
    <svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
      ${iconPath}
      <circle cx="${width/2}" cy="${height/2}" r="${width/2}" fill="none" stroke="#fff" stroke-width="1" opacity="0.5"/>
    </svg>
  `
  
  return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svg)))}`
}

// 创建当前位置SVG图标（更大更醒目）
const createCurrentLocationSvgIcon = () => {
  const size = iconSize.current
  const width = size[0]
  const height = size[1]
  
  const svg = `
    <svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
      <circle cx="${width/2}" cy="${height/2}" r="${width/2 - 4}" fill="#409EFF" fill-opacity="0.8" stroke="#fff" stroke-width="3"/>
      <circle cx="${width/2}" cy="${height/2}" r="${width/4}" fill="#fff"/>
      <circle cx="${width/2}" cy="${height/2}" r="${width/8}" fill="#409EFF"/>
      <circle cx="${width/2}" cy="${height/2}" r="${width/2}" fill="none" stroke="#409EFF" stroke-width="2" opacity="0.3"/>
    </svg>
  `
  
  return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svg)))}`
}

// 获取设备坐标数据
const loadDevicePoints = async () => {
  loading.value = true
  try {
    const response = await getDeviceCoordinate()
    const rawDevicePoints = response.data || []
    
    console.log('原始设备数据:', rawDevicePoints)
    
    // 坐标转换：WGS84转GCJ-02
    const transformedPoints = []
    for (let device of rawDevicePoints) {
      if (!device.lng || !device.lat) {
        console.warn('设备坐标数据不完整:', device)
        transformedPoints.push(device)
        continue
      }
      
      try {
        // 使用高德官方转换
        const [convertedLng, convertedLat] = await transformCoordinateWithAMap(device.lng, device.lat)
        
        transformedPoints.push({
          ...device,
          lng: convertedLng,
          lat: convertedLat,
          originalLng: device.lng,
          originalLat: device.lat,
          // 确保有状态字段
          status: device.status || 'normal'
        })
        
      } catch (error) {
        console.error('坐标转换失败:', error, device)
        transformedPoints.push({
          ...device,
          status: device.status || 'normal'
        })
      }
    }
    
    devicePoints.value = transformedPoints
    console.log('转换后的设备坐标数据(GCJ-02):', devicePoints.value)
    
    if (devicePoints.value.length === 0) {
      console.warn('没有获取到设备坐标数据')
      ElMessage.warning('暂无设备坐标数据')
      visibleDevicePoints.value = []
      clearMarkers()
    } else {
      ElMessage.success(`成功加载 ${devicePoints.value.length} 个设备位置`)
      createDeviceMarkers()
      updateVisibleDevices()
    }
  } catch (error) {
    console.error('获取设备坐标失败:', error)
    ElMessage.error('获取设备坐标数据失败')
  } finally {
    loading.value = false
  }
}

// WGS84转GCJ-02坐标转换函数
const transformWGS84ToGCJ02 = (lng, lat) => {
  if (!lng || !lat) return [lng, lat];
  
  const PI = 3.1415926535897932384626;
  const a = 6378245.0;
  const ee = 0.00669342162296594323;
  
  if (lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271) {
    return [lng, lat];
  }
  
  const transformLat = (x, y) => {
    let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
    return ret;
  };

  const transformLng = (x, y) => {
    let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
    ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
    return ret;
  };

  let wgLat = +lat;
  let wgLon = +lng;
  
  let dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
  let dLon = transformLng(wgLon - 105.0, wgLat - 35.0);
  
  const radLat = wgLat / 180.0 * PI;
  let magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  const sqrtMagic = Math.sqrt(magic);
  
  dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
  dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
  
  const mgLat = wgLat + dLat;
  const mgLon = wgLon + dLon;
  
  return [mgLon, mgLat];
};

// 创建设备标记（更大更醒目）
const createDeviceMarkers = () => {
  clearMarkers()
  
  devicePoints.value.forEach(device => {
    if (!device.lng || !device.lat) return
    
    const statusColor = getDeviceStatusColor(device)
    const iconSvg = createDeviceSvgIcon(statusColor, device.status)
    
    const icon = new AMap.Icon({
      size: new AMap.Size(iconSize.device[0], iconSize.device[1]),
      image: iconSvg,
      imageSize: new AMap.Size(iconSize.device[0], iconSize.device[1])
    })
    
    const marker = new AMap.Marker({
      position: [device.lng, device.lat],
      icon: icon,
      offset: new AMap.Pixel(-iconSize.device[0]/2, -iconSize.device[1]/2),
      title: device.name || '未知设备',
      map: mapInstance.value,
      zIndex: 10 // 提高z-index确保显示在最前面
    })
    
    marker.setExtData(device)
    
    marker.on('click', () => {
      showDeviceInfo(device, marker.getPosition())
    })
    
    // 添加鼠标悬停效果
    marker.on('mouseover', () => {
      marker.setzIndex(100)
    })
    
    marker.on('mouseout', () => {
      marker.setzIndex(10)
    })
    
    markers.value.push(marker)
  })
}

// 清除所有设备标记
const clearMarkers = () => {
  markers.value.forEach(marker => {
    mapInstance.value.remove(marker)
  })
  markers.value = []
}

// 创建当前位置标记（更大更醒目）
const createCurrentLocationMarker = (position) => {
  if (currentLocationMarker.value) {
    mapInstance.value.remove(currentLocationMarker.value)
  }
  
  const iconSvg = createCurrentLocationSvgIcon()
  
  currentLocationMarker.value = new AMap.Marker({
    position: position,
    icon: new AMap.Icon({
      image: iconSvg,
      size: new AMap.Size(iconSize.current[0], iconSize.current[1]),
      imageSize: new AMap.Size(iconSize.current[0], iconSize.current[1])
    }),
    offset: new AMap.Pixel(-iconSize.current[0]/2, -iconSize.current[1]/2),
    map: mapInstance.value,
    zIndex: 100 // 最高z-index，确保显示在最前面
  })
  
  currentLocationMarker.value.on('click', () => {
    showCurrentLocationInfo(position)
  })
}

// 创建信息窗口
const createInfoWindow = () => {
  infoWindow.value = new AMap.InfoWindow({
    offset: new AMap.Pixel(0, -40),
    closeWhenClickMap: true,
    autoMove: true
  })
}

// 显示当前位置信息
const showCurrentLocationInfo = (position) => {
  if (!infoWindow.value) createInfoWindow()
  
  const content = `
    <div class="info-content">
      <h4>📍 我的位置</h4>
      <div class="info-details">
        <div><strong>经度(GCJ-02):</strong> ${position[0].toFixed(6)}</div>
        <div><strong>纬度(GCJ-02):</strong> ${position[1].toFixed(6)}</div>
        <div><strong>坐标系:</strong> 高德地图(GCJ-02)</div>
      </div>
    </div>
  `
  
  infoWindow.value.setContent(content)
  infoWindow.value.open(mapInstance.value, position)
}

// 显示设备信息
const showDeviceInfo = (device, position) => {
  if (!infoWindow.value) createInfoWindow()
  
  const statusText = {
    normal: '正常',
    warning: '告警',
    offline: '离线',
    error: '故障'
  }[device.status] || '未知'
  
  const statusColor = getDeviceStatusColor(device)
  
  const content = `
    <div class="info-content">
      <h4>📱 ${device.name || '未知设备'}</h4>
      <div class="info-details">
        <div><strong>状态:</strong> <span style="color:${statusColor}">${statusText}</span></div>
        <div><strong>高德坐标(GCJ-02):</strong> ${position[0].toFixed(6)}, ${position[1].toFixed(6)}</div>
        <div><strong>原始坐标(WGS84):</strong> ${(device.originalLng || device.lng).toFixed(6)}, ${(device.originalLat || device.lat).toFixed(6)}</div>
        ${device.address ? `<div><strong>地址:</strong> ${device.address}</div>` : ''}
      </div>
    </div>
  `
  
  infoWindow.value.setContent(content)
  infoWindow.value.open(mapInstance.value, position)
}

// 初始化地图
const initMap = async () => {
  try {
    window._AMapSecurityConfig = {
      securityJsCode: "您的安全密钥"
    };
    
    const AMap = await AMapLoader.load({
      key: "ddf0be258cfcf9d8df2d6a2dcc5ff294",
      version: "2.0",
      plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.InfoWindow', 'AMap.Marker']
    })
    
    mapInstance.value = new AMap.Map('amap-container', {
      viewMode: '2D',
      zoom: mapZoom.value,
      center: mapCenter.value,
      mapStyle: 'amap://styles/normal',
      optimizeMode: true
    })
    
    mapInstance.value.on('complete', () => {
      console.log('地图加载完成')
      loadDevicePoints()
    })
    
    mapInstance.value.on('moveend', debouncedUpdateVisibleDevices)
    mapInstance.value.on('zoomend', debouncedUpdateVisibleDevices)
    mapInstance.value.on('movestart', () => {
      isDragging.value = true
    })
    
    createInfoWindow()
    mapInstance.value.addControl(new AMap.Scale())
    mapInstance.value.addControl(new AMap.ToolBar({
      position: 'RB'
    }))
    
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('地图加载失败，请检查网络连接或API Key配置')
  }
}

// 刷新地图
const refreshMap = () => {
  loadDevicePoints()
  
  if (mapInstance.value) {
    console.log('刷新地图数据')
    setTimeout(() => {
      updateVisibleDevices()
    }, 100)
  }
}

// 定位到当前位置
const centerToCurrentLocation = async () => {
  try {
    const location = await getCurrentPosition()
    currentLocation.value = location
    
    if (mapInstance.value) {
      // 转换当前位置到高德坐标
      const [convertedLng, convertedLat] = await transformCoordinateWithAMap(location[0], location[1])
      const convertedLocation = [convertedLng, convertedLat]
      
      mapInstance.value.setCenter(convertedLocation)
      mapInstance.value.setZoom(15) // 放大到更近的级别
      createCurrentLocationMarker(convertedLocation)
    }
    
    ElMessage.success('已定位到您的位置（高德坐标系）')
  } catch (error) {
    console.error('定位失败:', error)
    ElMessage.error('定位失败，请检查位置权限设置')
  }
}

onMounted(() => {
  initMap()
})
</script>

<style scoped>
.map-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header > div {
  display: flex;
  gap: 10px;
}

.map-container {
  position: relative;
  width: 100%;
  height: 600px; /* 增加地图高度 */
  min-height: 500px;
}

.amap-container {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  min-height: 500px;
  position: relative;
  overflow: hidden;
}

.no-data {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  border-radius: 4px;
  z-index: 10;
}

.drag-loading {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 10px 15px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #409eff;
  z-index: 1000;
  border: 1px solid #ebeef5;
}

/* 图例样式 */
.map-legend {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  border: 1px solid #ebeef5;
  min-width: 120px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 12px;
  color: #606266;
}

.legend-item:last-child {
  margin-bottom: 0;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.legend-color.current-location {
  background: #409EFF;
}

.legend-color.device-normal {
  background: #67C23A;
}

.legend-color.device-warning {
  background: #E6A23C;
}

.legend-color.device-offline {
  background: #909399;
}

/* 信息窗口样式增强 */
:deep(.info-content) {
  min-width: 200px;
  padding: 8px;
}

:deep(.info-content h4) {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
}

:deep(.info-details) {
  font-size: 12px;
  line-height: 1.5;
}

:deep(.info-details div) {
  margin-bottom: 4px;
}

:deep(.info-details strong) {
  color: #606266;
  min-width: 60px;
  display: inline-block;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .map-container {
    height: 450px;
    min-height: 400px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header > div {
    width: 100%;
    justify-content: flex-end;
  }
  
  .map-legend {
    top: auto;
    bottom: 10px;
    left: 10px;
    right: 10px;
    display: flex;
    justify-content: space-around;
    padding: 8px;
  }
  
  .legend-item {
    flex-direction: column;
    margin-bottom: 0;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .map-container {
    height: 400px;
    min-height: 350px;
  }
  
  .map-legend {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .legend-item {
    flex: 1;
    min-width: 60px;
  }
}
</style>