<template>
  <div class="map-page">
    <!-- ═══ 地图初始化状态 ═══ -->
    <div v-if="loading" class="map-status">⏳ 地图加载中...</div>
    <div v-else-if="error" class="map-status map-error">❌ {{ error }}</div>

    <!-- ═══ 🚨 越界报警浮层 ═══ -->
    <div v-if="alarmActive" class="alarm-overlay" @click="dismissAlarm">
      <div class="alarm-box">
        <div class="alarm-icon">🚨</div>
        <div class="alarm-content">
          <div class="alarm-title">电子围栏报警！</div>
          <div class="alarm-desc">
            老人已离开安全区域
            <br />
            <span v-if="alarmCount > 1">（累计越界 {{ alarmCount }} 次）</span>
          </div>
          <div class="alarm-hint">点击任意处解除警报</div>
        </div>
      </div>
    </div>

    <!-- ═══ 围栏内/外状态标签 ═══ -->
    <div
      v-if="hasPerson && hasFence && !isDrawing"
      class="fence-status"
      :class="alarmActive ? 'fence-status--alarm' : 'fence-status--safe'"
    >
      {{ alarmActive ? '🚨 老人已越界！' : '✅ 老人在安全区域内' }}
    </div>

    <!-- ═══ 地图容器 ═══ -->
    <div
      ref="containerRef"
      class="map-container"
      :class="{ 'map-hidden': loading || error }"
    />

    <!-- ═══ 底部控制栏 ═══ -->
    <div class="map-controls">
      <!-- ── 第一行：围栏操作 ── -->
      <div class="controls-row">
        <span class="map-title">🗺️ 电子围栏</span>
        <div class="map-actions">
          <!-- 绘制按钮 -->
          <button
            :disabled="!mapInstance || isDrawing"
            @click="startDrawPolygon"
            title="点击地图添加顶点 → 点击首顶点(红色①)闭合 → 或点击「闭合」按钮"
          >
            {{ isDrawing && fenceType === 'polygon' ? '⏳ 绘制中...' : '🔷 绘制围栏' }}
          </button>
          <button
            :disabled="!mapInstance || isDrawing"
            @click="startDrawCircle"
            title="第一次点击确定圆心，第二次点击确定半径"
          >
            {{ isDrawing && fenceType === 'circle' ? '⏳ 绘制中...' : '⭕ 圆形围栏' }}
          </button>

          <!-- ✅ 闭合围栏按钮（多边形绘制中 + 已添加 3+ 顶点） -->
          <button
            v-if="isDrawing && fenceType === 'polygon' && drawVertexCount >= 3"
            class="btn-finish"
            @click="finishDraw"
          >
            ✅ 闭合围栏（{{ drawVertexCount }}点）
          </button>

          <!-- 绘制中 → 取消 -->
          <button
            v-if="isDrawing"
            class="btn-cancel"
            @click="cancelDraw"
          >
            ❌ 取消
          </button>

          <!-- 清除围栏 -->
          <button
            v-if="hasFence && !isDrawing"
            class="btn-danger"
            @click="clearFence"
          >
            🗑️ 清除围栏
          </button>
        </div>
      </div>

      <!-- ── 绘制提示条（正在绘制时显示）── -->
      <div v-if="isDrawing" class="controls-row draw-hint-row">
        <span class="draw-hint">
          <template v-if="fenceType === 'polygon'">
            🎯 点击地图添加顶点 &nbsp;|&nbsp;
            <strong>点击红色 ① 号首顶点</strong> 或 <strong>「闭合围栏」按钮</strong> 完成 &nbsp;|&nbsp;
            右键取消 &nbsp;|&nbsp;
            已添加 <strong>{{ drawVertexCount }}</strong> 个点
            <span v-if="drawVertexCount >= 3" class="draw-hint-ok"> ✅ 可以闭合了！</span>
            <span v-else class="draw-hint-min">（至少还需要 {{ 3 - drawVertexCount }} 个点）</span>
          </template>
          <template v-else-if="fenceType === 'circle'">
            🎯 <strong>第 1 步</strong>：点击地图设置圆心 &nbsp;|&nbsp;
            <strong>第 2 步</strong>：再次点击设定半径 &nbsp;|&nbsp;
            右键取消
          </template>
        </span>
      </div>


      <!-- ── 第二行：老人标记操作 ── -->
      <div class="controls-row">
        <span class="controls-label">👴 老人控制</span>
        <div class="map-actions">
          <button
            v-if="!hasPerson"
            :disabled="!mapInstance || isDrawing"
            @click="addPerson"
          >
            ➕ 添加老人
          </button>
          <template v-else>
            <div class="dpad">
              <button class="dpad-btn dpad-up" :disabled="isDrawing" @click="movePerson('up')" title="向北移动">↑</button>
              <button class="dpad-btn dpad-left" :disabled="isDrawing" @click="movePerson('left')" title="向西移动">←</button>
              <button class="dpad-btn dpad-right" :disabled="isDrawing" @click="movePerson('right')" title="向东移动">→</button>
              <button class="dpad-btn dpad-down" :disabled="isDrawing" @click="movePerson('down')" title="向南移动">↓</button>
            </div>
            <span class="hint-text">或拖拽地图上的 👴 标记</span>
            <button class="btn-danger" @click="removePerson">🗑️ 移除</button>
          </template>
        </div>
      </div>

      <!-- ── 第三行：标记起点 / 终点 ── -->
      <div class="controls-row">
        <span class="controls-label">
          📍🏁 标记
          <span v-if="hasOrigin && hasDest && !isPlanning" class="route-ready">● 就绪</span>
          <span v-if="isPlanning" class="route-planning">⏳</span>
        </span>
        <div class="map-actions">
          <!-- 标记起点 -->
          <button
            v-if="!settingMode"
            :disabled="isPlanning || isAnimating || isDrawing"
            @click="enterSetMode('origin')"
          >
            📍 标记起点
          </button>
          <button v-else-if="settingMode === 'origin'" class="btn-finish" @click="exitSetMode">
            📍 点击地图放起点...
          </button>

          <!-- 标记终点 -->
          <button
            v-if="!settingMode"
            :disabled="isPlanning || isAnimating || isDrawing"
            @click="enterSetMode('dest')"
          >
            🏁 标记终点
          </button>
          <button v-else-if="settingMode === 'dest'" class="btn-finish" @click="exitSetMode">
            🏁 点击地图放终点...
          </button>

          <!-- 清除已放的点 -->
          <button v-if="hasOrigin && !settingMode" class="btn-reset" :disabled="isAnimating" @click="removeOrigin()">
            清起点
          </button>
          <button v-if="hasDest && !settingMode" class="btn-reset" :disabled="isAnimating" @click="removeDest()">
            清终点
          </button>
        </div>
      </div>

      <!-- ── 第四行：护理员 + 路线 + 动画 ── -->
      <div class="controls-row">
        <span class="controls-label">
          👩‍⚕️ 路线
          <span v-if="!hasCaregiver && hasOrigin" class="route-planning">（未添加护理员）</span>
        </span>
        <div class="map-actions">
          <!-- 护理员 -->
          <button
            v-if="!hasCaregiver"
            :disabled="!mapInstance || isDrawing"
            @click="addCaregiver"
          >
            ➕ 添加护理员
          </button>
          <button v-else class="btn-reset" :disabled="isAnimating" @click="removeCaregiver()">
            移除护理员
          </button>

          <!-- 规划路线 -->
          <button
            :disabled="!canPlanRoute || isDrawing"
            class="btn-route"
            @click="planRoute"
          >
            {{ isPlanning ? '⏳' : '🚗' }} 规划路线
          </button>

          <!-- 路线摘要 -->
          <span v-if="routeInfo" class="route-summary">{{ (routeInfo.distance / 1000).toFixed(0) }}km</span>

          <!-- 动画 -->
          <template v-if="hasRoute">
            <button v-if="!isAnimating" class="btn-start" :disabled="isDrawing" @click="startAnimation">
              ▶ 出发
            </button>
            <button v-else class="btn-cancel" @click="stopAnimation">
              ⏹ 暂停
            </button>
            <button
              v-if="!isAnimating && animProgress > 0 && animProgress < 1"
              class="btn-reset" @click="resetToOrigin"
            >
              🔄 回起点
            </button>
          </template>

          <!-- 全部清除 -->
          <button class="btn-danger" :disabled="isAnimating" @click="clearAll()">
            🗑️ 清除
          </button>
        </div>
      </div>

      <!-- ── 标记模式提示条 ── -->
      <div v-if="settingMode" class="controls-row draw-hint-row">
        <span class="draw-hint">
          🎯 <strong>点击地图</strong>放置{{ settingMode === 'origin' ? '起点(📍)' : '终点(🏁)' }}标记 &nbsp;|&nbsp; 再次点击按钮取消
        </span>
      </div>

      <!-- ── 动画进度条 ── -->
      <div v-if="isAnimating" class="route-progress-bar">
        <div class="route-progress-fill" :style="{ width: (animProgress * 100).toFixed(1) + '%' }" />
        <span class="route-progress-text">👩‍⚕️ 护理员移动中... {{ (animProgress * 100).toFixed(0) }}%</span>
      </div>
    </div>

    <!-- ═══ 报警历史侧边信息（桌面端） ═══ -->
    <div v-if="alarmHistory.length > 0" class="alarm-log">
      <div class="alarm-log-title">📋 报警记录</div>
      <div
        v-for="(record, i) in alarmHistory"
        :key="i"
        class="alarm-log-item"
      >
        <span class="alarm-log-time">{{ record.time }}</span>
        <span class="alarm-log-pos">
          [{{ record.position[0].toFixed(4) }}, {{ record.position[1].toFixed(4) }}]
        </span>
      </div>
      <button class="alarm-log-clear" @click="alarmHistory.length = 0; alarmCount = 0">
        清空记录
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, nextTick, onUnmounted } from 'vue'
import { useAmap } from '@/composables/useAmap'
import { useGeofence } from '@/composables/useGeofence'
import { useRouteTrack } from '@/composables/useRouteTrack'

// ═══ 地图初始化 ═══
const { containerRef, mapInstance, loading, error, initMap } = useAmap({
  center: [116.397428, 39.90923],
  zoom: 15,       // 围栏场景用更大比例尺
  pitch: 0,       // 2D 俯视图更便于绘制
})

void containerRef

async function bootstrapMap() {
  const map = await initMap()
  if (map) {
    nextTick(() => map.resize())
  }
}
onMounted(() => bootstrapMap())

// ═══ 电子围栏 ═══
const {
  fenceType,
  isDrawing,
  drawVertexCount,
  isInside,
  alarmActive,
  alarmCount,
  alarmHistory,
  hasFence,
  hasPerson,
  startDrawPolygon,
  startDrawCircle,
  finishDraw,
  cancelDraw,
  clearFence,
  addPerson,
  removePerson,
  movePerson,
  dismissAlarm,
  destroyGeofence,
} = useGeofence(mapInstance)

// ═══ 护理员轨迹 ═══
const {
  routeInfo,
  isPlanning,
  isAnimating,
  animProgress,
  settingMode,
  hasCaregiver,
  hasRoute,
  hasOrigin,
  hasDest,
  canPlanRoute,
  enterSetMode,
  exitSetMode,
  addCaregiver,
  removeCaregiver,
  removeOrigin,
  removeDest,
  planRoute,
  clearRoute,
  startAnimation,
  stopAnimation,
  resetToOrigin,
  clearAll,
  destroyRouteTrack,
} = useRouteTrack(mapInstance)

// ═══ 生命周期清理 ═══
onUnmounted(() => {
  destroyGeofence()
  destroyRouteTrack()
})
</script>

<style scoped>
/* ═══════════════════════════════════════════
   地图页面布局
   ═══════════════════════════════════════════ */
.map-page {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

/* ── 状态浮层 ── */
.map-status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  padding: 14px 24px;
  text-align: center;
  font-size: 14px;
  color: #666;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.map-error {
  color: #e74c3c;
  background: #fef2f2;
  border: 1px solid #fecaca;
}

/* ── 地图容器 ── */
.map-container {
  flex: 1;
  width: 100%;
  min-height: 0;
}

.map-hidden {
  visibility: hidden;
}

/* ═══════════════════════════════════════════
   🚨 越界报警浮层
   ═══════════════════════════════════════════ */
.alarm-overlay {
  position: absolute;
  inset: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 0, 0, 0.08);
  cursor: pointer;
  animation: alarm-bg-pulse 1s ease-in-out infinite;
}

@keyframes alarm-bg-pulse {
  0%, 100% { background: rgba(255, 0, 0, 0.04); }
  50%      { background: rgba(255, 0, 0, 0.12); }
}

.alarm-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 32px 48px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  box-shadow: 0 8px 40px rgba(255, 0, 0, 0.25);
  border: 2px solid #FF4D4F;
  animation: alarm-box-shake 0.4s ease-in-out;
}

@keyframes alarm-box-shake {
  0%, 100% { transform: translateX(0); }
  20%      { transform: translateX(-6px); }
  40%      { transform: translateX(6px); }
  60%      { transform: translateX(-4px); }
  80%      { transform: translateX(4px); }
}

.alarm-icon {
  font-size: 48px;
  animation: alarm-icon-pulse 0.6s ease-in-out infinite alternate;
}

@keyframes alarm-icon-pulse {
  from { transform: scale(1); }
  to   { transform: scale(1.15); }
}

.alarm-content {
  text-align: center;
}

.alarm-title {
  font-size: 22px;
  font-weight: 700;
  color: #FF4D4F;
  margin-bottom: 6px;
}

.alarm-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.alarm-hint {
  margin-top: 10px;
  font-size: 12px;
  color: #aaa;
}

/* ═══════════════════════════════════════════
   围栏状态标签
   ═══════════════════════════════════════════ */
.fence-status {
  position: absolute;
  top: 12px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 800;
  padding: 6px 18px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  pointer-events: none;
  transition: all 0.3s;
}

.fence-status--safe {
  background: rgba(66, 184, 131, 0.12);
  color: #2e7d32;
  border: 1px solid rgba(66, 184, 131, 0.3);
}

.fence-status--alarm {
  background: rgba(255, 77, 79, 0.12);
  color: #c62828;
  border: 1px solid rgba(255, 77, 79, 0.3);
  animation: status-alarm-pulse 0.6s ease-in-out infinite alternate;
}

@keyframes status-alarm-pulse {
  from { opacity: 1; }
  to   { opacity: 0.5; }
}

/* ═══════════════════════════════════════════
   底部控制栏（双行）
   ═══════════════════════════════════════════ */
.map-controls {
  display: flex;
  flex-direction: column;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.04);
  flex-shrink: 0;
  z-index: 5;
}

.controls-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  gap: 12px;
}

.controls-row + .controls-row {
  border-top: 1px solid #f0f0f0;
  padding-top: 6px;
  padding-bottom: 6px;
}

.map-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
}

.controls-label {
  font-size: 13px;
  font-weight: 600;
  color: #555;
  white-space: nowrap;
}

.map-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* ── 通用按钮 ── */
.map-actions button {
  padding: 6px 14px;
  border: 1px solid #42b883;
  border-radius: 6px;
  background: #fff;
  color: #42b883;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.map-actions button:hover:not(:disabled) {
  background: #42b883;
  color: #fff;
}

.map-actions button:disabled {
  opacity: 0.35;
  cursor: not-allowed;
}

.btn-cancel {
  border-color: #faad14 !important;
  color: #faad14 !important;
}

.btn-cancel:hover:not(:disabled) {
  background: #faad14 !important;
  color: #fff !important;
}

.btn-finish {
  border-color: #42b883 !important;
  background: #42b883 !important;
  color: #fff !important;
  font-weight: 600;
  animation: btn-finish-pulse 0.8s ease-in-out infinite alternate;
}

@keyframes btn-finish-pulse {
  from { box-shadow: 0 0 0 rgba(66, 184, 131, 0); }
  to   { box-shadow: 0 0 12px rgba(66, 184, 131, 0.5); }
}

.btn-finish:hover:not(:disabled) {
  background: #38a978 !important;
  border-color: #38a978 !important;
}

.btn-danger {
  border-color: #FF4D4F !important;
  color: #FF4D4F !important;
}

.btn-danger:hover:not(:disabled) {
  background: #FF4D4F !important;
  color: #fff !important;
}

.hint-text {
  font-size: 11px;
  color: #aaa;
  white-space: nowrap;
}

/* ── 绘制提示条 ── */
.draw-hint-row {
  background: #f0faf5;
  border-top: 1px solid #d0ede0;
}

.draw-hint {
  font-size: 12px;
  color: #555;
  line-height: 1.6;
}

.draw-hint strong {
  color: #42b883;
}

.draw-hint-ok {
  color: #2e7d32;
  font-weight: 600;
}

.draw-hint-min {
  color: #faad14;
}

/* ── 方向键 ── */
.dpad {
  display: grid;
  grid-template-areas:
    ".    up   ."
    "left .    right"
    ".    down .";
  grid-template-columns: repeat(3, 32px);
  grid-template-rows: repeat(3, 32px);
  gap: 2px;
}

.dpad-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fafafa;
  color: #555;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.15s;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.dpad-btn:hover:not(:disabled) {
  background: #42b883;
  border-color: #42b883;
  color: #fff;
}

.dpad-btn:disabled {
  opacity: 0.25;
  cursor: not-allowed;
}

.dpad-up    { grid-area: up; }
.dpad-left  { grid-area: left; }
.dpad-right { grid-area: right; }
.dpad-down  { grid-area: down; }

/* ═══════════════════════════════════════════
   报警历史侧边记录
   ═══════════════════════════════════════════ */
.alarm-log {
  position: absolute;
  right: 12px;
  bottom: 130px;
  z-index: 700;
  width: 200px;
  max-height: 180px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 10px;
  font-size: 12px;
}

.alarm-log-title {
  font-weight: 600;
  color: #FF4D4F;
  margin-bottom: 6px;
  font-size: 13px;
}

.alarm-log-item {
  display: flex;
  justify-content: space-between;
  padding: 3px 0;
  border-bottom: 1px solid #f5f5f5;
}

.alarm-log-time {
  color: #888;
}

.alarm-log-pos {
  color: #555;
  font-family: monospace;
  font-size: 10px;
}

.alarm-log-clear {
  margin-top: 6px;
  width: 100%;
  padding: 4px 0;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background: #fff;
  color: #999;
  font-size: 11px;
  cursor: pointer;
}

.alarm-log-clear:hover {
  background: #f5f5f5;
  color: #666;
}

/* ── 路线按钮 ── */
.btn-route {
  border-color: #4A90D9 !important;
  color: #4A90D9 !important;
}

.btn-route:hover:not(:disabled) {
  background: #4A90D9 !important;
  color: #fff !important;
}

.btn-start {
  border-color: #27ae60 !important;
  background: #27ae60 !important;
  color: #fff !important;
  font-weight: 600;
}

.btn-start:hover:not(:disabled) {
  background: #219a52 !important;
}

.btn-reset {
  border-color: #95a5a6 !important;
  color: #95a5a6 !important;
}

.btn-reset:hover:not(:disabled) {
  background: #95a5a6 !important;
  color: #fff !important;
}

.route-summary {
  font-size: 12px;
  color: #4A90D9;
  font-weight: 600;
  white-space: nowrap;
}

.route-ready {
  font-size: 11px;
  color: #27ae60;
  margin-left: 4px;
}

.route-planning {
  font-size: 11px;
  color: #faad14;
  margin-left: 4px;
  animation: status-alarm-pulse 0.6s ease-in-out infinite alternate;
}

/* ── 动画进度条 ── */
.route-progress-bar {
  position: relative;
  height: 22px;
  background: #e8f0fe;
  border-radius: 0;
  overflow: hidden;
}

.route-progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4A90D9, #357ABD);
  transition: width 0.04s linear;
  border-radius: 0;
}

.route-progress-text {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 600;
  color: #2c5f8a;
  mix-blend-mode: multiply;
}
</style>

<!-- AMap 自定义 Marker 全局样式（不能 scoped，因为 Marker DOM 由 AMap 直接注入） -->
<style>
/* ── 普通顶点标记 ── */
.geofence-vertex-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #42b883;
  border: 2px solid #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
  font-size: 8px;
  color: #fff;
  text-align: center;
  line-height: 12px;
  user-select: none;
}

/* ── 首顶点高亮（≥3 顶点后出现，提示可以点击闭合）── */
.geofence-first-vertex {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #FF4D4F;
  border: 3px solid #fff;
  box-shadow: 0 0 10px rgba(255, 77, 79, 0.7);
  font-size: 11px;
  font-weight: 700;
  color: #fff;
  text-align: center;
  line-height: 20px;
  user-select: none;
  animation: geofence-vertex-pulse 0.8s ease-in-out infinite alternate;
  cursor: pointer;
}

@keyframes geofence-vertex-pulse {
  from {
    box-shadow: 0 0 6px rgba(255, 77, 79, 0.5);
    transform: scale(1);
  }
  to {
    box-shadow: 0 0 16px rgba(255, 77, 79, 0.9);
    transform: scale(1.2);
  }
}

/* ── 老人标记 ── */
.geofence-person-marker {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  background: linear-gradient(135deg, #FF6B6B, #FF4D4F);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  border: 2px solid #fff;
  box-shadow: 0 2px 10px rgba(255, 77, 79, 0.35);
  cursor: grab;
  user-select: none;
}

/* ── 护理员标记 ── */
.geofence-caregiver-marker {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4A90D9, #357ABD);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  border: 2px solid #fff;
  box-shadow: 0 2px 10px rgba(74, 144, 217, 0.4);
  user-select: none;
}

/* ── 终点旗帜标记 ── */
.geofence-dest-marker {
  font-size: 24px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
  user-select: none;
}

/* ── 起点标记 ── */
.geofence-origin-marker {
  font-size: 20px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
  user-select: none;
}
</style>
