use gtk::{gdk_pixbuf, prelude::*};
use rand::Rng;
use crate::config::ModuleConfig;

const SPRITE_MARGIN: i32 = 100;
const RETRY_ATTEMPTS: usize = 10;

pub fn place_sprite(
    fixed: &gtk::Fixed,
    animation: &gdk_pixbuf::PixbufAnimation,
    screen_w: i32,
    screen_h: i32,
    config: &ModuleConfig,
) -> gtk::Image {
    let sprite_w = animation.width();
    let sprite_h = animation.height();

    let max_x = screen_w.saturating_sub(SPRITE_MARGIN).saturating_sub(sprite_w).max(0);
    let max_y = screen_h.saturating_sub(SPRITE_MARGIN).saturating_sub(sprite_h).max(0);

    let mut rng = rand::thread_rng();
    let mut x = rng.gen_range(0..=max_x);
    let mut y = rng.gen_range(0..=max_y);

    if let Some(dz) = config.deadzone {
        for _ in 0..RETRY_ATTEMPTS {
            let overlaps_x = x < dz.x() + dz.width() && x + sprite_w > dz.x();
            let overlaps_y = y < dz.y() + dz.height() && y + sprite_h > dz.y();
            if !(overlaps_x && overlaps_y) {
                break;
            }
            x = rng.gen_range(0..=max_x);
            y = rng.gen_range(0..=max_y);
        }
    }

    let image = gtk::Image::from_animation(animation);
    image.show();
    fixed.put(&image, x, y);
    image
}
