// src/render/obstacle.cpp
#include "obstacle.h"
#include "../assets/obstacle_crawl_frames.h"
#include "../assets/background_frame.h"
#include <cstdio>

// Draws an obstacle using bottom‑based world coordinates.
// x = left edge of the collision box in world space
// y = bottom edge of the collision box in world space (0 = ground)
void draw_obstacle(int x, int y, CrawlObstacleType type) {
    const char **obstacle_frame = nullptr;
    int frame_total_height = 0;

    // Collision‑model parameters for this obstacle
    int collision_top_offset = 0;   // rows from visual top to top of collision box
    int collision_height = 0;       // rows tall
    int collision_left_offset = 0;  // columns from visual left to collision left

    switch (type) {
    case CrawlObstacleType::Crawl1:
        obstacle_frame = OBSTACLE_CRAWL1_FRAME;
        frame_total_height = OBSTACLE_CRAWL1_FRAME_HEIGHT;
        collision_top_offset = OBSTACLE_CRAWL1_COLLISION_TOP_OFFSET;
        collision_height = OBSTACLE_CRAWL1_COLLISION_HEIGHT;
        collision_left_offset = OBSTACLE_CRAWL1_COLLISION_LEFT_OFFSET;
        break;

    case CrawlObstacleType::Crawl2:
        obstacle_frame = OBSTACLE_CRAWL2_FRAME;
        frame_total_height = OBSTACLE_CRAWL2_FRAME_HEIGHT;
        collision_top_offset = 0;
        collision_height = OBSTACLE_CRAWL2_COLLISION_HEIGHT;
        collision_left_offset = OBSTACLE_CRAWL2_COLLISION_LEFT_OFFSET;
        break;

    default:
        return; // no rendering for invalid type
    }

    // Convert bottom‑based (world) coordinates to screen coordinates.
    // Y of the collision bottom is given; translate to where to start drawing the visual frame.
    const int frame_row_index_bottom = collision_top_offset + collision_height - 1;
    const int frame_top_world_y = y + frame_row_index_bottom;
    const int frame_top_screen_row = VIEW_HEIGHT - frame_top_world_y;

    // X of the collision box is given; shift left to the visual frame's starting column.
    const int frame_screen_x = x - collision_left_offset;

    for (int i = 0; i < frame_total_height; i++) {
        const int screen_row = frame_top_screen_row + i;
        if (screen_row < 1 || screen_row > VIEW_HEIGHT) continue;
        printf("\033[%d;%dH%s", screen_row, frame_screen_x + 1, obstacle_frame[i]);
    }

    fflush(stdout);
}
