<template>
  <div class="map-panel">
    <!-- ═══ 标题浮层 ═══ -->
    <div class="panel-overlay">
      <span class="panel-title" :style="{ color }">{{ title }}</span>
      <span v-if="loading" class="panel-status">⏳ 加载中...</span>
      <span v-else-if="error" class="panel-status panel-error">❌ {{ error }}</span>
      <span v-else class="panel-status panel-ok">✅ 地图就绪</span>
    </div>

    <!-- ═══ 地图容器 —— 每个 MapPanel 有自己独立的 DOM 元素 ═══ -->
    <div
      ref="containerRef"
      class="panel-map"
    />

    <!-- ═══ 底部说明条 ═══ -->
    <div class="panel-footer">
      <span>🆔 容器：<code>containerRef</code>（独立 DOM）</span>
      <span>📦 JSAPI：全局单例（不重复下载）</span>
    </div>
  </div>
</template>

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

const props = defineProps<{
  title: string
  center: [number, number]
  zoom: number
  color: string
}>()

const emit = defineEmits<{
  (e: 'map-created'): void
  (e: 'map-destroyed'): void
}>()

// ═══ 每个 MapPanel 独立调用 useAmap() ═══
// 各自的 containerRef 绑定到各自的 <div ref="containerRef" />
// 互不干扰
const { containerRef, loading, error, initMap, destroyMap } = useAmap({
  center: props.center,
  zoom: props.zoom,
})

async function bootstrapMap() {
  const map = await initMap()
  if (map) {
    emit('map-created')
  }
}

// 组件挂载 → 初始化地图
onMounted(() => {
  bootstrapMap()
})

// 组件卸载 → 销毁地图（由 v-if 切换触发）
onUnmounted(() => {
  destroyMap()
  emit('map-destroyed')
})

// 暴露给父组件的调试用 ref（实际项目中不需要）
defineExpose({ containerRef })
</script>

<style scoped>
.map-panel {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
}

/* ── 标题浮层 ── */
.panel-overlay {
  position: absolute;
  top: 12px;
  left: 16px;
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
}

.panel-status {
  font-size: 12px;
  color: #999;
}

.panel-ok {
  color: #27ae60;
}

.panel-error {
  color: #e74c3c;
}

/* ── 地图 ── */
.panel-map {
  flex: 1;
  width: 100%;
}

/* ── 底部说明 ── */
.panel-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 16px;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  font-size: 11px;
  color: #999;
  flex-shrink: 0;
}

.panel-footer code {
  font-family: 'Consolas', 'Courier New', monospace;
  font-size: 11px;
  background: #f5f5f5;
  padding: 1px 6px;
  border-radius: 3px;
}
</style>
