const gameArea = document.getElementById('gameArea');
const shrinkBtn = document.getElementById('shrinkButton');
const scoreDisplay = document.getElementById('score');
const timerDisplay = document.getElementById('timeLeft');
const startButton = document.getElementById('startButton');

let currentSize = 100;
let score = 0;
let timeLeft = 30;
let gameInterval;
let isGameRunning = false;

function startGame() {
    if (isGameRunning) return;
    
    isGameRunning = true;
    score = 0;
    timeLeft = 30;
    currentSize = 100;
    
    updateDisplay();
    updateButtonPosition();
    shrinkBtn.style.display = 'block';
    startButton.disabled = true;

    gameInterval = setInterval(() => {
        timeLeft--;
        updateDisplay();
        if (timeLeft <= 0) {
            endGame();
        }
    }, 1000);
}

function endGame() {
    clearInterval(gameInterval);
    isGameRunning = false;
    shrinkBtn.style.display = 'none';
    startButton.disabled = false;
    alert(`ゲーム終了！最終スコア: ${score}`);
}

function updateDisplay() {
    scoreDisplay.textContent = score;
    timerDisplay.textContent = timeLeft;
}

function updateButtonPosition() {
    const maxX = gameArea.clientWidth - shrinkBtn.offsetWidth;
    const maxY = gameArea.clientHeight - shrinkBtn.offsetHeight;
    
    shrinkBtn.style.left = `${Math.random() * maxX}px`;
    shrinkBtn.style.top = `${Math.random() * maxY}px`;
}

function shrinkButtonSize() {
    if (currentSize > 10) {
        currentSize -= 8; // 5%ずつ小さくする
        shrinkBtn.style.transform = `scale(${currentSize / 100})`;
    } else {
        // 最小サイズに達したらリセット
        currentSize = 100;
        shrinkBtn.style.transform = 'scale(1)';
    }
}

shrinkBtn.addEventListener('click', function(event) {
    event.stopPropagation();
    if (!isGameRunning) return;
    
    // ボタンを小さくする
    shrinkButtonSize();
    
    // ボタンの位置を更新
    updateButtonPosition();
    
    score++;
    updateDisplay();
});

gameArea.addEventListener('click', function() {
    if (!isGameRunning) return;
    // ゲームエリアをクリックしても何も起こらないようにする
});

startButton.addEventListener('click', startGame);

// 初期状態でボタンを非表示にする
shrinkBtn.style.display = 'none';