use crate::components::_animator::Animator;
use pico_ecs::{_component_storage::ComponentStorage, _world::World};
use pico_rendering::components::_render_component::RendererComponent;
use pico_transform::{_pivot::Pivot, _size::Size};

const ANIMATION_FPS: u32 = 12; // Frames per second for animations
const ANIMATION_FRAME_TIME_MS: u32 = 1_000 / ANIMATION_FPS;

pub fn run(
    world: &World,
    animator_storage: &mut ComponentStorage<Animator>,
    render_storage: &mut ComponentStorage<RendererComponent>,
    size_storage: &mut ComponentStorage<Size>,
    pivot_storage: &mut ComponentStorage<Pivot>,
    delta_time: u32,
) {
    for (_entity, animator, renderer, size, pivot) in world.query_4mut(
        animator_storage,
        render_storage,
        size_storage,
        pivot_storage,
    ) {
        animator.frame_timer += delta_time;

        if animator.frame_timer < ANIMATION_FRAME_TIME_MS {
            continue;
        }

        // Reset frame timer (subtract instead of zeroing to keep timing accurate)
        animator.frame_timer = 0;

        let animation = &animator.animations[animator.current_animation];
        let frames = &animator.frames[animation.start_frame..=animation.end_frame];
        animator.current_frame_index = (animator.current_frame_index + 1) % frames.len();
        let frame = &frames[animator.current_frame_index];
        renderer.sprite = frame;
        size.width = frame.width as u16;
        size.height = frame.height as u16;
        pivot.x = frame.offset_x as u16;
        pivot.y = frame.offset_y as u16;
    }
}
