import { startShootingGame } from './shooter.js';

document.addEventListener("DOMContentLoaded", () => {
    const mapContainer = document.getElementById("map");
    const gameContainer = document.getElementById("game-container");
    const statusText = document.getElementById("status");
    const cheatButton = document.getElementById("cheatButton");

    let isCheatMode = false;
    let completedPins = 0;

    // マップの初期化
    const mymap = L.map("map").setView([38.898, 139.824], 14);
    L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(mymap);

    // ピン配置
    const pins = [
        { marker: [38.898999, 139.818379], options: { title: "その1" }, background: 'background1.jpg', completed: false },
        { marker: [38.902560, 139.838504], options: { title: "その2" }, background: 'background2.jpg', completed: false },
        { marker: [38.891517, 139.852012], options: { title: "その3" }, background: 'background3.jpg', completed: false },
        { marker: [38.923071, 139.843187], options: { title: "その4" }, background: 'background4.jpg', completed: false },
        { marker: [38.893542, 139.819199], options: { title: "その5" }, background: 'background5.jpg', completed: false }
    ];

    pins.forEach(pin => {
        const marker = L.marker(pin.marker, pin.options).addTo(mymap);
        pin.markerInstance = marker;
    });

    // プレイヤーの現在地を取得してピンの有効範囲を更新
    function updatePinAvailability() {
        navigator.geolocation.getCurrentPosition((position) => {
            const playerLat = position.coords.latitude;
            const playerLng = position.coords.longitude;

            pins.forEach(pin => {
                const distance = calculateDistance(playerLat, playerLng, pin.marker[0], pin.marker[1]);

                if (!pin.completed) {
                    if (isCheatMode || distance <= 50) {
                        pin.markerInstance.bindPopup(`
                            <div>
                                <p>${pin.options.title}</p>
                                <button id="startgame-${pin.options.title}" class="start-game-btn">ゲームを開始する</button>
                            </div>
                        `);
                    } else {
                        pin.markerInstance.unbindPopup();
                    }
                }
            });
        }, onError);
    }

    // チートモード
    cheatButton.addEventListener('click', () => {
        isCheatMode = !isCheatMode;
        cheatButton.textContent = isCheatMode ? "チートモード: ON" : "チートモード: OFF";
        updatePinAvailability();
    });

    // ゲーム開始処理
    mymap.on('popupopen', (event) => {
        const popupContent = event.popup.getContent();
        const startGameButton = document.querySelector('.start-game-btn');

        if (startGameButton) {
            startGameButton.addEventListener('click', () => {
                const pin = pins.find(pin => pin.options.title === startGameButton.id.split('-')[1]);

                if (pin && !pin.completed) {
                    mapContainer.style.display = 'none';
                    gameContainer.style.display = 'block';

                    startShootingGame(pin.background).then(() => {
                        pin.completed = true;
                        completedPins++;
                        statusText.textContent = `クリア済みのピン: ${completedPins}`;

                        pin.markerInstance.setIcon(L.icon({
                            iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
                            iconSize: [25, 41],
                            iconAnchor: [12, 41]
                        }));

                        gameContainer.style.display = 'none';
                        mapContainer.style.display = 'block';

                        pin.markerInstance.unbindPopup(); // クリック不可に
                        checkCompletion();
                    });
                }
            });
        }
    });

    // クリア確認
    function checkCompletion() {
        if (completedPins === pins.length) {
            alert("おめでとうございます！全てのピンをクリアしました！");
        }
    }

    // 距離計算関数
    function calculateDistance(lat1, lng1, lat2, lng2) {
        const R = 6371e3; // 地球の半径 (メートル)
        const φ1 = lat1 * Math.PI / 180;
        const φ2 = lat2 * Math.PI / 180;
        const Δφ = (lat2 - lat1) * Math.PI / 180;
        const Δλ = (lng2 - lng1) * Math.PI / 180;

        const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
                  Math.cos(φ1) * Math.cos(φ2) *
                  Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * c; // メートルでの距離
    }

    function onError(error) {
        console.error("位置情報の取得に失敗しました", error);
    }

    setInterval(updatePinAvailability, 5000);
});


