// src/game/obstacle_manager.h
#pragma once
#include "../game/collision.h"
#include "../assets/obstacle_crawl_frames.h"
#include "../assets/background_frame.h"

// Movable obstacle
struct MovingObstacle {
    Obstacle data;
    CrawlObstacleType type;
    bool active;
};

// Fixed obstacle pool
constexpr int MAX_OBSTACLES = 6;
static MovingObstacle obstacle_pool[MAX_OBSTACLES];

// Create / reset obstacle in one slot
inline int spawn_obstacle(CrawlObstacleType type, int x_start) {
    for (int i = 0; i < MAX_OBSTACLES; i++) {
        if (!obstacle_pool[i].active) {
            obstacle_pool[i].active = true;
            obstacle_pool[i].type = type;
	    obstacle_pool[i].data.x = x_start;

            obstacle_pool[i].data.width = (type == CrawlObstacleType::Crawl1) ? OBSTACLE_CRAWL1_COLLISION_WIDTH : OBSTACLE_CRAWL2_COLLISION_WIDTH;
            obstacle_pool[i].data.height = (type == CrawlObstacleType::Crawl1) ? OBSTACLE_CRAWL1_COLLISION_HEIGHT : OBSTACLE_CRAWL2_COLLISION_HEIGHT;

            // Default Y so that the character touches the top of the screen.
            // We store Y as the bottom of the COLLISION BOX in bottom-based world coords.
            int top_offset = 0;
            if (type == CrawlObstacleType::Crawl1) {
                top_offset = OBSTACLE_CRAWL1_COLLISION_TOP_OFFSET;
            } else {
                top_offset = 0;
            }
            const int i_bottom_of_collision = top_offset + obstacle_pool[i].data.height - 1;
            // Top of screen in world coords is VIEW_HEIGHT - 1
            const int collision_bottom_world_y = (VIEW_HEIGHT - 1) - i_bottom_of_collision;
            obstacle_pool[i].data.y = collision_bottom_world_y;

            return i;
        }
    }
    return -1;
}

// Update X positions; mark inactive if offscreen
inline void update_obstacles(int shift_speed) {
    for (int i = 0; i < MAX_OBSTACLES; i++) {
        if (!obstacle_pool[i].active) continue;
        obstacle_pool[i].data.x -= shift_speed;
        if (obstacle_pool[i].data.x + obstacle_pool[i].data.width < 0)
            obstacle_pool[i].active = false;
    }
}
