const map = L.map('map').setView([35.681236, 139.767125], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

let routingControl = null;
let destinationMarker = null;
let infoDiv = null;

navigator.geolocation.getCurrentPosition(function (position) {
  const currentLatLng = L.latLng(position.coords.latitude, position.coords.longitude);

  L.marker(currentLatLng).addTo(map).bindPopup("現在地").openPopup();

  infoDiv = L.control({ position: 'topright' });
  infoDiv.onAdd = function () {
    const div = L.DomUtil.create('div', 'info-box');
    div.style.background = 'white';
    div.style.padding = '10px';
    div.style.borderRadius = '8px';
    div.style.boxShadow = '0 0 5px rgba(0,0,0,0.3)';
    div.style.fontSize = '14px';
    div.style.minWidth = '150px';
    div.innerHTML = '目的地をクリックしてルート表示';
    return div;
  };
  infoDiv.addTo(map);

  map.on('click', function (e) {
    const destinationLatLng = e.latlng;

    if (destinationMarker) map.removeLayer(destinationMarker);
    if (routingControl) map.removeControl(routingControl);

    destinationMarker = L.marker(destinationLatLng).addTo(map).bindPopup("目的地").openPopup();

    routingControl = L.Routing.control({
      waypoints: [currentLatLng, destinationLatLng],
      routeWhileDragging: false,
      router: L.Routing.osrmv1({
        serviceUrl: 'https://router.project-osrm.org/route/v1'
      }),
      createMarker: () => null,
      show: false,
    }).addTo(map);

    routingControl.on('routesfound', function (e) {
      const route = e.routes[0].summary;
      const distance = (route.totalDistance / 1000).toFixed(2);
      const duration = Math.round(route.totalTime / 60);
      document.querySelector('.info-box').innerHTML =
        `<strong>ルート案内</strong><br>距離：約 ${distance} km<br>所要時間：約 ${duration} 分`;
    });
  });
});
