import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.152.2/build/three.module.js';

export function startShootingGame(backgroundImage) {
    return new Promise((resolve) => {
        const gameContainer = document.createElement('div');
        gameContainer.style.position = 'fixed';
        gameContainer.style.top = 0;
        gameContainer.style.left = 0;
        gameContainer.style.width = '100vw';
        gameContainer.style.height = '100vh';
        gameContainer.style.zIndex = 9999;
        document.body.appendChild(gameContainer);

        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);
        gameContainer.appendChild(renderer.domElement);

        // 背景画像
        const loader = new THREE.TextureLoader();
        loader.load(backgroundImage, (texture) => {
            scene.background = texture;
        });

        // プレイヤー
        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 = true;

        // 入力管理
        const keys = { up: false, down: false, left: false, right: false, space: false };
        document.addEventListener('keydown', (event) => {
            keys[event.key.toLowerCase()] = true;
        });

        document.addEventListener('keyup', (event) => {
            keys[event.key.toLowerCase()] = false;
        });

        // カウントダウン
        let count = 30;
        const infoBox = document.createElement('div');
        infoBox.style.position = 'absolute';
        infoBox.style.top = '10px';
        infoBox.style.left = '10px';
        infoBox.style.color = 'white';
        infoBox.style.fontSize = '20px';
        infoBox.textContent = `残り時間: ${count}秒`;
        gameContainer.appendChild(infoBox);

        const countDown = setInterval(() => {
            if (!gameActive) return;
            count--;
            infoBox.textContent = `残り時間: ${count}秒`;
            if (count === 0) gameStop();
        }, 1000);

        function gameStop() {
            clearInterval(countDown);
            gameActive = false;
            cancelAnimationFrame(animationId);
            document.body.removeChild(gameContainer);
            resolve(score);
        }

        let lastShot = 0;
        let animationId;

        function animate() {
            if (!gameActive) return;
            animationId = requestAnimationFrame(animate);

            const time = performance.now();

            // プレイヤー移動
            if (keys['w']) player.position.y += 6;
            if (keys['s']) player.position.y -= 6;
            if (keys['a']) player.position.x -= 6;
            if (keys['d']) player.position.x += 6;

            // 弾発射
            if (keys[' '] && time - lastShot > 250) {
                const bullet = new THREE.Mesh(
                    new THREE.BoxGeometry(5, 5, 1),
                    new THREE.MeshBasicMaterial({ color: 0xffff00 })
                );
                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 enemy = new THREE.Mesh(
                    new THREE.BoxGeometry(30, 30, 1),
                    new THREE.MeshBasicMaterial({ color: 0xff0000 })
                );
                enemy.position.set(window.innerWidth / 2, (Math.random() - 0.5) * window.innerHeight, 0);
                enemies.push(enemy);
                scene.add(enemy);
            }

            enemies.forEach((enemy, eIndex) => {
                enemy.position.x -= 3;
                bullets.forEach((bullet, bIndex) => {
                    if (bullet.position.distanceTo(enemy.position) < 20) {
                        scene.remove(enemy);
                        enemies.splice(eIndex, 1);
                        scene.remove(bullet);
                        bullets.splice(bIndex, 1);
                        score++;
                    }
                });
            });

            renderer.render(scene, camera);
        }

        animate();
    });
}

