document.addEventListener("DOMContentLoaded", () => {
        var allData = [];
        var currentQuestionIndex = 0;
        var nTrial = 100;
        var watchId = null;
     
        var mymap = L.map("locationmap").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();
     
        function loadCSV(targetFile) {
            fetch(targetFile)
                .then((resp) => resp.ok ? resp.text() : Promise.reject("CSV読み込みエラー"))
                .then((txt) => {
                    allData = new Papa.parse(txt, {header: true}).data;
                    console.log("CSVデータ読み込み完了:", allData);
                    setQuestion(currentQuestionIndex); // 初期のクイズをセット
                });
        }
     
        function setQuestion(number) {
            var q = allData[number];
            console.log("表示するクイズ:", q);
            document.getElementById("id_question").innerHTML = q.Q;
            document.getElementById("id_ChoiceA").innerHTML = q.A;
            document.getElementById("id_ChoiceB").innerHTML = q.B;
            document.getElementById("id_ChoiceC").innerHTML = q.C;
            document.getElementById("id_ChoiceD").innerHTML = q.D;
            document.getElementById("id_mondaigazo").src = "img/" + q.IMG;
            document.getElementById("id_kotae").innerHTML = '';
        }
     
        function answer(e) {
            var seikai = allData[currentQuestionIndex].ANS;
            var kaisetsu = allData[currentQuestionIndex].TEXT;
            var kaitou = e.target.value;
     
            if (kaitou === seikai) {
                document.getElementById("id_pf").innerHTML = '正解';
                document.getElementById("id_kotae").innerHTML = kaisetsu;
                document.body.style.background = "#ccffff";
            } else {
                document.getElementById("id_pf").innerHTML = '不正解 もう一度答えてみよう!';
                document.getElementById("id_kotae").innerHTML = '-';
                document.body.style.background = "#696969 ";
            }
        }
     
        function onSuccess(pos) {
            var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
            mymap.panTo(latlng);
            locmarker.setLatLng(latlng);
     
            console.log("現在地:", latlng);
     
            // 現在地とクイズの位置を比較
            allData.forEach((quiz, index) => {
                var quizLat = parseFloat(quiz.LAT);
                var quizLng = parseFloat(quiz.LNG);
                console.log(`クイズ位置：lat: ${quizLat}, lng: ${quizLng}`);
     
                // 現在地がクイズ位置に近ければ、そのクイズを表示
                if (Math.abs(latlng.lat - quizLat) < 0.0002 && Math.abs(latlng.lng - quizLng) < 0.0002) {
                    locmarker.setPopupContent("当たり").openPopup();
                    setQuestion(index); // クイズをセット
                    currentQuestionIndex = index; // 現在のクイズインデックスを更新
                }
            });
        }
     
        function onError(err) {
            console.log("位置情報の取得エラー:", err);
            restN = "あと" + (--nTrial) + "回試行します。";
            locmarker.setPopupContent("捕捉失敗:" + restN).openPopup();
            if (nTrial <= 0) {
                navigator.geolocation.clearWatch(watchId);
            }
        }
     
        function tryWatchLOC() {
            stopLOC();
            watchId = navigator.geolocation.watchPosition(onSuccess, onError, {
                maximumAge: 0,
                timeout: 3000,
                enableHighAccuracy: true
            });
            document.getElementById("title").textContent = "START!!";
        }
     
        function stopLOC() {
            if (watchId != null) {
                navigator.geolocation.clearWatch(watchId);
                document.getElementById("title").textContent = "STOP";
                locmarker.setPopupContent("停止しました");
            }
            watchId = null;
        }
     
        document.getElementById("start").addEventListener("click", tryWatchLOC);
        document.getElementById("stop").addEventListener("click", stopLOC);
     
        loadCSV("4taku.csv"); // クイズCSVの読み込み
    });
