<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from "vue";

const props = defineProps({
  minimapManager: Object,
});

const minimapContainerRef = ref(null);
let refreshTimeout = null;

// 强制重绘小地图，添加防抖处理
const forceRefresh = () => {
  if (refreshTimeout) {
    clearTimeout(refreshTimeout);
  }

  refreshTimeout = setTimeout(() => {
    if (props.minimapManager) {
      props.minimapManager.refresh();
    }
  }, 50);
};

onMounted(() => {
  if (props.minimapManager && minimapContainerRef.value) {
    // 使用新的mount方法挂载小地图
    props.minimapManager.mount(minimapContainerRef.value);
    // 初始加载后延迟刷新一次，确保内容正确加载
    setTimeout(forceRefresh, 200);
  }
});

watch(
  () => props.minimapManager,
  (newVal) => {
    if (newVal && minimapContainerRef.value) {
      newVal.mount(minimapContainerRef.value);
    }
  }
);

// 添加resize observer以适应容器大小变化
let resizeObserver = null;
onMounted(() => {
  if (window.ResizeObserver) {
    // 使用防抖处理resize事件，避免过于频繁的刷新
    resizeObserver = new ResizeObserver(() => {
      forceRefresh();
    });
    if (minimapContainerRef.value) {
      resizeObserver.observe(minimapContainerRef.value.parentElement);
    }
  }
});

onBeforeUnmount(() => {
  if (resizeObserver && minimapContainerRef.value) {
    resizeObserver.unobserve(minimapContainerRef.value.parentElement);
    resizeObserver.disconnect();
  }
  if (refreshTimeout) {
    clearTimeout(refreshTimeout);
  }
});
</script>

<template>
  <div class="minimap-container">
    <div class="minimap-header">
      <span>画布小地图</span>
      <button class="minimap-refresh" @click="forceRefresh" title="刷新小地图">⟳</button>
    </div>
    <div class="minimap-content" ref="minimapContainerRef">
      <!-- 不再需要直接提供canvas引用，由MinimapManager内部创建 -->
    </div>
  </div>
</template>

<style scoped>
.minimap-container {
  position: absolute;
  bottom: 10px;
  left: 10px;
  width: 200px;
  height: 140px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.minimap-header {
  padding: 5px 8px;
  font-size: 12px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.minimap-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.minimap-refresh {
  cursor: pointer;
  background: none;
  border: none;
  font-size: 14px;
  padding: 0 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.minimap-refresh:hover {
  color: #000;
}

/* 触控设备优化 */
@media (pointer: coarse) {
  .minimap-container {
    width: 220px;
    height: 160px;
  }

  .minimap-header {
    padding: 8px 10px;
    font-size: 14px;
  }

  .minimap-refresh {
    font-size: 18px;
    padding: 0 6px;
  }
}
</style>
