document.addEventListener("DOMContentLoaded", () => {
    var mymap = L.map("gpsmap").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 pins = [
        { name: "Location A", coordinates: [38.9, 139.8] },
        { name: "Location B", coordinates: [38.95, 139.85] }
    ];

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

    var watchId = null; // 追加
    var nTrial = 100; // 追加

    function getRandomPin() {
        return pins[Math.floor(Math.random() * pins.length)];
    }

    function stopGPS() {
        console.log("Stopping GPS");
        navigator.geolocation.clearWatch(watchId);
        document.getElementById("title").textContent = "stop";
        gpsmarker.setPopupContent("停めました");
        watchId = null;
    }

    function tryWatchGPS() {
        stopGPS();
        nTrial = 100; // 追加
        pinIndex = null;
        var pin1 = getRandomPin();
        var pin2 = getRandomPin();
        pinIndex = Math.random() < 0.5 ? 0 : 1; // 追加
        document.getElementById("pin-info").textContent = `Pin 1: ${pin1.name}, Pin 2: ${pin2.name}`;
        watchId = navigator.geolocation.watchPosition(
            onSuccess, onError, { maximumAge: 0, timeout: 3000, enableHighAccuracy: true });
        document.getElementById("title").textContent = "START!!";
    }

    function onSuccess(pos) {
        var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
        mymap.panTo(latlng);
        console.log(latlng);

        if (pinIndex !== null) {
            var pinCoordinates = pins[pinIndex].coordinates;
            var pinLatLng = L.latLng(pinCoordinates);
            var distance = latlng.distanceTo(pinLatLng);

            gpsmarker.setLatLng(latlng).setPopupContent(
                `距離: ${distance.toFixed(2)} メートル`
            ).openPopup();
        }
    }

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

    function finishGame() {
        if (pinIndex !== null) {
            stopGPS();
            var pinCoordinates = pins[pinIndex].coordinates;
            var pinLatLng = L.latLng(pinCoordinates);
            var distance = mymap.getCenter().distanceTo(pinLatLng);
            alert(`ゲーム終了！\n${pins[pinIndex].name}への距離: ${distance.toFixed(2)} メートル`);
        } else {
            alert("まずはSTARTボタンを押してゲームを始めてください！");
        }
    }

    document.getElementById("start").addEventListener("click", tryWatchGPS);
    document.getElementById("stop").addEventListener("click", stopGPS);
    document.getElementById("finish").addEventListener("click", finishGame);

}, false);
