const map = L.map('map').setView([35.6895, 139.6917], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap'
}).addTo(map);

let start = null;
let destMarker = null;
let routeLine = null;

// 現在地取得
navigator.geolocation.getCurrentPosition(pos => {
  start = [pos.coords.longitude, pos.coords.latitude];
  L.marker([start[1], start[0]]).addTo(map).bindPopup('現在地').openPopup();
  map.setView([start[1], start[0]], 15);
}, err => {
  alert('現在地が取得できません。東京に設定します');
  start = [139.6917, 35.6895]; 
  L.marker([start[1], start[0]]).addTo(map).bindPopup('東京').openPopup();
});

// 地図クリックで目的地設定
map.on('click', async (e) => {
  if(!start) return alert('現在地取得中...');

  const end = [e.latlng.lng, e.latlng.lat];

  if(destMarker) map.removeLayer(destMarker);
  destMarker = L.marker([end[1], end[0]]).addTo(map).bindPopup('目的地').openPopup();

  try {
    const res = await fetch('http://localhost:3000/route', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ start, end })
    });
    const data = await res.json();

    // 坂少ないルート選択
    let bestRoute = null;
    let minSlope = Infinity;

    data.features.forEach(feature => {
      const coords = feature.geometry.coordinates;
      let slopeSum = 0;
      for(let i=0; i<coords.length-1; i++){
        const dh = (coords[i+1][2] || 0) - (coords[i][2] || 0);
        const dd = Math.sqrt(
          Math.pow((coords[i+1][1]-coords[i][1])*111000,2) +
          Math.pow((coords[i+1][0]-coords[i][0])*111000,2)
        );
        slopeSum += Math.abs(dh/dd);
      }
      if(slopeSum < minSlope){
        minSlope = slopeSum;
        bestRoute = coords;
      }
    });

    if(routeLine) map.removeLayer(routeLine);
    const latlngs = bestRoute.map(c => [c[1], c[0]]);
    routeLine = L.polyline(latlngs, {color:'blue', weight:4}).addTo(map);
    map.fitBounds(routeLine.getBounds());

  } catch(err) {
    alert('ルート取得でエラー');
    console.error(err);
  }
});

