#include "defs.h"
#include <math.h>

/* Room descriptor used during generation */
typedef struct {
    int x, y, w, h;
} room_t;

#define MAX_ROOMS 14

/* Monster difficulty tiers: which types can appear at which depth range */
static const int mon_tier_easy[] = {
    MON_GIANT_SPIDER, MON_HAIRY_THING, MON_WILD_DOG_SM, MON_EYELESS_THING,
    MON_GIANT_ANT, MON_VIPER, MON_SLIMY_THING, MON_SLIMY_WORM, -1
};
static const int mon_tier_mid[] = {
    MON_FEATHERED_LIZARD, MON_GREKLE, MON_TROGLODYTE, MON_HORNED_HOPPER,
    MON_CENTIPEDE, MON_QUIVERING_MOUND, MON_TRANSLUCENT_THING,
    MON_MUNCHKIN, MON_WIDGET, MON_RAZORSNOUT, MON_FANGWING, MON_KREE,
    MON_SCALY_THING, MON_FLUTTERBANG, MON_JELLIED_JUMPER, MON_SNAGGLEPUSS,
    MON_ICKY_THING, MON_NEEDLENOSE, MON_PRICKLY_ORB, -1
};
static const int mon_tier_hard[] = {
    MON_ZYTT, MON_TENTACULAR_HORROR, MON_TOOTHY_THING, MON_FLOATING_EYE,
    MON_UNDULATING_MASS, MON_SHIMMERING_HAZE, MON_MECH,
    MON_MANY_ARMED_THING, MON_ICKY_LUMP, MON_BUG_EYED_MONSTER,
    MON_JELLIED_THING, MON_ENFORCER, MON_CYBERNAUT, MON_WADDLING_THING,
    MON_SENTINEL, MON_VAMPIRE_MIST, MON_WILD_DOG, MON_WILD_DOG_LG, -1
};
static const int mon_tier_boss[] = {
    MON_QUIVERING_THING, MON_GIANT_TENT_HORROR, MON_JUDICATOR,
    MON_DROOLING_THING, MON_INQUISITOR, MON_GIBBERING_THING,
    MON_LASEZOID, MON_GROANING_THING, MON_GUARDIAN, MON_DISGUSTING_THING,
    MON_GIANT_ZYTT, MON_HIDEOUS_THING, MON_ROGUE_ANDROID,
    MON_DREADNOUGHT, MON_NEUTRALIZOR, MON_PULSOR, MON_SWAMP_CREATURE,
    MON_ZYTT_COMMANDER, -1
};

/* Loot tiers: item types that can appear at different depth ranges */
static const int loot_shallow[] = {
    IT_ROCK, IT_BUTCHER_KNIFE, IT_RUSTY_PIPE, IT_BONE, IT_SKULL,
    IT_BOTTLE_TOP, IT_MILK_CARTON, IT_STALE_COOKIE, IT_EMPTY_BEER_CAN,
    IT_BROKEN_BOTTLE, IT_DIRTY_RAG, IT_BRICK, IT_WOODEN_CLUB,
    IT_LIGHT_GLOBE, IT_COIN, IT_PILL, IT_TRASH_CAN, IT_FLARE,
    IT_SM_WOODEN_CRATE, IT_STEPLADDER, IT_SOFT_PILLOW, IT_BOTTLE, -1
};
static const int loot_mid[] = {
    IT_COMBAT_KNIFE, IT_CROWBAR, IT_MACHETE, IT_ANTIQUE_SWORD,
    IT_LEATHER_JACKET, IT_ARMORED_VEST, IT_JACKET, IT_HELMET,
    IT_GAS_MASK, IT_GYROJET_PISTOL, IT_GYROJET, IT_LASER_PISTOL,
    IT_POWERCELL, IT_COIN, IT_PILL, IT_LIGHT_GLOBE, IT_SECURITY_BADGE,
    IT_KEYCARD, IT_GRENADE, IT_INFRARED_GOGGLES, IT_WOODEN_CRATE,
    IT_SM_METAL_LOCKER, IT_NEEDLE, IT_NEEDLER, IT_PAINT_PELLET,
    IT_AIR_GUN, IT_EAR_PROTECTORS, IT_SCREAMER, IT_PICKAXE,
    IT_GRAVBELT, IT_TOWEL, IT_MIRROR, IT_SONIC_SCREWDRIVER, -1
};
static const int loot_deep[] = {
    IT_BLASTER, IT_BLASTER_RIFLE, IT_LASER_RIFLE, IT_GYROJET_RIFLE,
    IT_GYROJET_SHOTGUN, IT_KEVLAR_JACKET, IT_KEVLAR_SUIT,
    IT_BATTLE_ARMOR, IT_FORCEFIELD_PACK, IT_LARGE_POWERCELL,
    IT_MACRO_METAL_JACKET, IT_MACRO_METAL_KNIFE, IT_MACRO_METAL_HELMET,
    IT_MACRO_METAL_ARMOR, IT_BATTLE_JACKET, IT_BATTLE_HELMET,
    IT_VIBRA_KNIFE, IT_VIBRA_SWORD, IT_VIBRA_LANCE, IT_MOLY_BLADE,
    IT_STUNROD, IT_STIMMER, IT_DISCOMBOBULATOR, IT_DISRUPTOR,
    IT_DISFLORGER, IT_DISINTEGRATOR, IT_PLASMA_CANNON, IT_HELGUN,
    IT_NEURO_WHIP, IT_HOLO_CUBE, IT_LAWS_ROCKET, IT_SCRAMBLER,
    IT_POWERPACK, IT_REPULSOR, IT_TIME_DILATOR, IT_CHAMELEON_CIRCUIT,
    IT_BIOCHEM_JUMPSUIT, IT_SPACESUIT, IT_OXYGEN_CYLINDER,
    IT_MAGNETOMETER, IT_RADOMETER, IT_JAUNT_BOX, IT_STASIS_BAG,
    IT_COLLOIDAL_JACKET, IT_COLLOIDAL_ARMOR, IT_EXOSKELETON,
    IT_LG_WOODEN_CRATE, IT_METAL_LOCKER, IT_LG_METAL_LOCKER, -1
};

static int tier_len(const int *tier)
{
    int n = 0;
    while (tier[n] != -1) n++;
    return n;
}

static int pick_from_tier(const int *tier)
{
    int n = tier_len(tier);
    if (n == 0) return 0;
    return tier[rng(0, n - 1)];
}

/* ---- Level allocation ---- */

void map_init(void)
{
    for (int i = 0; i < MAX_LEVELS; i++)
        G->levels[i] = NULL;
    G->cur_level = 0;
    G->n_levels = 0;
}

level_t *map_get_level(int depth)
{
    if (depth < 0 || depth >= MAX_LEVELS) return NULL;
    if (!G->levels[depth]) {
        G->levels[depth] = calloc(1, sizeof(level_t));
        if (!G->levels[depth]) return NULL;
        map_generate(G->levels[depth], depth);
        if (depth >= G->n_levels)
            G->n_levels = depth + 1;
    }
    return G->levels[depth];
}

/* ---- Room placement ---- */

static int rooms_overlap(room_t *a, room_t *b)
{
    return !(a->x + a->w + 1 < b->x || b->x + b->w + 1 < a->x ||
             a->y + a->h + 1 < b->y || b->y + b->h + 1 < a->y);
}

static void carve_room(level_t *lev, room_t *r)
{
    for (int y = r->y; y < r->y + r->h; y++)
        for (int x = r->x; x < r->x + r->w; x++)
            lev->map[y][x].tile = T_FLOOR;
}

static void carve_h_corridor(level_t *lev, int x1, int x2, int y)
{
    if (y < 0 || y >= MAP_H) return;
    int lo = x1 < x2 ? x1 : x2;
    int hi = x1 < x2 ? x2 : x1;
    for (int x = lo; x <= hi; x++) {
        if (x < 0 || x >= MAP_W) continue;
        if (lev->map[y][x].tile == T_WALL)
            lev->map[y][x].tile = T_FLOOR;
    }
}

static void carve_v_corridor(level_t *lev, int y1, int y2, int x)
{
    if (x < 0 || x >= MAP_W) return;
    int lo = y1 < y2 ? y1 : y2;
    int hi = y1 < y2 ? y2 : y1;
    for (int y = lo; y <= hi; y++) {
        if (y < 0 || y >= MAP_H) continue;
        if (lev->map[y][x].tile == T_WALL)
            lev->map[y][x].tile = T_FLOOR;
    }
}

static void connect_rooms(level_t *lev, room_t *a, room_t *b)
{
    int ax = a->x + a->w / 2;
    int ay = a->y + a->h / 2;
    int bx = b->x + b->w / 2;
    int by = b->y + b->h / 2;

    if (rng(0, 1)) {
        carve_h_corridor(lev, ax, bx, ay);
        carve_v_corridor(lev, ay, by, bx);
    } else {
        carve_v_corridor(lev, ay, by, ax);
        carve_h_corridor(lev, ax, bx, by);
    }
}

/* Place a door at a transition point between corridor and room */
static void place_doors(level_t *lev, int depth)
{
    for (int y = 1; y < MAP_H - 1; y++) {
        for (int x = 1; x < MAP_W - 1; x++) {
            if (lev->map[y][x].tile != T_FLOOR) continue;
            int wall_h = (lev->map[y][x-1].tile == T_WALL &&
                          lev->map[y][x+1].tile == T_WALL);
            int wall_v = (lev->map[y-1][x].tile == T_WALL &&
                          lev->map[y+1][x].tile == T_WALL);
            int floor_h = (x > 1 && x < MAP_W - 2 &&
                           lev->map[y][x-1].tile != T_WALL &&
                           lev->map[y][x+1].tile != T_WALL);
            int floor_v = (y > 1 && y < MAP_H - 2 &&
                           lev->map[y-1][x].tile != T_WALL &&
                           lev->map[y+1][x].tile != T_WALL);

            /* Chokepoint: walls on two opposite sides, open on other two */
            int is_chokepoint = (wall_h && !wall_v && !floor_h) ||
                                (wall_v && !wall_h && !floor_v);
            if (!is_chokepoint) continue;
            if (!rng_chance(40)) continue;

            if (rng_chance(15 + depth)) {
                lev->map[y][x].tile = T_DOOR_LOCKED;
                lev->map[y][x].install_type = 'A' + rng(0, 5);
            } else if (rng_chance(30)) {
                lev->map[y][x].tile = T_DOOR_OPEN;
            } else {
                lev->map[y][x].tile = T_DOOR_CLOSED;
            }
        }
    }
}

/* Find a random floor tile in the level */
static int find_open_spot(level_t *lev, int *ox, int *oy)
{
    for (int tries = 0; tries < 500; tries++) {
        int x = rng(1, MAP_W - 2);
        int y = rng(1, MAP_H - 2);
        if (lev->map[y][x].tile == T_FLOOR) {
            int occupied = 0;
            for (int m = 0; m < lev->n_monsters; m++) {
                if (lev->monsters[m].active &&
                    lev->monsters[m].x == x && lev->monsters[m].y == y) {
                    occupied = 1;
                    break;
                }
            }
            if (!occupied) {
                *ox = x;
                *oy = y;
                return 1;
            }
        }
    }
    return 0;
}

/* Place stairs */
static void place_stairs(level_t *lev, int depth)
{
    int x, y;
    if (depth > 0) {
        if (find_open_spot(lev, &x, &y))
            lev->map[y][x].tile = T_STAIRS_UP;
    }
    if (depth < MAX_LEVELS - 1) {
        if (find_open_spot(lev, &x, &y))
            lev->map[y][x].tile = T_STAIRS_DOWN;
    }
}

/* Place hazards: holes, waste, pits, special pads */
static void place_hazards(level_t *lev, int depth)
{
    int n_hazards = rng(0, 2 + depth / 3);
    for (int i = 0; i < n_hazards; i++) {
        int x, y;
        if (!find_open_spot(lev, &x, &y)) continue;
        int r = rng(0, 100);
        if (r < 25)
            lev->map[y][x].tile = T_HOLE;
        else if (r < 50)
            lev->map[y][x].tile = T_WASTE;
        else if (r < 70)
            lev->map[y][x].tile = T_PIT;
        else if (r < 85 && depth >= 3)
            lev->map[y][x].tile = T_FLOATER_PAD;
        else if (r < 95 && depth >= 5)
            lev->map[y][x].tile = T_JAUNT_PLATE;
        else if (depth >= 7)
            lev->map[y][x].tile = T_OMNIFLOW;
    }
}

/* Choose a monster type appropriate for the depth */
static int pick_monster_for_depth(int depth)
{
    if (depth <= 3)
        return pick_from_tier(mon_tier_easy);
    else if (depth <= 8)
        return rng_chance(30) ? pick_from_tier(mon_tier_mid)
                              : pick_from_tier(mon_tier_easy);
    else if (depth <= 15)
        return rng_chance(40) ? pick_from_tier(mon_tier_hard)
                              : pick_from_tier(mon_tier_mid);
    else if (depth <= 22)
        return rng_chance(20) ? pick_from_tier(mon_tier_boss)
                              : pick_from_tier(mon_tier_hard);
    else
        return rng_chance(40) ? pick_from_tier(mon_tier_boss)
                              : pick_from_tier(mon_tier_hard);
}

/* Scatter monsters into the level */
static void place_monsters(level_t *lev, int depth)
{
    int base = 3 + depth;
    int count = rng(base, base + 4);
    if (count > MAX_MONSTERS) count = MAX_MONSTERS;

    for (int i = 0; i < count; i++) {
        int x, y;
        if (!find_open_spot(lev, &x, &y)) break;
        int mtype = pick_monster_for_depth(depth);
        monster_spawn(lev, mtype, x, y);
    }

    /* Utility bots appear on most levels */
    if (depth >= 2 && rng_chance(50)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            monster_t *m = monster_spawn(lev, MON_UTILITY_BOT, x, y);
            if (m) m->friendly = 1;
        }
    }

    /* RoboCop on deeper levels */
    if (depth >= 8 && rng_chance(30)) {
        int x, y;
        if (find_open_spot(lev, &x, &y))
            monster_spawn(lev, MON_ROBOCOP, x, y);
    }

    /* Queen Zytt on deep levels (Mission 2 boss) */
    if (depth >= 14 && !G->player.queen_dead && rng_chance(20)) {
        int x, y;
        if (find_open_spot(lev, &x, &y))
            monster_spawn(lev, MON_QUEEN_ZYTT, x, y);
    }
}

/* Choose an item type appropriate for depth */
static int pick_item_for_depth(int depth)
{
    if (depth <= 3)
        return pick_from_tier(loot_shallow);
    else if (depth <= 10)
        return rng_chance(40) ? pick_from_tier(loot_mid)
                              : pick_from_tier(loot_shallow);
    else if (depth <= 20)
        return rng_chance(50) ? pick_from_tier(loot_deep)
                              : pick_from_tier(loot_mid);
    else
        return rng_chance(60) ? pick_from_tier(loot_deep)
                              : pick_from_tier(loot_mid);
}

/* Scatter items onto the floor */
static void place_items(level_t *lev, int depth)
{
    int base = 4 + depth / 2;
    int count = rng(base, base + 5);
    if (count > MAX_ITEMS_FLOOR) count = MAX_ITEMS_FLOOR;

    for (int i = 0; i < count; i++) {
        int x, y;
        if (!find_open_spot(lev, &x, &y)) break;
        if (lev->n_floor_items >= MAX_ITEMS_FLOOR) break;

        int itype = pick_item_for_depth(depth);
        int idx = lev->n_floor_items;
        lev->floor_items[idx] = item_create(itype);
        lev->floor_item_x[idx] = x;
        lev->floor_item_y[idx] = y;
        lev->n_floor_items++;
        lev->map[y][x].items_here = 1;
    }

    /* Place L.A.M.B. on levels 4-7 (Mission 1 objective) */
    if (depth >= 4 && depth <= 7 && !G->lamb_placed && rng_chance(25)) {
        int x, y;
        if (find_open_spot(lev, &x, &y) && lev->n_floor_items < MAX_ITEMS_FLOOR) {
            int idx = lev->n_floor_items;
            lev->floor_items[idx] = item_create(IT_LAMB);
            lev->floor_item_x[idx] = x;
            lev->floor_item_y[idx] = y;
            lev->n_floor_items++;
            lev->map[y][x].items_here = 1;
            G->lamb_placed = 1;
        }
    }
}

/* Place installations (AutoDoc, Transmat, Vending, etc.) */
static void place_installations(level_t *lev, int depth)
{
    if (depth >= 2 && rng_chance(40)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_AUTODOC;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 3 && rng_chance(30)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_TRANSMAT;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 1 && rng_chance(35)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_VENDING_MACHINE;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 2 && rng_chance(25)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_BANK;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 4 && rng_chance(20)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_WATER_FOUNTAIN;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 5 && rng_chance(15)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_SMALL_GENERATOR;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 6 && rng_chance(20)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_FACTORY_OUTLET;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 4 && rng_chance(20)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_RECLAMATION_CENTER;
            lev->map[y][x].tile = T_FLOOR;
        }
    }
    if (depth >= 8 && rng_chance(15)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_LIBRARIAN;
            lev->map[y][x].tile = T_FLOOR;
        }
    }

    /* StarGate on deep levels (Mission 2 completion) */
    if (depth >= 12 && !G->stargate_placed && rng_chance(15)) {
        int x, y;
        if (find_open_spot(lev, &x, &y)) {
            lev->map[y][x].install_type = IT_STARGATE;
            lev->map[y][x].tile = T_FLOOR;
            G->stargate_placed = 1;
        }
    }
}

/* ---- Main generation entry point ---- */

void map_generate(level_t *lev, int depth)
{
    lev->depth = depth;
    lev->region = depth / 10 + 1;
    lev->n_monsters = 0;
    lev->n_floor_items = 0;
    lev->generated = 1;

    /* Fill with walls */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++) {
            lev->map[y][x].tile = T_WALL;
            lev->map[y][x].explored = 0;
            lev->map[y][x].visible = 0;
            lev->map[y][x].items_here = 0;
            lev->map[y][x].has_trap = 0;
            lev->map[y][x].blood = 0;
            lev->map[y][x].paint = 0;
            lev->map[y][x].install_type = 0;
        }

    /* Generate rooms */
    room_t rooms[MAX_ROOMS];
    int n_rooms = 0;
    int target = rng(5, 12);

    for (int attempt = 0; attempt < 200 && n_rooms < target; attempt++) {
        room_t r;
        r.w = rng(3, 10);
        r.h = rng(3, 7);
        r.x = rng(1, MAP_W - r.w - 2);
        r.y = rng(1, MAP_H - r.h - 2);

        int ok = 1;
        for (int i = 0; i < n_rooms; i++) {
            if (rooms_overlap(&r, &rooms[i])) { ok = 0; break; }
        }
        if (!ok) continue;

        carve_room(lev, &r);
        rooms[n_rooms++] = r;
    }

    /* Connect rooms in sequence, then add a few random extra corridors */
    for (int i = 1; i < n_rooms; i++)
        connect_rooms(lev, &rooms[i - 1], &rooms[i]);

    int extras = rng(0, n_rooms / 3);
    for (int i = 0; i < extras; i++) {
        int a = rng(0, n_rooms - 1);
        int b = rng(0, n_rooms - 1);
        if (a != b) connect_rooms(lev, &rooms[a], &rooms[b]);
    }

    /* Surround the map with walls to ensure a border */
    for (int x = 0; x < MAP_W; x++) {
        lev->map[0][x].tile = T_WALL;
        lev->map[MAP_H - 1][x].tile = T_WALL;
    }
    for (int y = 0; y < MAP_H; y++) {
        lev->map[y][0].tile = T_WALL;
        lev->map[y][MAP_W - 1].tile = T_WALL;
    }

    place_doors(lev, depth);
    place_stairs(lev, depth);
    place_hazards(lev, depth);
    place_installations(lev, depth);
    place_monsters(lev, depth);
    place_items(lev, depth);

    /* Scatter some traps on deeper levels */
    if (depth >= 2) {
        int n_traps = rng(0, 1 + depth / 3);
        for (int i = 0; i < n_traps; i++) {
            int x, y;
            if (find_open_spot(lev, &x, &y))
                lev->map[y][x].has_trap = 1;
        }
    }
}

/* ---- Field of view (recursive shadowcasting) ---- */

#define FOV_RADIUS 8

static int fov_blocked(level_t *lev, int x, int y)
{
    if (x < 0 || x >= MAP_W || y < 0 || y >= MAP_H) return 1;
    int t = lev->map[y][x].tile;
    return (t == T_WALL);
}

/*
 * Octant-based recursive shadowcasting.
 * Each octant transforms (row, col) differently.
 */
static void fov_cast(level_t *lev, int px, int py, int octant,
                     int row, float start_slope, float end_slope)
{
    if (start_slope < end_slope) return;

    float next_start = start_slope;

    for (int i = row; i <= FOV_RADIUS; i++) {
        int blocked = 0;
        int dy = -i;
        for (int dxx = -i; dxx <= 0; dxx++) {
            float l_slope = ((float)dxx - 0.5f) / ((float)dy + 0.5f);
            float r_slope = ((float)dxx + 0.5f) / ((float)dy - 0.5f);

            if (start_slope < r_slope) continue;
            if (end_slope > l_slope) break;

            int mx, my;
            switch (octant) {
            case 0: mx = px + dxx;  my = py + dy;  break;
            case 1: mx = px + dy;   my = py + dxx;  break;
            case 2: mx = px + dy;   my = py - dxx; break;
            case 3: mx = px + dxx;  my = py - dy;  break;
            case 4: mx = px - dxx;  my = py - dy;  break;
            case 5: mx = px - dy;   my = py - dxx; break;
            case 6: mx = px - dy;   my = py + dxx;  break;
            case 7: mx = px - dxx;  my = py + dy;  break;
            default: mx = px; my = py; break;
            }

            if (mx < 0 || mx >= MAP_W || my < 0 || my >= MAP_H) {
                blocked = 1;
                next_start = r_slope;
                continue;
            }

            float dist = sqrtf((float)((mx-px)*(mx-px) + (my-py)*(my-py)));
            if (dist <= (float)FOV_RADIUS) {
                lev->map[my][mx].visible = 1;
                lev->map[my][mx].explored = 1;
            }

            if (blocked) {
                if (fov_blocked(lev, mx, my)) {
                    next_start = r_slope;
                } else {
                    blocked = 0;
                    start_slope = next_start;
                }
            } else if (fov_blocked(lev, mx, my)) {
                blocked = 1;
                next_start = r_slope;
                fov_cast(lev, px, py, octant, i + 1, start_slope, l_slope);
            }
        }
        if (blocked) break;
    }
}

void map_update_fov(void)
{
    level_t *lev = G->levels[G->cur_level];
    if (!lev) return;

    /* Clear visibility */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            lev->map[y][x].visible = 0;

    int px = G->player.x;
    int py = G->player.y;

    /* Player's own cell is always visible */
    lev->map[py][px].visible = 1;
    lev->map[py][px].explored = 1;

    /* If blinded, only see own tile */
    if (G->player.status & SF_BLINDED) return;

    for (int oct = 0; oct < 8; oct++)
        fov_cast(lev, px, py, oct, 1, 1.0f, 0.0f);
}

/* ---- Query functions ---- */

int map_passable(int x, int y)
{
    if (x < 0 || x >= MAP_W || y < 0 || y >= MAP_H) return 0;
    level_t *lev = G->levels[G->cur_level];
    if (!lev) return 0;
    int t = lev->map[y][x].tile;
    switch (t) {
    case T_WALL:
    case T_DOOR_CLOSED:
    case T_DOOR_LOCKED:
        return 0;
    default:
        return 1;
    }
}

int map_has_monster(int x, int y)
{
    return map_monster_at(x, y) != NULL;
}

monster_t *map_monster_at(int x, int y)
{
    level_t *lev = G->levels[G->cur_level];
    if (!lev) return NULL;
    for (int i = 0; i < lev->n_monsters; i++) {
        if (lev->monsters[i].active &&
            lev->monsters[i].x == x && lev->monsters[i].y == y)
            return &lev->monsters[i];
    }
    return NULL;
}

int map_line_of_sight(int x1, int y1, int x2, int y2)
{
    level_t *lev = G->levels[G->cur_level];
    if (!lev) return 0;

    int ddx = abs(x2 - x1);
    int ddy = abs(y2 - y1);
    int sx = x1 < x2 ? 1 : -1;
    int sy = y1 < y2 ? 1 : -1;
    int err = ddx - ddy;

    int cx = x1, cy = y1;
    while (cx != x2 || cy != y2) {
        int e2 = 2 * err;
        if (e2 > -ddy) { err -= ddy; cx += sx; }
        if (e2 <  ddx) { err += ddx; cy += sy; }
        if (cx == x2 && cy == y2) return 1;
        if (cx < 0 || cx >= MAP_W || cy < 0 || cy >= MAP_H) return 0;
        if (lev->map[cy][cx].tile == T_WALL) return 0;
        if (lev->map[cy][cx].tile == T_DOOR_CLOSED) return 0;
        if (lev->map[cy][cx].tile == T_DOOR_LOCKED) return 0;
    }
    return 1;
}
