import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import Vant from 'vant';
import 'vant/lib/index.css';

// 全局样式 - 防止移动端输入框自动缩放
const globalStyle = document.createElement('style');
globalStyle.textContent = `
  /* 防止iOS输入框自动缩放 */
  input, textarea, select {
    font-size: 16px !important;
  }
  
  /* 防止页面缩放 */
  * {
    touch-action: manipulation;
  }
  
  /* 优化输入框体验 */
  input:focus, textarea:focus, select:focus {
    font-size: 16px !important;
  }
`;
document.head.appendChild(globalStyle);

// 获取高德地图配置（优先使用运行时配置，其次使用构建时环境变量）
const getAmapKey = () => {
  if (window.AMAP_CONFIG && window.AMAP_CONFIG.key && window.AMAP_CONFIG.key !== 'YOUR_AMAP_KEY_PLACEHOLDER') {
    return window.AMAP_CONFIG.key;
  }
  return import.meta.env.VITE_AMAP_KEY;
};

const getAmapSecurityCode = () => {
  if (window.AMAP_CONFIG && window.AMAP_CONFIG.securityCode && window.AMAP_CONFIG.securityCode !== 'YOUR_AMAP_SECURITY_CODE_PLACEHOLDER') {
    return window.AMAP_CONFIG.securityCode;
  }
  return import.meta.env.VITE_AMAP_SECURITY_CODE || 'b2e67bb4d5eed8848f0b8aae6ca667fc';
};

// 配置高德地图安全密钥（必须在加载地图前配置）
window._AMapSecurityConfig = {
  securityJsCode: getAmapSecurityCode()
};

console.log('高德地图配置:', {
  hasKey: !!getAmapKey(),
  keySource: window.AMAP_CONFIG && window.AMAP_CONFIG.key !== 'YOUR_AMAP_KEY_PLACEHOLDER' ? 'runtime' : 'build-time',
  hasSecurityCode: !!getAmapSecurityCode()
});

const app = createApp(App);
app.use(router);
app.use(Vant);
app.mount('#app');

// 动态加载高德地图（含插件）
const loadAMap = () => {
  return new Promise((resolve, reject) => {
    const amapKey = getAmapKey();
    
    if (!amapKey || amapKey === 'YOUR_AMAP_KEY_PLACEHOLDER' || amapKey === 'YOUR_AMAP_KEY') {
      console.error('高德地图Key未配置！');
      console.error('请在 docker-compose.yml 中配置 AMAP_KEY 环境变量');
      console.error('当前 Key 值:', amapKey);
      reject(new Error('高德地图Key未配置'));
      return;
    }

    if (window.AMap) {
      // 如果已加载，检查插件是否可用
      if (window.AMap.Geocoder && window.AMap.PlaceSearch) {
        console.log('高德地图已加载，插件可用');
        resolve(window.AMap);
      } else {
        // 插件未加载，异步加载
        console.log('加载高德地图插件...');
        window.AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete'], () => {
          console.log('高德地图插件加载完成');
          resolve(window.AMap);
        });
      }
      return;
    }

    console.log('开始加载高德地图脚本...');
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${amapKey}&plugin=AMap.Geocoder,AMap.PlaceSearch,AMap.AutoComplete`;
    script.async = true;
    script.onload = () => {
      if (window.AMap) {
        console.log('高德地图脚本加载成功');
        // 脚本加载后再确保插件加载
        window.AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete'], () => {
          console.log('高德地图插件初始化完成');
          resolve(window.AMap);
        });
      } else {
        console.error('高德地图加载失败：window.AMap未定义');
        reject(new Error('高德地图加载失败'));
      }
    };
    script.onerror = (error) => {
      console.error('高德地图脚本加载失败:', error);
      reject(new Error('高德地图脚本加载失败'));
    };
    document.head.appendChild(script);
  });
};

// 导出加载函数供其他组件使用
window.loadAMap = loadAMap;

// 预加载地图
loadAMap().catch(err => {
  console.error('地图预加载失败:', err);
});
