use gtk::{gdk_pixbuf, gio};
use gdk_pixbuf::InterpType;
use glib::Cast;

const SPRITE_SCALE: f64 = 0.6;

extern "C" {
    fn ahfail_get_resource() -> *mut gio::ffi::GResource;
}

/// Registers GResources and loads all sprite frames into a looping PixbufSimpleAnim.
/// Returns None if GResources unavailable or no frames found.
pub unsafe fn load_animation() -> Option<gdk_pixbuf::PixbufAnimation> {
    use glib::translate::from_glib_none;

    let resource_ptr = ahfail_get_resource();
    if resource_ptr.is_null() { return None; }
    let resource = from_glib_none::<_, gio::Resource>(resource_ptr);
    gio::resources_register(&resource);

    let mut frames = gio::resources_enumerate_children(
        "/ahfail/sprites", gio::ResourceLookupFlags::NONE,
    ).ok()?;
    frames.sort();

    let mut loaded: Vec<gdk_pixbuf::Pixbuf> = Vec::new();
    for name in frames {
        let path = format!("/ahfail/sprites/{}", name);
        if let Ok(pb) = gdk_pixbuf::Pixbuf::from_resource(&path) {
            let w = (pb.width() as f64 * SPRITE_SCALE) as i32;
            let h = (pb.height() as f64 * SPRITE_SCALE) as i32;
            let scaled = pb.scale_simple(w, h, InterpType::Bilinear).unwrap_or(pb);
            loaded.push(scaled);
        }
    }
    if loaded.is_empty() { return None; }

    let first = &loaded[0];
    let anim = gdk_pixbuf::PixbufSimpleAnim::new(first.width(), first.height(), 12.0);
    anim.set_loop(true);
    for frame in loaded { anim.add_frame(&frame); }
    Some(anim.upcast())
}
