const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(
    window.innerWidth / -2, window.innerWidth / 2,
    window.innerHeight / 2, window.innerHeight / -2,
    1, 1000
);
camera.position.z = 10;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// プレイヤー召喚
const playerGeometry = new THREE.BoxGeometry(30, 30, 1);
const playerMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const player = new THREE.Mesh(playerGeometry, playerMaterial);
player.position.x = -200;
scene.add(player);

const bullets = [];
const enemies = [];
let score = 0;
let gameActive = false;

// 入力関連
const keys = { up: false, down: false,  left: false, right: false, space: false};

document.addEventListener('keydown', (event) => {
    if (event.key === 'w') {
        keys.up = true;
        console.log("w pressed - Move Up");
    }
    if (event.key === 's') {
        keys.down = true;
        console.log("s pressed - Move Down");
    }
    if (event.key === 'a') {
        keys.left = true;
        console.log("s pressed - Move Left");
    }
    if (event.key === 'd') {
        keys.right = true;
        console.log("s pressed - Move Right");
    }
    if (event.key === ' ') {  // スペースキー
        keys.space = true;
        console.log("Space pressed");
    }
});

document.addEventListener('keyup', (event) => {
    if (event.key === 'w') {
        keys.up = false;
    }
    if (event.key === 's') {
        keys.down = false;
    }
    if (event.key === 'a') {
        keys.left = false;
    }
    if (event.key === 'd') {
        keys.right = false;
    }
    if (event.key === ' ') {
        keys.space = false;
    }
});

// カウントダウン関連
let count = 30;
let tmID;
const infobox = document.getElementById("infobox");
const startButton = document.getElementById("startButton");

function countDown() {
    if (count === 0) {
        gamestop();
    } else {
        infobox.innerHTML = "残り時間: " + count + "秒";
        count--;
        tmID = setTimeout(countDown, 1000);
    }
}

// ゲームスタート処理
startButton.addEventListener("click", () => {
	gameActive = true;
        count = 30;
        score = 0;
        infobox.innerHTML = "残り時間: 30秒";
	startButton.style.display = "none";
	initGame(); 
        countDown();
});

// ゲーム終了処理
function gamestop() {
    clearTimeout(tmID);
    gameActive = false;
    infobox.innerHTML = "ゲーム終了！ 倒した敵の数: " + score;
    startButton.style.display = "block";
}

// リンカーネーション
function initGame() {
    bullets.forEach(bullet => {
        scene.remove(bullet);
    });
    bullets.length = 0;

    enemies.forEach(enemy => {
        scene.remove(enemy);
    });
    enemies.length = 0; 

    player.position.set(-200, 0, 0); 

    if (!gameActive) return; 
    animate();
}

// ループ処理
let lastShot = 0;
function animate() {
    if (!gameActive) return;
    requestAnimationFrame(animate);
    const time = performance.now();

    // プレイヤーの移動
    if (keys.up) { player.position.y += 6; }
    if (keys.down) { player.position.y -= 6; }
    if (keys.left) { player.position.x -= 6; }
    if (keys.right) { player.position.x += 6; }

    // 弾の発射
    if (keys.space && time - lastShot > 250) {
        const bulletGeometry = new THREE.BoxGeometry(5, 5, 1);
        const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
        const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
        bullet.position.set(player.position.x + 20, player.position.y, 0);
        bullets.push(bullet);
        scene.add(bullet);
        lastShot = time;
    }

    // 弾の移動
    bullets.forEach((bullet, index) => {
        bullet.position.x += 15;
        if (bullet.position.x > window.innerWidth / 2) {
            scene.remove(bullet);
            bullets.splice(index, 1);
        }
    });

    // 敵の生成
    if (Math.random() < 0.02) {
        const enemyGeometry = new THREE.BoxGeometry(30, 30, 1);
        const enemyMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
        const enemy = new THREE.Mesh(enemyGeometry, enemyMaterial);
        enemy.position.set(window.innerWidth / 2, (Math.random() - 0.5) * window.innerHeight, 0);
        enemies.push(enemy);
        scene.add(enemy);
    }

    // 敵の移動と弾との衝突判定
    enemies.forEach((enemy, enemyIndex) => {
        enemy.position.x -= 3;

        bullets.forEach((bullet, bulletIndex) => {
            if (bullet.position.distanceTo(enemy.position) < 20) {
                scene.remove(enemy);
                enemies.splice(enemyIndex, 1);
                scene.remove(bullet);
                bullets.splice(bulletIndex, 1);
		score++;
            }
        });

        // 画面外の敵削除処理
        if (enemy.position.x < -window.innerWidth / 2) {
            scene.remove(enemy);
            enemies.splice(enemyIndex, 1);
              // さいなら~
        }
    });

    renderer.render(scene, camera);
}
