package se.urmo.game.entities.ghost.mode;

import lombok.extern.slf4j.Slf4j;
import se.urmo.game.entities.ghost.Ghost;
import se.urmo.game.entities.ghost.strategy.FearStrategy;
import se.urmo.game.entities.pacman.PacMan;
import se.urmo.game.graphics.SpriteLocation;
import se.urmo.game.graphics.SpriteSheetManager;
import se.urmo.game.main.Game;
import se.urmo.game.map.GameMap;

import java.awt.image.BufferedImage;

@Slf4j
public class FrightenedGhostMode extends AbstractGhostModeImpl {
    // Frightened mode specific constants
    private static final int WARNING_THRESHOLD = 180; // 3 seconds of warning
    private static final BufferedImage[] FEAR_ANIMATION = SpriteSheetManager.get(SpriteLocation.GHOST).getAnimation(8);
    private static final int FRIGHTENED_DURATION_TICKS = 10 * Game.UPS_SET;

    // Frightened mode specific state
    private int frightenedTimer = FRIGHTENED_DURATION_TICKS;
    private boolean isBlinking = false;

    public FrightenedGhostMode(Ghost ghost) {
        super(ghost, new FearStrategy(), ghost.getLevelManager(), ghost.getAnimation());
        strategy = new FearStrategy();
    }

    @Override
    public void update(Ghost ghost, PacMan pacman, GameMap map) {
        updateFrightened(ghost);
        updatePosition(ghost, pacman, map);
    }

    @Override
    public BufferedImage[] getAnimation() {
        return (!isBlinking ? FEAR_ANIMATION : super.getAnimation());
    }

    @Override
    public double getSpeed() {
        return 1.0;
    }

    /**
     * Update the frightened state timer and handle blinking animation
     */
    private void updateFrightened(Ghost ghost) {
        frightenedTimer--;

        // Handle blinking animation when timer is running low
        if (frightenedTimer <= WARNING_THRESHOLD) {
            isBlinking = (frightenedTimer / 25) % 2 == 0;
        }

        // Check if frightened mode should end
        if (frightenedTimer <= 0) {
            log.debug("Frightened mode ended");
            ghost.requestModeChange(GhostMode.CHASE);
            frightenedTimer = FRIGHTENED_DURATION_TICKS;
            isBlinking = false;
        }
    }

//    public void enter(Ghost ghost) {
//        // Initialize frightened mode-specific state
//        log.debug("Entering frightened mode");
//        frightenedTimer = FRIGHTENED_DURATION_TICKS;
//        isBlinking = false;
//    }

    /**
     * Get the current time remaining in frightened mode (for external queries)
     */
    public int getRemainingTime() {
        return frightenedTimer;
    }

    /**
     * Reset the frightened timer (for power pellet extensions)
     */
    public void resetTimer() {
        frightenedTimer = FRIGHTENED_DURATION_TICKS;
        isBlinking = false;
    }
}