<template>
  <div class="map-wrapper" :style="mapCssVars">
    <div ref="mapContainer" class="map-container"></div>

    <div class="map-legend" :style="privateStyle.legend" v-if="(!mode || mode === '路口')"
      :class="{ 'legend-hidden': !legendVisible }">
      <div class="legend-header">
        <div class="legend-title">图例</div>
        <div class="legend-close-btn" @click="toggleLegend">✕</div>
      </div>
      <div class="legend-list">
        <div class="legend-item all-select" @click="toggleAll">
          <div class="legend-dot all-select-dot" :class="{ 'is-checked': isAllSelected }">
            <i class="check-icon" v-if="isAllSelected"></i>
          </div>
          <div class="legend-label" style="font-weight: bold;">全选</div>
        </div>

        <div v-for="item in legendStatusConfig" class="legend-item" @click="toggleRouteVisible(item.name)" :key="item.name"
          :class="{ 'is-inactive': !activeLegends.includes(item.name) }">

          <div class="legend-dot"
            :style="{ backgroundColor: ['离线', '降级', '故障'].includes(item.name) ? 'transparent' : item.color }"
            :class="{ 'special-route': ['干线协调', '勤务路线'].includes(item.name), 'is-status-wrapper': ['离线', '降级', '故障'].includes(item.name) }">

            <span v-if="!['离线', '降级', '故障'].includes(item.name)">
              {{ item.name.charAt(0) }}
            </span>

            <img v-else
              :src="require(`@/assets/images/icon_${item.name === '离线' ? 'lixian' : item.name === '降级' ? 'jiangji' : 'guzhang'}.png`)"
              class="status-icon" />
          </div>

          <div class="legend-label">{{ item.name }}</div>
        </div>
      </div>
    </div>
    <div class="legend-show-btn" v-if="(!mode || mode === '路口') && !legendVisible" @click="toggleLegend" :style="legendShowBtnStyle" title="显示图例">
      <div class="legend-show-icon">☰</div>
    </div>

    <div v-if="showSearch" class="map-search-wrap" :style="searchBoxStyle">
      <MapSearchBox :data-source="intersectionData" @select="onSearchSelect" />
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getIntersectionCategory } from '@/mock/api';
import MapSearchBox from '@/components/ui/MapSearchBox.vue';
import { amap as amapConfig } from '@/utils/brand';

export default {
  name: "TrafficMap",
  components: { MapSearchBox },
  props: {
    amapKey: { type: String, default: () => amapConfig.key },
    securityJsCode: { type: String, default: () => amapConfig.securityCode },
    mode: { type: String, default: '', validator: (value) => ['', '路口', '干线', '特勤'].includes(value) },
    // 是否渲染地图搜索框。默认关闭，仅 Home 显式开启。
    showSearch: { type: Boolean, default: false },
    // 搜索框相对屏幕右侧的偏移；默认 490px 适配 Home 的 400px 右侧栏。
    searchOffsetRight: { type: Number, default: 490 },
    searchOffsetTop: { type: Number, default: 110 },
  },
  data() {
    return {
      AMap: null,
      map: null,
      infoWindow: null,
      routeGroups: {},
      dotMarkers: [],
      privateStyle: {
        legend: {}
      },
      legendVisible: true,
      activeLegends: ["中心计划", "干线协调", "勤务路线", "定周期控制", "感应控制", "自适应控制", "手动控制", "黄闪", "全红", "关灯", "离线", "降级", "故障"],
      isComponentDestroyed: false,
      drawSeq: 0,
      driving: null,
      infoCloseTimer: null,
      activeInfoWindowId: null,
      isInfoWindowHovered: false,
      statusConfig: [
        { name: "中心计划", color: "#004CDE", type: "normal" },
        { name: "干线协调", color: "#13C373", type: "route" },
        { name: "勤务路线", color: "#BC301D", type: "route" },
        { name: "定周期控制", color: "#3296FA", type: "normal" },
        { name: "感应控制", color: "#FF864C", type: "normal" },
        { name: "自适应控制", color: "#9F6EFE", type: "normal" },
        { name: "手动控制", color: "#EB9F36", type: "normal" },
        { name: "黄闪", color: "#F4D03F", type: "normal" },
        { name: "全红", color: "#E74C3C", type: "normal" },
        { name: "关灯", color: "#5B6B7A", type: "normal" },
        { name: "离线", color: "#7A7A7A", type: "abnormal" },
        // 降级 仍参与数据分类与地图绘制，但不出现在图例（hideInLegend: true）
        { name: "降级", color: "#D9C13B", type: "abnormal", hideInLegend: true },
        { name: "故障", color: "#FF3938", type: "abnormal" }
      ],
      intersectionData: [],
      statusIntersections: {},
      currentZoomSize: 20, // 保存当前的动态尺寸（与 zoom=15 基准一致）
      markerById: {}, // ID → marker 索引，加速 focusById 查找
      startEndMarkers: [], // 起点/终点 marker 引用，缩放时需重建
      subAreaOverlays: [], // 子区蒙层覆盖物
      _subAreaParams: null, // 子区绘制参数，缩放时重绘用
      // ── 视口裁剪相关（详见 pyscripts/AMap路口marker视口加载与聚合设计.md Phase 1）──
      mountedMarkerSet: new Set(),       // 当前已挂载到 map 的 overlay 引用
      _viewportRefreshTimer: null,       // moveend/zoomend 合并 debounce 句柄
      viewportBufferRatio: 0.15,         // 视口外扩比例
      viewportRefreshDebounceMs: 100,    // 拖图停下后多久执行一次重算
      _infoWindowProtectedMarker: null,  // InfoWindow 打开时的 marker，期间不参与裁剪
    };
  },
  mounted() {
    this.isComponentDestroyed = false;
    this.loadMapData().then(() => {
      this.classifyIntersectionsByStatus();
      this.updateMapByMode();
      this.initAMap();
      this.storeStatusCoordsToLocalStorage();
    });

    if (this.$route.path === '/home' || this.$route.path === '/watch') {
      this.privateStyle.legend = { right: "25%" };
    }
  },
  watch: {
    mode: {
      handler() {
        this.updateMapByMode();
        this.updateMapDisplay();
      },
      immediate: false
    }
  },
  beforeDestroy() {
    // 1. 立即设置销毁状态
    this.isComponentDestroyed = true;
    this.drawSeq += 1;

    // 1.5 清理视口裁剪 debounce 句柄与挂载集
    if (this._viewportRefreshTimer) {
      clearTimeout(this._viewportRefreshTimer);
      this._viewportRefreshTimer = null;
    }
    if (this.mountedMarkerSet) this.mountedMarkerSet.clear();
    this._infoWindowProtectedMarker = null;

    // 2. 关闭弹窗
    if (this.infoWindow) {
      try {
        this.infoWindow.close();
      } catch (e) {
        console.warn('关闭信息窗口时出错:', e);
      }
      this.infoWindow = null;
    }

    // 3. 清理覆盖物引用
    if (this.routeGroups) {
      Object.values(this.routeGroups).forEach(overlays => {
        if (Array.isArray(overlays)) {
          overlays.forEach(o => {
            try {
              if (o.setMap) o.setMap(null);
            } catch (e) {
              console.warn('清理覆盖物时出错:', e);
            }
          });
        }
      });
      this.routeGroups = {};
      this.startEndMarkers = [];
    }

    // 4. 清理子区蒙层
    this.clearSubAreaOverlays();

    // 6. 销毁地图实例并清空引用
    if (this.map) {
      try {
        this.map.destroy();
      } catch (e) {
        console.warn('销毁地图实例时出错:', e);
      }
      this.map = null;
    }

    // 7. 清理其他引用
    this.AMap = null;
    this.driving = null;
    if (this.infoCloseTimer) {
      clearTimeout(this.infoCloseTimer);
      this.infoCloseTimer = null;
    }
    this.activeInfoWindowId = null;
    this.isInfoWindowHovered = false;
  },
  computed: {
    // 全选状态：仅判断"图例上可见的项"是否全部启用，不受常隐项（如降级）影响
    isAllSelected() {
      const visible = this.legendStatusConfig.map(i => i.name);
      if (visible.length === 0) return false;
      return visible.every(n => this.activeLegends.includes(n));
    },
    isHomePage() {
      return this.$route && (this.$route.path === '/home' || this.$route.path === '/surve');
    },
    legendShowBtnStyle() {
      if (!this.isHomePage) return {};
      const right = (this.privateStyle.legend && this.privateStyle.legend.right) ? this.privateStyle.legend.right : '25%';
      return { right, borderRadius: '6px' };
    },
    searchBoxStyle() {
      return {
        position: 'fixed',
        top: `${this.searchOffsetTop}px`,
        right: `${this.searchOffsetRight}px`,
        zIndex: 999,
      };
    },
    legendStatusConfig() {
      // 1. 按 mode 过滤
      let list = this.statusConfig;
      if (this.mode === '路口') {
        list = list.filter(item => !['干线协调', '勤务路线'].includes(item.name));
      } else if (this.mode && this.mode !== '路口') {
        return [];
      }
      // 2. hideInLegend 项一律不进图例（数据与地图绘制不受影响）
      list = list.filter(item => !item.hideInLegend);
      // 3. 仅展示路口/路线实际存在的控制模式：
      //    - 路线类（type: route）固定有线段配置，始终显示
      //    - 其余按 statusIntersections[name] 是否非空过滤
      list = list.filter(item => {
        if (item.type === 'route') return true;
        const ints = this.statusIntersections && this.statusIntersections[item.name];
        return ints && ints.length > 0;
      });
      return list;
    },
    // 自动计算并下发给所有 CSS 的变量字典
    mapCssVars() {
      const size = this.currentZoomSize;
      const specialSize = Math.max(12, size * 1.2);
      return {
        '--dot-size': `${size}px`,
        '--dot-padding': size >= 14 ? '4px' : '0px',
        '--text-display': size >= 14 ? 'flex' : 'none',
        '--text-size': `${Math.max(10, size - 4)}px`,
        '--special-size': `${specialSize}px`
      };
    }
  },
  methods: {
    // 视口裁剪（Phase 1，详见 pyscripts/AMap路口marker视口加载与聚合设计.md）

    /**
     * 单一调度入口：根据 map.getBounds() 与 activeLegends 计算应显示的 marker 集合，
     * 与已挂载集合做 diff，批量 add/remove。
     */
    computeVisibleMarkers() {
      if (!this.isMapReady()) return;
      const bounds = this.map.getBounds();
      if (!bounds) return;

      // 视口外扩 buffer，避免边缘 marker 在拖动停下时立刻消失
      const expanded = this.expandBounds(bounds, this.viewportBufferRatio);

      const visibleLegendNames = new Set(this.activeLegends);
      const shouldShow = new Set();

      // 收集应显示的 overlay
      Object.keys(this.routeGroups).forEach(name => {
        const overlays = this.routeGroups[name];
        if (!overlays || overlays.length === 0) return;
        if (!visibleLegendNames.has(name)) return;

        for (const o of overlays) {
          // 路线（折线/弧线/装饰）—— 不参与视口裁剪
          if (!this.isMarkerNode(o)) {
            shouldShow.add(o);
            continue;
          }
          // 起终点 marker —— 不参与视口裁剪（数量极少）
          if (this.isStartEndMarker(o)) {
            shouldShow.add(o);
            continue;
          }
          // 普通路口 marker —— 按视口判定
          const pos = this.getOverlayPosition(o);
          if (pos && this.boundsContains(expanded, pos)) {
            shouldShow.add(o);
          }
        }
      });

      // InfoWindow 打开期间 marker 豁免：始终保留以避免底层 marker 被移除导致弹窗错位
      if (this._infoWindowProtectedMarker) {
        shouldShow.add(this._infoWindowProtectedMarker);
      }

      // diff
      const toAdd = [];
      const toRemove = [];
      shouldShow.forEach(o => {
        if (!this.mountedMarkerSet.has(o)) toAdd.push(o);
      });
      this.mountedMarkerSet.forEach(o => {
        if (!shouldShow.has(o)) toRemove.push(o);
      });

      if (toAdd.length) {
        try { this.map.add(toAdd); } catch (e) { void e; }
        toAdd.forEach(o => this.mountedMarkerSet.add(o));
      }
      if (toRemove.length) {
        try { this.map.remove(toRemove); } catch (e) { void e; }
        toRemove.forEach(o => this.mountedMarkerSet.delete(o));
      }
    },

    /**
     * 拖图/缩放后合并触发的视口刷新；100ms 内多次调用合并为一次。
     */
    scheduleViewportRefresh() {
      if (this._viewportRefreshTimer) return;
      this._viewportRefreshTimer = setTimeout(() => {
        this._viewportRefreshTimer = null;
        this.computeVisibleMarkers();
      }, this.viewportRefreshDebounceMs);
    },

    /**
     * 视口外扩 ratio 比例，避免在边界处 marker 闪入闪出。
     */
    expandBounds(bounds, ratio) {
      const sw = bounds.getSouthWest();
      const ne = bounds.getNorthEast();
      const dLng = (ne.lng - sw.lng) * ratio;
      const dLat = (ne.lat - sw.lat) * ratio;
      return new this.AMap.Bounds(
        [sw.lng - dLng, sw.lat - dLat],
        [ne.lng + dLng, ne.lat + dLat]
      );
    },

    /**
     * 兼容多种 position 形态（[lng,lat] 数组 / LngLat 对象）的 contains 判定。
     */
    boundsContains(bounds, pos) {
      try {
        if (Array.isArray(pos)) {
          return bounds.contains(new this.AMap.LngLat(pos[0], pos[1]));
        }
        return bounds.contains(pos);
      } catch (e) {
        return false;
      }
    },

    isMarkerNode(o) {
      return this.AMap && o instanceof this.AMap.Marker;
    },

    isStartEndMarker(o) {
      if (!o || !this.startEndMarkers || this.startEndMarkers.length === 0) return false;
      for (const s of this.startEndMarkers) {
        if (s.marker === o) return true;
      }
      return false;
    },

    /**
     * 取 overlay 经纬位置：优先用 marker.getPosition()，回退到 extData.position。
     */
    getOverlayPosition(o) {
      if (!o) return null;
      if (typeof o.getPosition === 'function') {
        const p = o.getPosition();
        if (p) return p;
      }
      const ext = (typeof o.getExtData === 'function') ? o.getExtData() : null;
      return ext && ext.position;
    },

    /**
     * 动态加载地图数据
     * @returns {Promise<void>}
     */
    async loadMapData() {
      try {
        const mapDataModule = await import('@/mock/map_data_gaode.json');
        this.intersectionData = mapDataModule.default || [];
        console.log('地图数据加载成功，共', this.intersectionData.length, '个路口');
      } catch (error) {
        console.error('地图数据加载失败:', error);
        this.intersectionData = [];
      }
    },

    /**
     * 检查地图环境是否安全可用
     * @returns {boolean}
     */
    isMapReady() {
      return !this.isComponentDestroyed && this.map && typeof this.map.add === 'function';
    },

    /**
     * 将真实路口数据按状态类型分类
     */
    classifyIntersectionsByStatus() {
      const categories = {
        "中心计划": [], "干线协调": [], "勤务路线": [],
        "定周期控制": [], "感应控制": [], "自适应控制": [],
        "手动控制": [],
        "黄闪": [], "全红": [], "关灯": [],
        "离线": [], "降级": [], "故障": []
      };
      for (const item of this.intersectionData) {
        const category = getIntersectionCategory(item["路口编号"]);
        if (categories[category]) {
          categories[category].push(item);
        }
      }
      this.statusIntersections = categories;
    },

    /**
     * 根据模式更新地图显示
     */
    updateMapByMode() {
      switch (this.mode) {
        case '路口':
          this.activeLegends = ["中心计划", "定周期控制", "感应控制", "自适应控制", "手动控制", "黄闪", "全红", "关灯", "离线", "降级", "故障"];
          break;
        case '干线':
          this.activeLegends = ["干线协调"];
          break;
        case '特勤':
          this.activeLegends = ["勤务路线"];
          break;
        default:
          this.activeLegends = this.statusConfig.map(item => item.name);
      }
    },

    /**
     * 更新地图显示状态：统一委托给视口裁剪调度器，
     * 由 computeVisibleMarkers 综合 activeLegends + bounds 决定 add/remove。
     */
    updateMapDisplay() {
      if (this.infoWindow) this.infoWindow.close();
      if (!this.isMapReady()) return;
      this.computeVisibleMarkers();
    },

    /**
     * 初始化高德地图
     * @returns {Promise<void>}
     */
    async initAMap() {
      if (this.isComponentDestroyed) return;

      window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };

      try {
        const AMap = await AMapLoader.load({
          key: this.amapKey,
          version: "2.0",
          plugins: ['AMap.Driving']
        });

        if (this.isComponentDestroyed) return;

        this.AMap = AMap;
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 15,
          mapStyle: "amap://styles/darkblue",
          center: [116.663, 39.905]
        });

        this.driving = new AMap.Driving({ map: null, hideMarkers: true });

        this.map.on('complete', () => {
          if (!this.isComponentDestroyed) {
            this.currentZoomSize = this.getDotSizeByZoom();
            this.drawStaticRoutes();
          }
        });

        this.map.on('zoomend', () => {
          if (!this.isComponentDestroyed) {
            this.currentZoomSize = this.getDotSizeByZoom();
            this.rebuildStartEndMarkers();
            this.rebuildDotMarkers();
            this.rebuildSubAreaText();
            // 视口裁剪：缩放后重算视口内 marker
            this.scheduleViewportRefresh();
          }
        });

        // 视口裁剪：拖图停下后重算视口内 marker（debounce 100ms）
        this.map.on('moveend', () => {
          if (!this.isComponentDestroyed) {
            this.scheduleViewportRefresh();
          }
        });
      } catch (err) {
        console.error('地图加载失败:', err);
      }
    },

    /**
     * 绘制静态路线和标记
     * @returns {Promise<void>}
     */
    async drawStaticRoutes() {
      if (!this.isMapReady()) return;

      this.drawSeq += 1;
      const drawSeq = this.drawSeq;

      this.clearAllRouteOverlays();

      const realRouteConfigs = {
        "干线协调": [
          { start: [116.6421, 39.9272], end: [116.6623, 39.9272], color: "#13C373", trunkId: 'trunk_1', trunkName: '古城南路与古城大街' },
          { start: [116.6623, 39.9272], end: [116.6825, 39.9272], color: "#13C373", trunkId: 'trunk_2', trunkName: '古城西路东口南一过街' },
          { start: [116.6426, 39.9221], end: [116.6628, 39.9221], color: "#13C373", trunkId: 'trunk_3', trunkName: '古城大街与古城北路' },
          { start: [116.6628, 39.9221], end: [116.683, 39.9221], color: "#13C373", trunkId: 'trunk_4', trunkName: '八角北路与八角东街' },
          { start: [116.6432, 39.9171], end: [116.66325, 39.9171], color: "#13C373", trunkId: 'trunk_5', trunkName: '古城西路与古城大街' },
          { start: [116.66325, 39.9171], end: [116.6833, 39.9171], color: "#13C373", trunkId: 'trunk_6', trunkName: '张台路与湖亦路路口' },
        ],
        "勤务路线": [
          { start: [116.6400, 39.9270], end: [116.7000, 39.9270], color: "#BC301D", dutyState: 'pending', taskId: 1 },
          { start: [116.6400, 39.9120], end: [116.7000, 39.9120], color: "#BC301D", dutyState: 'active', progress: 0.45, taskId: 3 },
          { start: [116.6700, 39.8970], end: [116.7300, 39.8970], color: "#BC301D", dutyState: 'done', taskId: 2 },
          { start: [116.6400, 39.8820], end: [116.7000, 39.8820], color: "#BC301D", dutyState: 'done', taskId: 4 },
          { start: [116.6400, 39.8670], end: [116.7000, 39.8670], color: "#BC301D", dutyState: 'pending', taskId: 5 }
        ]
      };

      for (const config of this.statusConfig) {
        if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

        if (!realRouteConfigs[config.name]) {
          const intersections = this.statusIntersections[config.name] || [];
          const markers = intersections.map(item =>
            this.createTrafficLightMarker([item["位置-经度"], item["位置-纬度"]], {
              ...config,
              id: item["路口编号"],
              road: item["路口名称"] || '规划路口'
            })
          ).filter(Boolean);
          this.routeGroups[config.name] = markers;
          // 视口裁剪：不直接 add，由 computeVisibleMarkers 统一处理
          continue;
        }

        this.routeGroups[config.name] = [];
        const lines = realRouteConfigs[config.name] || [];
        const trunkSegments = [];

        for (let lineIdx = 0; lineIdx < lines.length; lineIdx += 1) {
          if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

          const line = lines[lineIdx];
          let path = null;
          try {
            path = await this.searchDrivingPathWithRetry(line.start, line.end);
          } catch (e) {
            path = null;
          }

          const overlays = this.buildRouteOverlaysFromPath({
            config,
            configName: config.name,
            line,
            lineIdx,
            path
          });

          if (config.name === '干线协调' && overlays.length > 0) {
            const name = line.trunkName || ('干线' + (lineIdx + 1));
            trunkSegments.push({
              id: line.trunkId || ('trunk_' + (lineIdx + 1)),
              label: name,
              intersections: Array.from({ length: 6 }, (_, k) => name + '_路口' + (k + 1)),
              distances: Array.from({ length: 6 }, (_, k) => k * 500),
              _lineIdx: lineIdx
            });
          }

          if (this.isComponentDestroyed || drawSeq !== this.drawSeq) return;

          if (overlays.length > 0) {
            this.routeGroups[config.name].push(...overlays);
            // 视口裁剪：每批新覆盖物入组后触发一次重算，让线/路口逐步出现在视口
            this.computeVisibleMarkers();
          }

          await this.sleep(80);
        }

        if (config.name === '干线协调' && trunkSegments.length > 0) {
          this.$emit('bindTrunkMenuTree', trunkSegments);
        }
      }

      // 全部 routeGroups 准备好后再做一次终态刷新
      this.computeVisibleMarkers();
    },

    /**
     * 清除所有路线覆盖物
     */
    clearAllRouteOverlays() {
      if (!this.isMapReady()) return;
      try {
        if (this.infoWindow) this.infoWindow.close();
      } catch (e) {
        void e;
      }

      Object.values(this.routeGroups || {}).forEach(overlays => {
        if (!Array.isArray(overlays) || overlays.length === 0) return;
        try {
          this.map.remove(overlays);
        } catch (e) {
          void e;
        }
        overlays.forEach(o => {
          try {
            if (o && typeof o.setMap === 'function') o.setMap(null);
          } catch (e) {
            void e;
          }
        });
      });

      this.routeGroups = {};
      this.startEndMarkers = [];
      this.dotMarkers = [];
      // 重置视口裁剪挂载集（已 map.remove 过，这里只清引用）
      this.mountedMarkerSet.clear();
    },

    /**
     * 休眠函数
     * @param {number} ms - 休眠毫秒数
     * @returns {Promise<void>}
     */
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },

    /**
     * 带重试机制的路径规划
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @returns {Promise<Array>} 路径点数组
     */
    async searchDrivingPathWithRetry(start, end) {
      if (!this.AMap || !this.driving || typeof this.driving.search !== 'function') {
        throw new Error('Driving not ready');
      }

      const maxAttempts = 3;
      let lastErr = null;
      for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
        try {
          return await this.withTimeout(this.searchDrivingPathOnce(start, end), 8000);
        } catch (e) {
          lastErr = e;
          await this.sleep(250 * attempt);
        }
      }
      throw lastErr || new Error('Driving search failed');
    },

    /**
     * 单次路径规划
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @returns {Promise<Array>} 路径点数组
     */
    searchDrivingPathOnce(start, end) {
      return new Promise((resolve, reject) => {
        this.driving.search(start, end, (status, result) => {
          const route = result && result.routes && result.routes[0];
          if (status === 'complete' && route && Array.isArray(route.steps)) {
            const fullPath = [];
            route.steps.forEach(step => {
              if (step && Array.isArray(step.path)) fullPath.push(...step.path);
            });
            if (fullPath.length >= 2) resolve(fullPath);
            else reject(new Error('empty_path'));
            return;
          }
          reject(new Error(typeof status === 'string' ? status : 'driving_error'));
        });
      });
    },

    /**
     * 为Promise添加超时机制
     * @param {Promise} promise - 要执行的Promise
     * @param {number} timeoutMs - 超时毫秒数
     * @returns {Promise} 带超时的Promise
     */
    withTimeout(promise, timeoutMs) {
      return Promise.race([
        promise,
        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
      ]);
    },

    /**
     * 从路径构建路线覆盖物
     * @param {Object} params - 参数对象
     * @param {Object} params.config - 配置对象
     * @param {string} params.configName - 配置名称
     * @param {Object} params.line - 路线配置
     * @param {number} params.lineIdx - 路线索引
     * @param {Array} params.path - 路径点数组
     * @returns {Array} 覆盖物数组
     */
    buildRouteOverlaysFromPath({ config, configName, line, lineIdx, path }) {
      if (!this.AMap || !this.map) return [];

      let basePath = path;
      if (!Array.isArray(basePath) || basePath.length < 2) {
        basePath = this.buildFallbackLinePath(line.start, line.end, 30);
      }

      const offsetVal = 0;
      const applyOffset = (p) => {
        const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
        const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
        return [lng + offsetVal, lat + offsetVal];
      };

      const allSegments = this.extractMainStraightSegments(basePath);
      const segments = configName === '干线协调'
        ? allSegments.slice(0, 1)
        : configName === '勤务路线'
          ? [basePath]
          : allSegments;
      const overlays = [];

      segments.forEach((rawSegmentPath, segmentIdx) => {
        if (!Array.isArray(rawSegmentPath) || rawSegmentPath.length < 2) return;

        const segmentPath = rawSegmentPath.map(p => applyOffset(p));

        if (configName === '勤务路线' && line.dutyState) {
          const state = line.dutyState; // 'pending' | 'active' | 'done'
          const progress = (state === 'active') ? Math.min(Math.max(Number(line.progress) || 0.5, 0), 1) : (state === 'done' ? 1 : 0);

          // 计算整段累计距离
          const dists = [0];
          let totalDist = 0;
          for (let j = 0; j < segmentPath.length - 1; j++) {
            totalDist += this.calcApproxDistance(segmentPath[j], segmentPath[j + 1]);
            dists.push(totalDist);
          }
          const splitDist = totalDist * progress;

          // 找切割点坐标（线性插值）
          let splitIdx = segmentPath.length - 1;
          let splitPoint = segmentPath[segmentPath.length - 1];
          for (let j = 0; j < dists.length - 1; j++) {
            if (splitDist >= dists[j] && splitDist <= dists[j + 1]) {
              const ratio = dists[j + 1] === dists[j] ? 0 : (splitDist - dists[j]) / (dists[j + 1] - dists[j]);
              const p1 = segmentPath[j], p2 = segmentPath[j + 1];
              splitPoint = [
                Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio,
                Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio
              ];
              splitIdx = j;
              break;
            }
          }

          // 已过段（灰色）
          const passedPath = [...segmentPath.slice(0, splitIdx + 1), splitPoint];
          if (passedPath.length >= 2) {
            overlays.push(new this.AMap.Polyline({
              path: passedPath,
              strokeColor: '#5A5A5A',
              strokeWeight: 6,
              strokeOpacity: 0.45,
              zIndex: 15
            }));
          }

          // 未过段（原红色），done 状态不绘制
          const remainPath = [splitPoint, ...segmentPath.slice(splitIdx + 1)];
          if (state !== 'done' && remainPath.length >= 2) {
            overlays.push(new this.AMap.Polyline({
              path: remainPath,
              strokeColor: line.color,
              strokeWeight: 6,
              strokeOpacity: 0.8,
              zIndex: 15
            }));
          }

          // 执行中：进度点脉冲 marker
          if (state === 'active') {
            overlays.push(new this.AMap.Marker({
              position: splitPoint,
              zIndex: 150,
              anchor: 'center',
              bubble: true,
              content: `<div class="duty-progress-node" style="width:var(--special-size);height:var(--special-size);border-radius:50%;background:#BC301D;border:3px solid #fff;box-shadow:0 0 0 3px rgba(188,48,29,0.4);display:flex;justify-content:center;align-items:center;cursor:default;"><div style="width:30%;height:30%;border-radius:50%;background:#fff;"></div></div>`
            }));
          }

          // 方向箭头：已过段灰色低透明，未过段正常
          const targetSpacing = 0.0036;
          let arrowDist = targetSpacing / 2;
          while (arrowDist < totalDist) {
            let foundIdx = 0;
            for (let j = 0; j < dists.length - 1; j++) {
              if (arrowDist >= dists[j] && arrowDist <= dists[j + 1]) { foundIdx = j; break; }
            }
            const p1 = segmentPath[foundIdx], p2 = segmentPath[foundIdx + 1];
            if (p1 && p2) {
              const ratio = (arrowDist - dists[foundIdx]) / (dists[foundIdx + 1] - dists[foundIdx]);
              const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
              const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
              const isPassed = arrowDist <= splitDist;
              const rotation = this.calcBearingDeg(p1, p2) - 90;
              overlays.push(new this.AMap.Marker({
                position: [midLng, midLat],
                content: `<div style="transform:rotate(${rotation}deg);width:20px;height:10px;display:flex;align-items:center;pointer-events:none;opacity:${isPassed ? 0.2 : 0.85};filter:${isPassed ? 'grayscale(1)' : 'none'};"><img src="${require('@/assets/map/direction.png')}" style="width:100%;height:auto;" /></div>`,
                offset: new this.AMap.Pixel(-10, -5),
                zIndex: 20,
                bubble: true
              }));
            }
            arrowDist += targetSpacing;
          }

          // 路口圆点：已过置灰，未过正常
          const indices = this.pickEvenlySpacedIndices(segmentPath.length, 6);
          for (let i = 0; i < indices.length; i++) {
            const idx = indices[i];
            const p = segmentPath[idx];
            const lng = Number(p[0]), lat = Number(p[1]);
            if (Number.isNaN(lng) || Number.isNaN(lat)) continue;
            const dotDist = dists[idx] || 0;
            let markerType = 'normal';
            if (i === 0) markerType = 'start';
            else if (i === indices.length - 1) markerType = 'end';

            const isPastDot = dotDist <= splitDist;
            const dotConfig = isPastDot
              ? { ...config, color: '#5A5A5A', id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}`, taskId: line.taskId, dutyState: line.dutyState }
              : { ...config, id: `MOCK-D-${lineIdx}-${segmentIdx}-${idx}`, road: `勤务路线路口-${lineIdx}-${segmentIdx}-${idx}`, taskId: line.taskId, dutyState: line.dutyState };
            const dotType = isPastDot && markerType === 'normal' ? 'passed' : markerType;
            const marker = this.createTrafficLightMarker([lng, lat], dotConfig, dotType);
            if (marker) overlays.push(marker);
          }

        } else {
          // 非勤务路线 或 无 dutyState：原有逻辑
          const polyline = new this.AMap.Polyline({
            path: segmentPath,
            strokeColor: line.color,
            strokeWeight: 6,
            strokeOpacity: 0.8,
            zIndex: 15
          });
          overlays.push(polyline);

          const totalPoints = segmentPath.length;

          const pathDistances = [0];
          let totalPathDist = 0;
          for (let j = 0; j < totalPoints - 1; j++) {
            const d = this.calcApproxDistance(segmentPath[j], segmentPath[j+1]);
            totalPathDist += d;
            pathDistances.push(totalPathDist);
          }

          if (configName !== '干线协调') {
            const targetSpacing = configName === '勤务路线' ? 0.0036 : 0.0018;
            let currentTargetDist = targetSpacing / 2;

            while (currentTargetDist < totalPathDist) {
              let foundIdx = 0;
              for (let j = 0; j < pathDistances.length - 1; j++) {
                if (currentTargetDist >= pathDistances[j] && currentTargetDist <= pathDistances[j + 1]) {
                  foundIdx = j;
                  break;
                }
              }
              const p1 = segmentPath[foundIdx];
              const p2 = segmentPath[foundIdx + 1];
              if (p1 && p2) {
                const ratio = (currentTargetDist - pathDistances[foundIdx]) / (pathDistances[foundIdx + 1] - pathDistances[foundIdx]);
                const midLng = Number(p1[0]) + (Number(p2[0]) - Number(p1[0])) * ratio;
                const midLat = Number(p1[1]) + (Number(p2[1]) - Number(p1[1])) * ratio;
                const bearing = this.calcBearingDeg(p1, p2);
                const rotation = bearing - 90;
                const directionMarker = new this.AMap.Marker({
                  position: [midLng, midLat],
                  content: `
                    <div style="transform: rotate(${rotation}deg); width: 20px; height: 10px; display: flex; align-items: center; pointer-events: none; opacity: 0.85;">
                      <img src="${require('@/assets/map/direction.png')}" style="width: 100%; height: auto;" />
                    </div>
                  `,
                  offset: new this.AMap.Pixel(-10, -5),
                  zIndex: 20,
                  bubble: true
                });
                overlays.push(directionMarker);
              }
              currentTargetDist += targetSpacing;
            }
          }

          const indices = this.pickEvenlySpacedIndices(totalPoints, 6);
          for (let i = 0; i < indices.length; i++) {
            const idx = indices[i];
            const p = segmentPath[idx];
            const lng = Number(p[0]);
            const lat = Number(p[1]);
            if (Number.isNaN(lng) || Number.isNaN(lat)) continue;

            let markerType = 'normal';
            if (configName !== '干线协调') {
              if (i === 0) markerType = 'start';
              else if (i === indices.length - 1) markerType = 'end';
            }

            // 干线协调：id 用干线编号，road 用干线名称（与菜单标题一致）
            const markerId = (configName === '干线协调' && line.trunkId)
              ? `${line.trunkId}_point_${i + 1}`
              : `MOCK-${configName.charAt(0)}-${lineIdx}-${segmentIdx}-${idx}`;
            const markerRoad = (configName === '干线协调' && line.trunkName)
              ? line.trunkName
              : `${configName}路口-${lineIdx}-${segmentIdx}-${idx}`;

            const marker = this.createTrafficLightMarker([lng, lat], {
              ...config,
              id: markerId,
              road: markerRoad
            }, markerType);
            if (marker) overlays.push(marker);
          }
        } // end else

      }); // end segments.forEach

      return overlays;
    },

    /**
     * 均匀选取点的索引
     * @param {number} totalPoints - 总点数
     * @param {number} count - 要选取的点数
     * @returns {Array<number>} 索引数组
     */
    pickEvenlySpacedIndices(totalPoints, count) {
      const total = Math.max(Number(totalPoints) || 0, 0);
      const target = Math.max(Number(count) || 0, 0);
      if (total <= 0 || target <= 0) return [];
      if (target >= total) return Array.from({ length: total }, (_, i) => i);
      if (target === 1) return [0];

      return Array.from({ length: target }, (_, k) => Math.round((k * (total - 1)) / (target - 1)));
    },

    /**
     * 构建备选线路路径
     * @param {Array<number>} start - 起点坐标 [lng, lat]
     * @param {Array<number>} end - 终点坐标 [lng, lat]
     * @param {number} pointCount - 点数量
     * @returns {Array} 路径点数组
     */
    buildFallbackLinePath(start, end, pointCount) {
      const sLng = Number(start && start[0]);
      const sLat = Number(start && start[1]);
      const eLng = Number(end && end[0]);
      const eLat = Number(end && end[1]);
      const n = Math.max(Number(pointCount) || 2, 2);
      const path = [];

      if ([sLng, sLat, eLng, eLat].some(v => Number.isNaN(v))) return path;

      for (let i = 0; i < n; i += 1) {
        const t = n === 1 ? 0 : i / (n - 1);
        const lng = sLng + (eLng - sLng) * t;
        const lat = sLat + (eLat - sLat) * t;
        path.push({ lng, lat });
      }
      return path;
    },

    /**
     * 提取主要直线段
     * @param {Array} path - 路径点数组
     * @returns {Array} 直线段数组
     */
    extractMainStraightSegments(path) {
      const getCoord = (p) => {
        if (!p) return { lng: NaN, lat: NaN };
        if (Array.isArray(p)) return { lng: Number(p[0]), lat: Number(p[1]) };
        if (p.getLng) return { lng: p.getLng(), lat: p.getLat() };
        return { lng: Number(p.lng), lat: Number(p.lat) };
      };

      const points = (path || []).map(p => getCoord(p)).filter(p => !isNaN(p.lng) && !isNaN(p.lat));
      if (points.length < 2) return [];

      const thresholdDeg = 18;
      const segments = [];
      let curStart = 0;
      let curAngle = null;
      let curLen = 0;

      const pushSegment = (endIdx) => {
        if (endIdx <= curStart) return;
        segments.push({
          start: curStart,
          end: endIdx,
          len: curLen
        });
      };

      for (let i = 0; i < points.length - 1; i += 1) {
        const a = points[i];
        const b = points[i + 1];
        const len = this.calcApproxDistance(a, b);
        if (len <= 0) continue;
        const angle = this.calcBearingDeg(a, b);

        if (curAngle === null) {
          curStart = i;
          curAngle = angle;
          curLen = len;
          continue;
        }

        const diff = this.calcAngleDiffDeg(curAngle, angle);
        if (diff <= thresholdDeg) {
          curLen += len;
        } else {
          pushSegment(i);
          curStart = i;
          curAngle = angle;
          curLen = len;
        }
      }

      pushSegment(points.length - 2);

      if (segments.length === 0) return [points];

      segments.sort((s1, s2) => s2.len - s1.len);
      const maxLen = segments[0].len || 0;
      const filtered = segments.filter(s => s.len >= maxLen * 0.55).slice(0, 3);
      const finalSegments = filtered.map(s => points.slice(s.start, s.end + 2));
      return finalSegments.length > 0 ? finalSegments : [points];
    },

    /**
     * 从不同格式的点中提取经纬度数组 [lng, lat]
     * @param {Object|Array} p - 点对象或数组
     * @returns {Array<number>} 经纬度数组
     */
    _getCoords(p) {
      if (!p) return [0, 0];
      const lng = p.lng || (p.getLng ? p.getLng() : (Array.isArray(p) ? Number(p[0]) : 0));
      const lat = p.lat || (p.getLat ? p.getLat() : (Array.isArray(p) ? Number(p[1]) : 0));
      return [lng, lat];
    },

    /**
     * 计算两点之间的方位角（度）
     * @param {Object|Array} a - 起点
     * @param {Object|Array} b - 终点
     * @returns {number} 方位角
     */
    calcBearingDeg(a, b) {
      const [alng, alat] = this._getCoords(a);
      const [blng, blat] = this._getCoords(b);

      const latRad = ((alat + blat) / 2) * Math.PI / 180;
      const dx = (blng - alng) * Math.cos(latRad);
      const dy = (blat - alat);
      
      const mathAngle = Math.atan2(dy, dx) * 180 / Math.PI;
      return (90 - mathAngle + 360) % 360;
    },

    /**
     * 计算两个角度的差值
     * @param {number} a - 角度1
     * @param {number} b - 角度2
     * @returns {number} 角度差
     */
    calcAngleDiffDeg(a, b) {
      let diff = Math.abs(a - b);
      if (diff > 180) diff = 360 - diff;
      return diff;
    },

    /**
     * 计算两点之间的近似距离
     * @param {Object|Array} a - 点1
     * @param {Object|Array} b - 点2
     * @returns {number} 距离
     */
    calcApproxDistance(a, b) {
      const [alng, alat] = this._getCoords(a);
      const [blng, blat] = this._getCoords(b);

      const latRad = ((alat + blat) / 2) * Math.PI / 180;
      const dx = (blng - alng) * Math.cos(latRad);
      const dy = (blat - alat);
      return Math.sqrt(dx * dx + dy * dy);
    },

    /**
     * 根据当前缩放级别计算普通圆点的尺寸（px）
     * @returns {number} 圆点尺寸
     */
    getDotSizeByZoom() {
      if (!this.map) return 14;
      const zoom = this.map.getZoom();
      // 基准：zoom=15时是20px。每缩小一级减小3px。
      const size = 20 + (zoom - 15) * 3;
      return Math.min(Math.max(6, size), 32); // 最小值设为 6px
    },

    /**
     * 缩放后重建起点/终点 marker，让高德重新计算 anchor 偏移
     */
    rebuildStartEndMarkers() {
      if (!this.map || this.startEndMarkers.length === 0) return;
      for (const entry of this.startEndMarkers) {
        const { marker, position, config, type } = entry;
        // 生成新的 content HTML（此时 CSS 变量已更新）
        const size = this.currentZoomSize;
        const specialSize = Math.max(12, size * 1.2);
        const newContent = `
          <div class="pure-light-node start-end-node" style="width: ${specialSize}px; height: ${specialSize + 6}px; background: transparent; border: none; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transform-origin: bottom center;">
            <img src="${require(`@/assets/map/${type}.png`)}" style="width: 100%; height: auto; object-fit: contain; pointer-events: none;" />
          </div>
        `;
        marker.setContent(newContent);
      }
    },

    rebuildDotMarkers() {
      if (!this.map || this.dotMarkers.length === 0) return;
      const size = this.currentZoomSize;
      const textDisplay = size >= 14 ? 'flex' : 'none';
      const textSize = `${Math.max(10, size - 4)}px`;
      for (const entry of this.dotMarkers) {
        const { marker, config, isPassed } = entry;
        if (isPassed) {
          marker.setContent(`
            <div class="pure-light-node" style="width: ${size}px; height: ${size}px; background: #5A5A5A; border: 1.5px solid rgba(255,255,255,0.25); box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; opacity: 0.55;">
              <span style="display: ${textDisplay}; font-weight: bold; font-size: ${textSize};">勤</span>
            </div>
          `);
        } else {
          const displayText = config.name ? config.name.charAt(0) : '';
          marker.setContent(`
            <div class="pure-light-node route-node" style="width: ${size}px; height: ${size}px; background: ${config.color || '#999'}; box-shadow: none; border: none; box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer;">
              <span style="display: ${textDisplay}; font-weight: bold; font-size: ${textSize};">${displayText}</span>
            </div>
          `);
        }
      }
    },


    /**
     * 创建交通信号灯标记
     * @param {Array<number>|Object} position - 位置坐标
     * @param {Object} config - 配置对象
     * @param {string} [type='normal'] - 标记类型
     * @returns {Object|null} 标记对象
     */
    createTrafficLightMarker(position, config, type = 'normal') {
      if (!position || !config) return null;

      try {
        const lng = position.getLng ? position.getLng() : Number(position[0] !== undefined ? position[0] : position.lng);
        const lat = position.getLat ? position.getLat() : Number(position[1] !== undefined ? position[1] : position.lat);
        if (isNaN(lng) || isNaN(lat)) return null;

        let displayText = config.name ? config.name.charAt(0) : '';
        if (type === 'start') displayText = '起';
        if (type === 'end') displayText = '终';

        const isAbnormal = ["离线", "降级", "故障"].includes(config.name);
        const isRoute = ["干线协调", "勤务路线"].includes(config.name);
        const isStartEnd = type === 'start' || type === 'end';
        const isPassed = type === 'passed';

        let markerContent = '';
        
        // --- 核心优化：尺寸全部使用 var(--xxx) CSS变量接管 ---
        if (isStartEnd) {
          markerContent = `
            <div class="pure-light-node start-end-node" style="width: var(--special-size); height: calc(var(--special-size) + 6px); background: transparent; border: none; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transform-origin: bottom center;">
              <img src="${require(`@/assets/map/${type}.png`)}" style="width: 100%; height: auto; object-fit: contain; pointer-events: none;" />
            </div>
          `;
        } else if (isPassed) {
          markerContent = `
            <div class="pure-light-node" style="width: var(--dot-size); height: var(--dot-size); background: #5A5A5A; border: 1.5px solid rgba(255,255,255,0.25); box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; opacity: 0.55;">
              <span style="display: var(--text-display); font-weight: bold; font-size: var(--text-size);">勤</span>
            </div>
          `;
        } else if (isAbnormal) {
          const iconName = config.name === '离线' ? 'lixian' : config.name === '降级' ? 'jiangji' : 'guzhang';
          markerContent = `
            <div class="pure-light-node breathe" style="width: var(--special-size); height: var(--special-size); background: transparent; border: none; display: flex; justify-content: center; align-items: center; cursor: pointer; padding: 0;">
              <img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />
            </div>
          `;
        } else {
          markerContent = `
            <div class="pure-light-node ${isRoute ? 'route-node' : ''}" style="width: var(--dot-size); height: var(--dot-size); background: ${config.color || '#999'}; box-shadow: ${isRoute ? 'none' : `0 0 8px ${config.color}`}; border: ${isRoute ? 'none' : '1.5px solid rgba(255,255,255,0.7)'}; box-sizing: border-box; display: flex; justify-content: center; align-items: center; color: #fff; border-radius: 50%; cursor: pointer; padding: var(--dot-padding);">
              <span style="display: var(--text-display); font-weight: bold; font-size: var(--text-size);">${displayText}</span>
            </div>
          `;
        }

        const marker = new this.AMap.Marker({
          position: [lng, lat],
          zIndex: isStartEnd ? 120 : (isAbnormal ? 110 : 100),
          content: markerContent,
          // 核心优化：高德 2.0 原生支持 anchor 属性。代替手动计算 Offset！
          anchor: isStartEnd ? 'bottom-center' : 'center', 
          extData: {
            ...config,
            position: [lng, lat],
            statusColor: config.color || '#999',
            statusLabel: config.name,
            road: config.road || '规划路口',
            timestamp: Date.now(),
            time: this.formatEventTime(Date.now())
          }
        });

        // 建立 ID 索引
        if (config.id) this.markerById[config.id] = marker;
        if (config['路口编号']) this.markerById[config['路口编号']] = marker;

        // 记录起点/终点 marker，缩放时需重建以修正 anchor 偏移
        if (isStartEnd) {
          this.startEndMarkers.push({ marker, position: [lng, lat], config, type });
        }
        // 记录勤务路线上的圆点 marker（passed + normal route），缩放时需重建
        if (!isStartEnd && isRoute) {
          this.dotMarkers.push({ marker, config, type, isPassed });
        }

        marker.on('click', (e) => {
          if (this.isComponentDestroyed) return;
          const extData = e.target.getExtData();
          if (this.$route && this.$route.path === '/home') {
            this.cancelCloseInfoWindow();
            // 视口裁剪：标记当前展开 InfoWindow 的 marker，期间豁免裁剪
            this._infoWindowProtectedMarker = e.target;
            this.openLightInfo(extData, e.lnglat);
          }
          const pixel = this.map.lngLatToContainer(e.lnglat);
          this.$emit('map-crossing-click', extData, e.lnglat, pixel);
        });

        marker.on('mouseover', (e) => {
          if (this.isComponentDestroyed) return;
          if (this.$route && this.$route.path === '/home') {
            this.cancelCloseInfoWindow();
            this._infoWindowProtectedMarker = e.target;
            this.openLightInfo(e.target.getExtData(), e.lnglat);
          }
          const pixel = this.map.lngLatToContainer(e.lnglat);
          this.$emit('map-crossing-mouseover', e.target.getExtData(), e.lnglat, pixel);
        });

        marker.on('mouseout', (e) => {
          if (this.isComponentDestroyed) return;
          if (this.$route && this.$route.path === '/home') {
            this.scheduleCloseInfoWindow();
          }
          this.$emit('map-crossing-mouseout', e.target.getExtData());
        });

        return marker;
      } catch (e) {
        console.warn('创建标记时出错:', e);
        return null;
      }
    },

    /**
     * 打开信号灯信息窗口
     * @param {Object} data - 信号灯数据
     * @param {Array<number>} position - 位置坐标
     */
    openLightInfo(data, position) {
      if (!this.isMapReady()) return;

      const infoWindowId = `info-window-${Date.now()}`;
      this.activeInfoWindowId = infoWindowId;
      const isAbnormal = ["离线", "降级", "故障"].includes(data.name);
      const deviceStatusText = isAbnormal ? data.name : '正常';
      const alarmInfoText = isAbnormal ? this.getAlarmInfoText(data.name) : '';
      const eventTimeText = this.formatEventTime(data.timestamp || data.time);
      let statusDotContent = '';
      
      if (isAbnormal) {
        const iconName = data.name === '离线' ? 'lixian' : data.name === '降级' ? 'jiangji' : 'guzhang';
        statusDotContent = `<img src="${require(`@/assets/images/icon_${iconName}.png`)}" style="width: 100%; height: 100%; object-fit: contain;" />`;
      } else {
        statusDotContent = `<span>${data.name.charAt(0)}</span>`;
      }
      
      const content = `
        <div class="custom-info-card" id="${infoWindowId}">
          <div class="close-btn" data-id="${infoWindowId}">✕</div>
          <div class="card-header">
            <div class="status-dot ${isAbnormal ? 'breathe' : ''}" style="background: ${isAbnormal ? 'transparent' : data.statusColor}; border: ${isAbnormal ? 'none' : ''}">
              ${statusDotContent}
            </div>
            <span class="status-text">${data.statusLabel}</span>
          </div>
          <div class="card-body">
            ${isAbnormal
              ? `
                <div class="info-line"><span class="label">路口名称：</span><span class="value">${data.road}</span></div>
                <div class="info-line"><span class="label">设备状态：</span><span class="value digital">${deviceStatusText}</span></div>
                <div class="info-line"><span class="label">报警信息：</span><span class="value">${alarmInfoText}</span></div>
                <div class="info-line"><span class="label">发生时间：</span><span class="value digital">${eventTimeText}</span></div>
              `
              : `
                <div class="info-line"><span class="label">路口名称：</span><span class="value">${data.road}</span></div>
                <div class="info-line"><span class="label">设备状态：</span><span class="value digital">${deviceStatusText}</span></div>
              `
            }
          </div>
        </div>
      `;

      if (!this.infoWindow) {
        this.infoWindow = new this.AMap.InfoWindow({
          isCustom: true,
          offset: new this.AMap.Pixel(0, -20),
          autoMove: false
        });
        // 视口裁剪：InfoWindow 关闭时解除 marker 保护
        this.infoWindow.on('close', () => {
          this._infoWindowProtectedMarker = null;
        });
      }

      this.infoWindow.setContent(content);
      this.infoWindow.open(this.map, position);

      setTimeout(() => {
        if (this.activeInfoWindowId !== infoWindowId) return;
        const closeBtn = document.querySelector(`#${infoWindowId} .close-btn`);
        if (closeBtn) {
          closeBtn.addEventListener('click', () => {
            if (this.infoWindow) this.infoWindow.close();
          });
        }

        const root = document.querySelector(`#${infoWindowId}`);
        if (root) {
          root.addEventListener('mouseenter', () => {
            if (this.activeInfoWindowId !== infoWindowId) return;
            this.isInfoWindowHovered = true;
            this.cancelCloseInfoWindow();
          });
          root.addEventListener('mouseleave', () => {
            if (this.activeInfoWindowId !== infoWindowId) return;
            this.isInfoWindowHovered = false;
            this.scheduleCloseInfoWindow();
          });
        }
      }, 100);
    },

    /**
     * 取消关闭信息窗口
     */
    cancelCloseInfoWindow() {
      if (this.infoCloseTimer) {
        clearTimeout(this.infoCloseTimer);
        this.infoCloseTimer = null;
      }
    },

    /**
     * 安排关闭信息窗口
     */
    scheduleCloseInfoWindow() {
      this.cancelCloseInfoWindow();
      this.infoCloseTimer = setTimeout(() => {
        if (this.isComponentDestroyed) return;
        if (this.isInfoWindowHovered) return;
        if (this.infoWindow) this.infoWindow.close();
        this.activeInfoWindowId = null;
      }, 160);
    },

    /**
     * 获取报警信息文本
     * @param {string} statusName - 状态名称
     * @returns {string} 报警信息
     */
    getAlarmInfoText(statusName) {
      if (statusName === '离线') return '通讯中断设备离线';
      if (statusName === '降级') return '降级定周期控制';
      if (statusName === '故障') return '东向左转信号灯红绿同亮';
      return '设备异常';
    },

    /**
     * 格式化事件时间
     * @param {Date|number|string} input - 时间输入
     * @returns {string} 格式化后的时间
     */
    formatEventTime(input) {
      let d = null;
      if (input instanceof Date) d = input;
      else if (typeof input === 'number') d = new Date(input);
      else if (typeof input === 'string') {
        const t = Date.parse(input);
        if (!Number.isNaN(t)) d = new Date(t);
      }
      if (!d || Number.isNaN(d.getTime())) d = new Date();
      const y = d.getFullYear();
      const m = d.getMonth() + 1;
      const day = d.getDate();
      const hh = String(d.getHours()).padStart(2, '0');
      const mm = String(d.getMinutes()).padStart(2, '0');
      return `${y}.${m}.${day} ${hh}:${mm}`;
    },

    /**
     * 切换"所有图例可见项"的开关。常隐项（hideInLegend，如 降级）始终保留显示。
     * 视口裁剪：只更新 activeLegends，实际 add/remove 由 computeVisibleMarkers 统一处理。
     */
    toggleAll() {
      if (!this.isMapReady()) return;
      const visibleNames = this.legendStatusConfig.map(i => i.name);
      const alwaysOnNames = this.statusConfig
        .filter(i => i.hideInLegend)
        .map(i => i.name);
      const targetState = !this.isAllSelected;

      if (targetState) {
        this.activeLegends = Array.from(new Set([...alwaysOnNames, ...visibleNames]));
      } else {
        this.activeLegends = [...alwaysOnNames];
        if (this.infoWindow) this.infoWindow.close();
      }
      this.computeVisibleMarkers();
    },

    /**
     * 切换指定路线的可见性。视口裁剪：仅更新 activeLegends，由调度器决定 add/remove。
     * @param {string} name - 路线名称
     */
    toggleRouteVisible(name) {
      if (!this.isMapReady()) return;

      const index = this.activeLegends.indexOf(name);
      if (index > -1) {
        this.activeLegends.splice(index, 1);
        if (this.infoWindow) this.infoWindow.close();
      } else {
        this.activeLegends.push(name);
      }
      this.computeVisibleMarkers();
    },

    /**
     * 根据位置聚焦地图
     * @param {string|Array<number>} targetPos - 目标位置
     */
    focusByLocation(targetPos) {
      if (!this.isMapReady() || !targetPos) return;

      let pos = targetPos;
      if (typeof targetPos === 'string') {
        pos = targetPos.split(',').map(Number);
      }
      if (!Array.isArray(pos) || pos.length < 2) return;

      const [targetLng, targetLat] = pos;
      let bestMarker = null;
      let minDistanceSq = Infinity;

      Object.values(this.routeGroups).forEach(group => {
        if (!Array.isArray(group)) return;
        group.forEach(item => {
          if (!(item instanceof this.AMap.Marker)) return;
          const markerExt = item.getExtData();
          const markerPos = markerExt.position;
          if (!markerPos) return;

          const dx = markerPos[0] - targetLng;
          const dy = markerPos[1] - targetLat;
          const distSq = dx * dx + dy * dy;

          if (distSq < 0.000001) {
            const isAbnormal = ["离线", "降级", "故障"].includes(markerExt.name);
            const currentIsAbnormal = bestMarker ? ["离线", "降级", "故障"].includes(bestMarker.getExtData().name) : false;

            if (distSq < minDistanceSq || (isAbnormal && !currentIsAbnormal)) {
              minDistanceSq = distSq;
              bestMarker = item;
            }
          }
        });
      });

      if (bestMarker) {
        const finalPos = bestMarker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500);
        setTimeout(() => {
          if (!this.isComponentDestroyed) this.openLightInfo(bestMarker.getExtData(), finalPos);
        }, 600);
      } else {
        this.map.setZoomAndCenter(17, [targetLng, targetLat], false, 500);
      }
    },

    /**
     * 通过路口编号定位到对应的标记
     * @param {string} id - 路口编号
     * @returns {Array<number>|null} 位置坐标
     */
    focusById(id) {
      if (!this.isMapReady() || !id) return null;

      const marker = this.markerById[id];
      if (marker) {
        const finalPos = marker.getPosition();
        this.map.setZoomAndCenter(17, finalPos, false, 500);
        return finalPos;
      }
      return null;
    },

    /**
     * 搜索框选中回调：定位 + 立即触发视口重算（避免 100ms debounce 延迟），
     * 让目标 marker 在 setZoomAndCenter 动画期间就完成挂载。
     * Home 页另在飞行结束后弹出该路口的 InfoWindow，与 marker click 行为一致。
     */
    onSearchSelect(item) {
      if (!item) return;
      const id = item['路口编号'];
      const finalPos = this.focusById(id);
      this.computeVisibleMarkers();

      if (!finalPos) return;
      if (!(this.$route && this.$route.path === '/home')) return;
      const marker = this.markerById[id];
      if (!marker) return;
      setTimeout(() => {
        if (this.isComponentDestroyed) return;
        this._infoWindowProtectedMarker = marker;
        this.openLightInfo(marker.getExtData(), finalPos);
      }, 600);
    },

    /**
     * 切换图例的可见性
     */
    toggleLegend() {
      this.legendVisible = !this.legendVisible;
    },

    /**
     * 按4:4:4比例提取故障、离线、降级路口信息并存储到localStorage
     */
    storeStatusCoordsToLocalStorage() {
      const alarmTypes = [
        { status: "故障", titles: ["通讯中断", "灯组故障", "相位冲突", "绿冲突"], level: "high", type: "error" },
        { status: "离线", titles: ["信号机离线", "信号机离线", "通讯中断", "检测器异常"], level: "mid", type: "warning" },
        { status: "降级", titles: ["降级黄闪", "降级黄闪", "方案切换异常", "检测器异常"], level: "mid", type: "warning" },
      ];

      const alarmList = [];
      let id = 1;

      alarmTypes.forEach(({ status, titles, level, type }) => {
        (this.statusIntersections[status] || []).slice(0, 4).forEach((item, i) => {
          const lng = item["位置-经度"];
          const lat = item["位置-纬度"];
          const name = item["路口名称"] || "";
          if (!lng || !lat) return;
          alarmList.push({
            id: `A${String(id).padStart(3, "0")}`,
            title: titles[i] || titles[0],
            loc: name,
            level,
            type,
            description: `${name}-${titles[i] || titles[0]}`,
            position: [lng, lat],
          });
          localStorage.setItem(`pos${id}`, `${lng},${lat}`);
          id++;
        });
      });

      localStorage.setItem("alarmListFromMap", JSON.stringify(alarmList));
      console.log('状态坐标及告警数据已存储到localStorage');
    },

    /**
     * 将经纬度转换为像素坐标
     * @param {number} lng - 经度
     * @param {number} lat - 纬度
     * @returns {Object|null} 像素坐标
     */
    lngLatToPixel(lng, lat) {
        if (!this.map) return null;
        return this.map.lngLatToContainer([lng, lat]);
    },

    /**
     * 对外暴露：为指定子区路口列表绘制凸包多边形蒙层，点击不同子区时自动替换上一个
     * @param {Array<{lng: number, lat: number}>} leaves - 子区内所有叶子路口节点
     */
    drawSubAreaCircle(leaves, label) {
      if (!this.isMapReady() || !leaves || leaves.length === 0) return;

      this._subAreaParams = { leaves, label };
      this.clearSubAreaOverlays();

      const pts = leaves.map(n => [Number(n.lng), Number(n.lat)]);
      if (pts.length < 3) return;

      const hull = this._convexHull(pts);
      if (hull.length < 3) return;

      // 以凸包重心为基准，向外扩展 10% 留出视觉间距
      const cx = hull.reduce((s, p) => s + p[0], 0) / hull.length;
      const cy = hull.reduce((s, p) => s + p[1], 0) / hull.length;
      const paddedHull = hull.map(p => [
        cx + (p[0] - cx) * 1.1,
        cy + (p[1] - cy) * 1.1,
      ]);

      const polygon = new this.AMap.Polygon({
        path: paddedHull,
        fillColor: '#4A9EFF',
        fillOpacity: 0.15,
        strokeColor: '#4A9EFF',
        strokeOpacity: 0.6,
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [4, 4],
        zIndex: 10,
        bubble: true,
      });

      this.subAreaOverlays.push(polygon);
      this.map.add(polygon);

      // 在凸包重心位置显示子区名称（水印风格，字号随区域大小缩放）
      if (label) {
        // 用地图坐标转像素，精确计算区域在屏幕上的实际大小
        const lngs = paddedHull.map(p => p[0]);
        const lats = paddedHull.map(p => p[1]);
        const topLeft = this.map.lngLatToContainer([Math.min(...lngs), Math.max(...lats)]);
        const bottomRight = this.map.lngLatToContainer([Math.max(...lngs), Math.min(...lats)]);
        const pixelW = Math.abs(bottomRight.x - topLeft.x);
        const pixelH = Math.abs(bottomRight.y - topLeft.y);
        // 字号同时受宽度和高度约束，取较小值确保不超出区域
        const charCount = label.length || 1;
        const sizeByW = Math.round(pixelW * 0.8 / (charCount + 1));
        const sizeByH = Math.round(pixelH * 0.6);
        const fontSize = Math.min(Math.max(10, Math.min(sizeByW, sizeByH)), 48);

        // 缩放过小时隐藏文字
        if (fontSize < 10) {
          // 不绘制文字
        } else {
        const text = new this.AMap.Text({
          text: label,
          position: [cx, cy],
          anchor: 'center',
          zIndex: 11,
          style: {
            'background': 'transparent',
            'border': 'none',
            'color': 'rgba(255, 255, 255, 0.25)',
            'font-size': `${fontSize}px`,
            'font-weight': 'bold',
            'padding': '0',
            'letter-spacing': fontSize >= 16 ? '2px' : '0px',
            'white-space': 'nowrap',
            'pointer-events': 'none',
          },
        });
        this.subAreaOverlays.push(text);
        this.map.add(text);
        }
      }
    },

    /**
     * Graham Scan 凸包算法
     * @param {Array<[number, number]>} points - 经纬度点数组
     * @returns {Array<[number, number]>} 凸包顶点（逆时针）
     */
    _convexHull(points) {
      if (points.length < 3) return [...points];

      const p0 = points.reduce((best, p) =>
        p[1] < best[1] || (p[1] === best[1] && p[0] < best[0]) ? p : best
      );

      const cross = (o, a, b) =>
        (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);

      const dist2 = (a, b) =>
        (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;

      const sorted = points
        .filter(p => p !== p0)
        .sort((a, b) => {
          const c = cross(p0, a, b);
          if (c !== 0) return c > 0 ? -1 : 1;
          return dist2(p0, a) - dist2(p0, b);
        });

      const hull = [p0];
      for (const p of sorted) {
        while (hull.length >= 2 && cross(hull[hull.length - 2], hull[hull.length - 1], p) <= 0) {
          hull.pop();
        }
        hull.push(p);
      }
      return hull;
    },

    /**
     * 清除子区圆形蒙层
     */
    rebuildSubAreaText() {
      if (!this._subAreaParams) return;
      const { leaves, label } = this._subAreaParams;
      // 保留参数，重绘整个子区（包含字号重新计算）
      this.drawSubAreaCircle(leaves, label);
    },

    clearSubAreaOverlays() {
      if (this.map && this.subAreaOverlays.length > 0) {
        try { this.map.remove(this.subAreaOverlays); } catch (e) { void e; }
        this.subAreaOverlays = [];
      }
    },
  }
};
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: 100vh;
  position: relative;
  background: #010813;
}

.map-container {
  width: 100%;
  height: 100%;
}

::v-deep .amap-logo,
::v-deep .amap-copyright,
::v-deep .amap-copyright-logo {
  display: none !important;
}

::v-deep .pure-light-node.breathe {
  animation: light-breathe 2s infinite ease-in-out;
}

::v-deep .pure-light-node span {
  display: flex;
  transform: scale(0.75);
  align-items: center;
}

::v-deep .pure-light-node:hover {
  transform: scale(1.4);
  filter: brightness(1.2);
}

@keyframes light-breathe {
  0% {
    transform: scale(0.9);
    opacity: 0.8;
  }

  50% {
    transform: scale(1.1);
    opacity: 1;
  }

  100% {
    transform: scale(0.9);
    opacity: 0.8;
  }
}

::v-deep .close-btn {
  position: absolute;
  top: 10px;
  right: 12px;
  color: #8da6c7;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.3s;
  line-height: 1;
  z-index: 10;
}

::v-deep .close-btn:hover {
  color: #ffffff;
}

::v-deep .custom-info-card {
  position: relative;
  background: rgba(10, 15, 24, 0.95);
  border-radius: 10px;
  padding: 12px 16px;
  min-width: 200px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  color: #fff;
}

::v-deep .card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

::v-deep .status-dot {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 8px;
  font-size: 14px;
  padding: 0;
  box-sizing: border-box;
}

::v-deep .status-dot.breathe {
  animation: light-breathe 2s infinite ease-in-out;
}

::v-deep .status-dot span {
  transform: scale(0.75);
}

::v-deep .status-dot img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

::v-deep .status-text {
  font-size: 15px;
  font-weight: bold;
}

::v-deep .info-line {
  display: flex;
  margin-bottom: 6px;
  font-size: 13px;
  align-items: center;
}

::v-deep .label {
  color: #8da6c7;
  white-space: nowrap;
}

::v-deep .value {
  color: #ffffff;
}

::v-deep .digital {
  font-family: 'Consolas', monospace;
}

.map-legend {
  position: absolute;
  bottom: 30px;
  right: 40px;
  background: rgba(5, 22, 45, 0.9);
  border: 1px solid #1e4d8e;
  padding: 15px;
  border-radius: 6px;
  z-index: 100;
  transition: all 0.3s ease-in-out;
  opacity: 1;
  max-width: 200px;
  overflow: hidden;
}

.map-legend.legend-hidden {
  opacity: 0;
  transform: translateX(calc(100% + 20px));
  pointer-events: none;
}

.legend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  border-bottom: 1px solid #1e4d8e;
  padding-bottom: 8px;
}

.legend-close-btn {
  color: #8da6c7;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.3s;
  line-height: 1;
}

.legend-close-btn:hover {
  color: #ffffff;
}

.legend-show-btn {
  position: absolute;
  bottom: 30px;
  right: 20px;
  background: rgba(30, 86, 168, 0.92);
  border: 1px solid #5892ff;
  width: 40px;
  height: 40px;
  border-radius: 6px 0 0 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 99;
  box-shadow: 0 0 12px rgba(88, 146, 255, 0.7);
  transition: all 0.3s ease-in-out;
}

.legend-show-btn:hover {
  background: rgba(58, 117, 196, 0.95);
  border-color: #8db4ff;
  box-shadow: 0 0 16px rgba(88, 146, 255, 0.9);
}

.legend-show-icon {
  color: #ffffff;
  font-size: 18px;
  transition: color 0.3s;
}

.legend-show-btn:hover .legend-show-icon {
  color: #ffffff;
}

.legend-title {
  color: #fff;
  font-size: 14px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  cursor: pointer;
  transition: 0.3s;
}

.legend-item.is-inactive {
  opacity: 0.7;
  filter: grayscale(1);
}

.legend-dot {
  margin-right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.legend-dot:not(.is-status-wrapper) {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.legend-dot span {
  display: inline-block;
  width: 20px;
  height: 20px;
  font-size: 12px;
  color: #FFF;
  text-align: center;
  transform: scale(0.75);
  line-height: 20px;
}

.legend-dot.special-route {
  position: relative;
  overflow: visible !important;
  z-index: 1;
  border: none !important;
  border-radius: 50%;
}

.legend-dot.special-route span {
  position: relative;
  z-index: 3;
  font-weight: bold;
}

.legend-dot.special-route::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 150%;
  height: 3px;
  background-color: inherit;
  opacity: 0.8;
  transform: translate(-50%, -50%) rotate(-45deg);
  pointer-events: none;
  z-index: 0;
}

.legend-dot.special-route::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  z-index: 2;
  background-color: inherit;
  opacity: 1;
}

.legend-label {
  flex: 1;
  color: #d0d9e2;
  font-size: 13px;
}

.legend-status {
  font-size: 11px;
  color: #5b7da8;
}

.all-select {
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 12px;
  margin-bottom: 12px !important;
}

.all-select .legend-dot {
  border-radius: 2px;
  transition: all 0.3s;
  width: 10px;
  height: 10px;
}

.all-select .legend-dot.all-select-dot {
  width: 14px;
  height: 14px;
  border-radius: 3px;
  border: 1px solid #fff;
  background: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: none;
}

.all-select .legend-dot.all-select-dot.is-checked {
  background: #1890ff;
  border-color: #1890ff;
}

.all-select .check-icon {
  display: block;
  width: 6px;
  height: 9px;
  border: solid #fff;
  border-width: 0 2px 2px 0;
  transform: translateY(-1px) rotate(45deg);
  transform-origin: center;
}

.legend-dot.is-status-wrapper {
  width: 28px;
  height: 28px;
  background-color: transparent !important;
  box-shadow: none !important;
  border: none !important;
  margin-right: 0;
  transform: translateX(-15%);
}

.status-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

::v-deep .pure-light-node {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  pointer-events: auto;
}

::v-deep .pure-light-node.route-node {
  position: relative;
  overflow: visible;
}

::v-deep .pure-light-node.route-node::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 150%;
  height: 3px;
  background-color: inherit;
  opacity: 0.8;
  transform: translate(-50%, -50%) rotate(-45deg);
  pointer-events: none;
}

::v-deep .pure-light-node.route-node span {
  position: relative;
  z-index: 1;
}

::v-deep .pure-light-node:not(.abnormal-node) {
  border: 1px solid rgba(255, 255, 255, 0.4);
}

::v-deep .duty-progress-node {
  animation: duty-pulse 1.6s infinite ease-in-out;
}

@keyframes duty-pulse {
  0%   { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
  50%  { box-shadow: 0 0 0 9px rgba(188, 48, 29, 0.08); }
  100% { box-shadow: 0 0 0 3px rgba(188, 48, 29, 0.5); }
}
</style>
