document.addEventListener("DOMContentLoaded", () => {
  var mymap = L.map("locationmap", { tap: true }).setView([38.891, 139.824], 16);

  L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", {
    attribution:
      '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(mymap);

  var locmarker = L.marker(mymap.getCenter()).addTo(mymap);
  locmarker.bindPopup("STARTおしてね").openPopup();

  var nTrial = 100;
  var watchId = null;

  function stopLOC() {
    if (watchId != null) {
      navigator.geolocation.clearWatch(watchId);
      document.getElementById("title").textContent = "stop";
      locmarker.setPopupContent("停めました");
    }
    watchId = null;
  }

  function tryWatchLOC() {
    stopLOC();
    watchId = navigator.geolocation.watchPosition(
      onSuccess,
      onError,
      { maximumAge: 0, timeout: 3000, enableHighAccuracy: true }
    );
    document.getElementById("title").textContent = "START!!";
  }

  function updateLocation(latlng) {
    mymap.panTo(latlng);

    const goalLat = 38.892;
    const goalLng = 139.825;

    const dLat = Math.abs(latlng.lat - goalLat);
    const dLng = Math.abs(latlng.lng - goalLng);

    let message;

    if (dLat < 0.001 && dLng < 0.001) {
      message = "🎉 GOAL!! 宝を見つけました！";
    } else if (dLat < 0.005 && dLng < 0.005) {
      message = "おしい！もう少し！";
    } else {
      message = "探索中…";
    }

    locmarker
      .setLatLng(latlng)
      .setPopupContent(message)
      .openPopup();
  }

  function onSuccess(pos) {
    var latlng = L.latLng(
      pos.coords.latitude,
      pos.coords.longitude
    );
    updateLocation(latlng);
  }

  function onError(err) {
    var restN = "あと" + (--nTrial) + "回試行します。";
    locmarker.setPopupContent("捕捉失敗:" + restN).openPopup();
    if (nTrial <= 0) {
      navigator.geolocation.clearWatch(watchId);
    }
  }

  mymap.on("click", function (e) {
    console.log("クリック/タッチ:", e.latlng);
    stopLOC();
    updateLocation(e.latlng);
  });

  document.getElementById("start")
    .addEventListener("click", tryWatchLOC);

  document.getElementById("stop")
    .addEventListener("click", stopLOC);
    
    if ('serviceWorker' in navigator) {
    	navigator.serviceWorker.register('./serviceworker.js')
    	.then(() => {
    		console.log('service worker registered');
    	});
    }

}, false);
