let loadingPromise: Promise<any> | null = null;
export const BEIJING_CENTER: [number, number] = [116.407526, 39.90403];

export function getMapConfig() {
  return {
    key: import.meta.env.VITE_AMAP_KEY,
    securityCode: import.meta.env.VITE_AMAP_SECURITY_CODE,
    center: [
      Number(import.meta.env.VITE_MAP_CENTER_LNG || 104.195397),
      Number(import.meta.env.VITE_MAP_CENTER_LAT || 35.86166),
    ] as [number, number],
    zoom: Number(import.meta.env.VITE_MAP_DEFAULT_ZOOM || 4),
  };
}

export function getBrowserCoordinates() {
  return new Promise<[number, number]>((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器定位不可用'));
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        resolve([position.coords.longitude, position.coords.latitude]);
      },
      () => reject(new Error('浏览器定位失败')),
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 5 * 60 * 1000,
      },
    );
  });
}

export function loadAmap() {
  if (window.AMap) {
    return Promise.resolve(window.AMap);
  }
  if (loadingPromise) {
    return loadingPromise;
  }

  const { key, securityCode } = getMapConfig();
  if (!key) {
    return Promise.reject(new Error('未配置 VITE_AMAP_KEY，地图将使用列表降级展示'));
  }

  if (securityCode) {
    window._AMapSecurityConfig = { securityJsCode: securityCode };
  }

  loadingPromise = new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`;
    script.async = true;
    script.onload = () => resolve(window.AMap);
    script.onerror = () => reject(new Error('高德地图脚本加载失败'));
    document.head.appendChild(script);
  });

  return loadingPromise;
}
