/**
 * Leaflet 地图库预加载器
 * 确保 Leaflet 在需要时已经加载完成
 */

let leafletLoading = false;
let leafletLoaded = false;

/**
 * 预加载 Leaflet 库
 * @returns Promise<boolean> 加载成功返回 true
 */
export const preloadLeaflet = (): Promise<boolean> => {
  return new Promise((resolve) => {
    // 如果已经加载，直接返回
    if (leafletLoaded || window.L) {
      leafletLoaded = true;
      console.log('✅ Leaflet 已加载');
      resolve(true);
      return;
    }

    // 如果正在加载，等待加载完成
    if (leafletLoading) {
      const checkInterval = setInterval(() => {
        if (leafletLoaded || window.L) {
          clearInterval(checkInterval);
          leafletLoaded = true;
          resolve(true);
        }
      }, 100);
      return;
    }

    leafletLoading = true;
    console.log('🔄 开始加载 Leaflet...');

    try {
      // 加载 CSS
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
      link.integrity = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';
      link.crossOrigin = '';
      document.head.appendChild(link);

      // 加载 JS
      const script = document.createElement('script');
      script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
      script.integrity = 'sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=';
      script.crossOrigin = '';

      script.onload = () => {
        leafletLoaded = true;
        leafletLoading = false;
        console.log('✅ Leaflet 加载成功');
        console.log('📍 版本:', window.L?.version);
        resolve(true);
      };

      script.onerror = () => {
        leafletLoading = false;
        console.warn('⚠️ Leaflet 加载失败，将使用占位地图');
        resolve(false);
      };

      document.head.appendChild(script);
    } catch (error) {
      leafletLoading = false;
      console.error('❌ 加载 Leaflet 时发生错误:', error);
      resolve(false);
    }
  });
};

/**
 * 检查 Leaflet 是否已加载
 */
export const isLeafletLoaded = (): boolean => {
  return leafletLoaded || !!window.L;
};

/**
 * 获取 Leaflet 版本
 */
export const getLeafletVersion = (): string | null => {
  if (isLeafletLoaded() && window.L) {
    return window.L.version || null;
  }
  return null;
};

// 扩展 Window 接口
declare global {
  interface Window {
    L: any;
  }
}