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;
let gameAreaRect;

function startGame() {
    if (isGameRunning) return;
    
    isGameRunning = true;
    score = 0;
    timeLeft = 30;
    currentSize = 100;
    
    gameAreaRect = gameArea.getBoundingClientRect();
    
    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 buttonRect = shrinkBtn.getBoundingClientRect();
    const maxX = gameAreaRect.width - buttonRect.width;
    const maxY = gameAreaRect.height - buttonRect.height;
    
    let newX = Math.random() * maxX;
    let newY = Math.random() * maxY;
    
    newX = Math.max(0, Math.min(newX, maxX));
    newY = Math.max(0, Math.min(newY, maxY));
    
    shrinkBtn.style.left = `${newX}px`;
    shrinkBtn.style.top = `${newY}px`;
}

function shrinkButtonSize() {
    if (currentSize > 30) {
        currentSize -= 8;
        shrinkBtn.style.transform = `scale(${currentSize / 100})`;
    } else {
        currentSize = 100;
        shrinkBtn.style.transform = 'scale(1)';
    }
}

function resetScore() {
    score = 0;
    updateDisplay();
    
    gameArea.style.backgroundColor = '#ffcccc';
    setTimeout(() => {
        gameArea.style.backgroundColor = '';
    }, 200);
}

shrinkBtn.addEventListener('click', function(event) {
    event.stopPropagation();
    if (!isGameRunning) return;
    
    shrinkButtonSize();
    updateButtonPosition();
    
    score++;
    updateDisplay();
});

gameArea.addEventListener('click', function(event) {
    if (!isGameRunning) return;
    if (event.target === shrinkBtn) return; 
    
    resetScore();
    updateButtonPosition();
});

startButton.addEventListener('click', startGame);

shrinkBtn.style.display = 'none';

