<script setup lang="ts">
/**
 * 全屏地图页面
 *
 * MapLibre 地图容器，底部工具栏可切换图层、
 * 打开弹出窗口等操作。
 */
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { MapManager } from '@/map/MapManager'
import { MapFactory } from '@/map/MapFactory'
import { useMap } from '@/map/composables/useMap'
import { useLayer } from '@/map/composables/useLayer'
import { usePopup } from '@/map/composables/usePopup'
import TckzPop from './tckzPop.vue'
import YbPop from './ybPop.vue'

const router = useRouter()

// ── 地图状态 ──────────────────────────────────────────────
const { map, loading, error, isReady } = useMap()
const { addLayer, removeLayer } = useLayer()
const { showPopup, hidePopup } = usePopup()

/** 地图容器 ref */
const mapContainer = ref<HTMLElement | null>(null)

/** 地图初始化错误（map 本身加载失败，区别于运行错误） */
const initError = ref<string | null>(null)

/** 底部工具栏状态 */
const tools = [
  { icon: 'location-o', label: '定位' },
  { icon: 'eye-o', label: '图层' },
  { icon: 'search', label: '搜索' },
  { icon: 'records', label: '台账' },
  { icon: 'data-o', label: '仪表' },
]

/** 弹窗显示控制 */
const showTckz = ref(false)
const showYb = ref(false)

// ── 初始化地图 ───────────────────────────────────────────
onMounted(() => {
  const manager = MapManager.getInstance()

  // 如果地图已存在，复用即可
  if (manager.hasMap()) return

  const container = document.getElementById('ytmap-container')
  if (!container) {
    initError.value = '地图容器元素 #ytmap-container 未找到'
    return
  }
  mapContainer.value = container

  try {
    MapFactory.createWithBasemap('osm', {
      container: 'ytmap-container',
      zoom: 10,
      center: [104.065735, 30.659462], // 成都中心
      onLoad: (m) => {
        console.log('[MapPage] 地图已加载', m.getCenter())
      },
    })
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '地图初始化失败'
    initError.value = msg
    console.error('[MapPage] 地图创建失败:', err)
  }
})

// ── 组件卸载 ─────────────────────────────────────────────
onUnmounted(() => {
  MapManager.getInstance().destroyMap()
})

// ── 工具栏操作 ───────────────────────────────────────────
function handleToolClick(label: string) {
  if (label === '定位') {
    const m = map.value
    if (m) {
      // 尝试使用浏览器定位
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (pos) => {
            m.flyTo({ center: [pos.coords.longitude, pos.coords.latitude], zoom: 14 })
          },
          () => {
            // 定位失败，回到默认中心
            m.flyTo({ center: [104.065735, 30.659462], zoom: 10 })
          },
        )
      }
    }
  } else if (label === '台账') {
    showTckz.value = true
  } else if (label === '仪表') {
    showYb.value = true
  }
}
</script>

<template>
  <div class="map-page">
    <van-nav-bar title="地图" left-text="返回" left-arrow fixed placeholder @click-left="router.back()" />

    <!-- MapLibre 地图容器 -->
    <div id="ytmap-container" class="map-container">
      <!-- 加载状态 -->
      <div v-if="loading && !error && !initError" class="map-overlay map-loading">
        <van-loading type="spinner" size="32" color="var(--color-primary)" />
        <p class="overlay-text">地图加载中…</p>
      </div>

      <!-- 初始化错误 -->
      <div v-if="initError" class="map-overlay map-error">
        <van-icon name="warning-o" size="48" color="#F44336" />
        <p class="overlay-text">{{ initError }}</p>
        <van-button size="small" type="primary" @click="router.back()">返回</van-button>
      </div>

      <!-- 运行时错误 -->
      <div v-if="error" class="map-error-banner">
        <van-icon name="warning-o" size="16" />
        <span>{{ error }}</span>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools">
      <div
        v-for="tool in tools"
        :key="tool.label"
        class="tool-item"
        @click="handleToolClick(tool.label)"
      >
        <van-icon :name="tool.icon" size="20" />
        <span class="tool-label">{{ tool.label }}</span>
      </div>
    </div>

    <!-- 弹窗组件 -->
    <TckzPop v-model:show="showTckz" />
    <YbPop v-model:show="showYb" />
  </div>
</template>

<style lang="scss" scoped>
.map-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg-page);

  :deep(.van-nav-bar) {
    background: var(--color-primary);
    --van-nav-bar-title-text-color: #fff;
    --van-nav-bar-text-color: #fff;
    --van-nav-bar-icon-color: #fff;
  }
}

.map-container {
  flex: 1;
  position: relative;
  margin: 0;

  :deep(.maplibregl-map) {
    width: 100%;
    height: 100%;
  }
}

/* ── 加载 & 错误覆盖层 ── */
.map-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f0f3f7;
  z-index: 5;
  gap: 12px;
}

.overlay-text {
  font-size: 14px;
  color: var(--color-text-placeholder);
  margin: 0;
}

.map-error {
  .overlay-text {
    color: #F44336;
    font-size: 14px;
  }
}

/* ── 运行时错误横幅 ── */
.map-error-banner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 6;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #fff3f3;
  color: #F44336;
  font-size: 12px;
}

.bottom-tools {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: var(--color-bg-card);
  padding: 8px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  z-index: 10;

  .tool-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    padding: 4px 8px;

    .tool-label {
      font-size: 12px;
      color: var(--color-text-regular);
    }
  }
}
</style>
