import React, { useState, useEffect } from 'react';

const ANIMATIONS = {
    idle:  { frames: 10, speed: 80, loop: true,  path: '/assets/Monkey/Idle',  name: 'idle' },
    air:   { frames: 5,  speed: 120, loop: false, path: '/assets/Monkey/Air',   name: 'air'  },
    punch: { frames: 4,  speed: 80,  loop: false, path: '/assets/Monkey/Punch', name: 'punch'},
};

// Preload all frames once so src swaps are instant (no flicker)
Object.values(ANIMATIONS).forEach(({ path, name, frames }) => {
    for (let i = 0; i < frames; i++) {
        const img = new Image();
        img.src = `${path}/${name}${i}.png`;
    }
});

const MonkeySprite = ({ animation = 'idle', onAnimationEnd, className, style: styleProp }) => {
    const [frame, setFrame] = useState(0);
    const currentAnim = ANIMATIONS[animation];

    useEffect(() => {
        setFrame(0);
        let currentFrame = 0;
        const interval = setInterval(() => {
            currentFrame++;
            if (currentFrame >= currentAnim.frames) {
                if (currentAnim.loop) {
                    currentFrame = 0;
                    setFrame(0);
                } else {
                    clearInterval(interval);
                    if (onAnimationEnd) onAnimationEnd();
                }
                return;
            }
            setFrame(currentFrame);
        }, currentAnim.speed);

        return () => clearInterval(interval);
    }, [animation, onAnimationEnd, currentAnim]);

    const src = `${currentAnim.path}/${currentAnim.name}${frame}.png`;

    return (
        <img
            src={src}
            alt=""
            className={className}
            style={{
                imageRendering: 'pixelated',
                width: '200px',
                height: 'auto',
                filter: 'grayscale(1)',
                ...styleProp,
            }}
        />
    );
};

export default MonkeySprite;
