#include "defs.h"

void player_init(player_t *p)
{
    memset(p, 0, sizeof(*p));
    strncpy(p->name, "Capt. Hazard", MAX_NAME - 1);
    p->alive = 1;
    p->mission = MISSION_1_ACTIVE;
    p->wielded = -1;
    p->reserve = -1;
    p->worn_armor = -1;
    p->worn_helmet = -1;
    p->worn_headgear = -1;
    p->session_start = time(NULL);
}

void player_roll_stats(player_t *p)
{
    p->str = 8 + rng(0, 8);
    p->dex = 8 + rng(0, 8);
    p->spd = 8 + rng(0, 8);
    p->con = 8 + rng(0, 8);
    p->intel = 8 + rng(0, 8);
    p->wis = 8 + rng(0, 8);
    p->chr = 8 + rng(0, 8);
    p->level = 1;
    p->max_hp = 8 + p->con / 2;
    p->hp = p->max_hp;
    p->ac = 0;
    p->wc = 0;
    p->eps = 0;
    p->bonus_pts = 0;
    p->penalty_pts = 0;
    p->region = 1;
    p->depth = 0;
    p->weight_carried = 0;
    p->savings = 0;

    /* Starting equipment: combat knife and leather jacket */
    item_t knife = item_create(IT_COMBAT_KNIFE);
    item_t jacket = item_create(IT_LEATHER_JACKET);
    item_t globe = item_create(IT_LIGHT_GLOBE);
    globe.is_active = 1;
    globe.charges = 500;

    p->inventory[0] = knife;
    p->inventory[1] = jacket;
    p->inventory[2] = globe;
    p->inv_count = 3;
    p->wielded = 0;
    p->worn_armor = 1;
    p->wc = 3;
    p->ac = 1;
}

int player_total_weight(player_t *p)
{
    int w = 0;
    for (int i = 0; i < p->inv_count; i++)
        w += p->inventory[i].weight * p->inventory[i].qty;
    return w;
}

int player_max_weight(player_t *p)
{
    return p->str * 10;
}

void player_move(int dir)
{
    player_t *p = &G->player;
    level_t *lev = G->levels[G->cur_level];

    if (dir == DIR_UP) { player_go_up(); return; }
    if (dir == DIR_DOWN) { player_go_down(); return; }
    if (dir == DIR_STAY) { player_rest(); return; }

    int nx = p->x + dx[dir];
    int ny = p->y + dy[dir];

    if (nx < 0 || nx >= MAP_W || ny < 0 || ny >= MAP_H) {
        msg("You walked into a wall");
        return;
    }

    cell_t *c = &lev->map[ny][nx];

    if (c->tile == T_WALL) {
        msg("You walked into a wall");
        if (player_has_status(SF_CONFUSED) && rng_chance(20)) {
            msg("... and hurt yourself!");
            player_take_damage(1, "walked into a wall");
        }
        return;
    }

    if (c->tile == T_DOOR_CLOSED) {
        msg("The door is closed");
        return;
    }

    if (c->tile == T_DOOR_LOCKED) {
        msg("It's locked ...");
        return;
    }

    /* Check for monster */
    monster_t *m = map_monster_at(nx, ny);
    if (m && m->active) {
        combat_attack(dir);
        return;
    }

    if (!map_passable(nx, ny)) {
        msg("You can't go there");
        return;
    }

    p->x = nx;
    p->y = ny;

    /* Environmental effects */
    if (c->tile == T_WASTE) {
        msg("Splash!");
        msg("... you fell into a rather vile smelling liquid ...");
        if (rng_chance(30)) {
            msg("... you don't feel very well ...");
            player_add_status(SF_POISONED, 10 + rng(0, 10));
        }
    }

    if (c->tile == T_PIT) {
        msg("There is a debris-filled pit here");
    }

    if (c->blood) {
        msg("The floor is slick with blood and grime");
    }

    if (c->paint) {
        msg("There are paint splotches here");
    }

    /* Auto-pickup or notify of items */
    if (c->items_here > 0) {
        for (int i = 0; i < lev->n_floor_items; i++) {
            if (lev->floor_item_x[i] == nx && lev->floor_item_y[i] == ny) {
                if (p->auto_take) {
                    item_pickup();
                } else {
                    msg("You find %s", item_type_name(lev->floor_items[i].type));
                }
                break;
            }
        }
    }

    /* Hole in floor */
    if (c->tile == T_HOLE) {
        msg("There is a large hole in the floor");
    }

    /* Auto-search */
    if (p->auto_search)
        player_search();

    p->turns++;
    player_tick_status();
}

void player_run(int dir)
{
    player_t *p = &G->player;

    if (player_has_status(SF_CONFUSED)) {
        msg("You're too confused to do that ...");
        return;
    }
    if (player_has_status(SF_BLINDED)) {
        msg("You can't see well enough to do that!");
        return;
    }

    for (int i = 0; i < 20; i++) {
        int nx = p->x + dx[dir];
        int ny = p->y + dy[dir];

        if (nx < 0 || nx >= MAP_W || ny < 0 || ny >= MAP_H) break;
        if (!map_passable(nx, ny)) break;
        if (map_has_monster(nx, ny)) break;

        p->x = nx;
        p->y = ny;
        p->turns++;

        map_update_fov();

        /* Stop if at intersection */
        int exits = 0;
        for (int d = 0; d < 8; d++) {
            int ex = p->x + dx[d];
            int ey = p->y + dy[d];
            if (ex >= 0 && ex < MAP_W && ey >= 0 && ey < MAP_H &&
                map_passable(ex, ey))
                exits++;
        }
        if (exits > 2) break;

        /* Stop if items here */
        level_t *lev = G->levels[G->cur_level];
        if (lev->map[p->y][p->x].items_here > 0 && !p->ignore_objects)
            break;
    }

    player_tick_status();
}

void player_rest(void)
{
    player_t *p = &G->player;
    p->turns++;
    player_tick_status();
}

void player_search(void)
{
    player_t *p = &G->player;
    level_t *lev = G->levels[G->cur_level];

    for (int d = 0; d < 8; d++) {
        int sx = p->x + dx[d];
        int sy = p->y + dy[d];
        if (sx < 0 || sx >= MAP_W || sy < 0 || sy >= MAP_H) continue;

        cell_t *c = &lev->map[sy][sx];

        /* Discover hidden doors */
        if (c->tile == T_WALL) {
            int found = rng_chance(p->intel + p->wis);
            if (found) {
                int adj_floor = 0;
                for (int dd = 0; dd < 4; dd++) {
                    int ax = sx + dx[dd * 2];
                    int ay = sy + dy[dd * 2];
                    if (ax >= 0 && ax < MAP_W && ay >= 0 && ay < MAP_H &&
                        lev->map[ay][ax].tile == T_FLOOR)
                        adj_floor++;
                }
                if (adj_floor >= 2 && rng_chance(5)) {
                    c->tile = T_DOOR_CLOSED;
                    msg("You found a hidden door!");
                }
            }
        }

        /* Discover traps */
        if (c->has_trap && rng_chance(p->intel / 2 + p->wis / 2)) {
            msg("There is something strange about the floor ...");
        }
    }

    p->turns++;
    player_tick_status();
}

void player_go_up(void)
{
    player_t *p = &G->player;
    level_t *lev = G->levels[G->cur_level];
    cell_t *c = &lev->map[p->y][p->x];

    if (c->tile != T_STAIRS_UP && c->tile != T_HOLE) {
        msg("No way up from here");
        return;
    }

    if (G->cur_level <= 0) {
        if (p->mission == MISSION_1_ACTIVE && !p->has_lamb) {
            msg("As you exit the underground MegaTech facility a QuickLift suddenly appears");
            msg("... and zaps you safely back to Rebel headquarters.  Upon arrival you are");
            msg("... escorted to General Claibourne's office, who shows marked displeasure");
            msg("... at your failure to recover the L.A.M.B.");
            p->penalty_pts += 1000;
            p->mission = MISSION_FAILED;
            return;
        }
        if (p->mission == MISSION_1_ACTIVE && p->has_lamb) {
            msg("As you exit the underground MegaTech facility a QuickLift suddenly appears");
            msg("... and zaps you safely back to Rebel headquarters.  Congratulations and");
            msg("... assorted medals are heaped upon you as General Claibourne leads you off");
            msg("... to a grand celebration held in your honor that lasts for many days.");
            p->bonus_pts += 5000;
            p->mission = MISSION_1_COMPLETE;
            return;
        }
    }

    if (c->tile == T_HOLE) {
        if (player_has_status(SF_FLOATING)) {
            msg("You float up through a hole in the ceiling");
        } else {
            msg("You climb up through a hole in the ceiling");
        }
    }

    if (p->weight_carried > player_max_weight(p)) {
        msg("It seems you are overburdened ...");
        if (rng_chance(30)) {
            msg("... you fall down the stairs");
            player_take_damage(rng(1, 4), "fell down stairs");
        }
    }

    G->cur_level--;
    if (G->cur_level < 0) G->cur_level = 0;

    level_t *nlev = map_get_level(G->cur_level);
    /* Find stairs down on new level to place player */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (nlev->map[y][x].tile == T_STAIRS_DOWN) {
                p->x = x;
                p->y = y;
                goto placed_up;
            }
    /* Fallback: find any floor tile */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (nlev->map[y][x].tile == T_FLOOR) {
                p->x = x;
                p->y = y;
                goto placed_up;
            }
placed_up:
    p->depth = G->cur_level;
    p->region = 1 + G->cur_level / 10;
    msg("Welcome to level %d!", G->cur_level + 1);
}

void player_go_down(void)
{
    player_t *p = &G->player;
    level_t *lev = G->levels[G->cur_level];
    cell_t *c = &lev->map[p->y][p->x];

    if (c->tile != T_STAIRS_DOWN && c->tile != T_HOLE) {
        msg("No way down from here");
        return;
    }

    if (c->tile == T_HOLE) {
        if (player_has_status(SF_FLOATING)) {
            msg("You float down through the hole");
        } else {
            msg("You drop through the hole");
            if (p->weight_carried > player_max_weight(p)) {
                msg("You collapse under your load");
                player_take_damage(rng(2, 6), "collapsed under load");
            }
        }
    }

    if (p->weight_carried > player_max_weight(p)) {
        msg("It seems you are carrying more than you can easily handle ...");
    }

    G->cur_level++;
    if (G->cur_level >= MAX_LEVELS) G->cur_level = MAX_LEVELS - 1;

    level_t *nlev = map_get_level(G->cur_level);
    /* Find stairs up on new level */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (nlev->map[y][x].tile == T_STAIRS_UP) {
                p->x = x;
                p->y = y;
                goto placed_down;
            }
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (nlev->map[y][x].tile == T_FLOOR) {
                p->x = x;
                p->y = y;
                goto placed_down;
            }
placed_down:
    p->depth = G->cur_level;
    p->region = 1 + G->cur_level / 10;
    msg("Welcome to level %d!", G->cur_level + 1);
}

void player_gain_exp(int amt)
{
    player_t *p = &G->player;
    p->eps += amt;

    /* Level-up thresholds */
    static const int thresholds[] = {
        0, 20, 60, 150, 350, 700, 1200, 2000, 3500, 5500,
        8000, 12000, 17000, 24000, 33000, 45000, 60000, 80000,
        105000, 140000, 185000, 250000, 350000, 500000, 750000,
        1000000, 1500000, 2000000, 3000000, 5000000
    };
    int max_lev = (int)(sizeof(thresholds) / sizeof(thresholds[0]));

    while (p->level < max_lev && p->eps >= thresholds[p->level]) {
        p->level++;
        int hp_gain = rng(1, 4) + p->con / 4;
        p->max_hp += hp_gain;
        p->hp += hp_gain;
        msg("Welcome to level %d!", p->level);
    }
}

void player_take_damage(int amt, const char *source)
{
    player_t *p = &G->player;

    if (player_has_status(SF_VULNERABLE))
        amt = amt * 3 / 2;

    p->hp -= amt;
    if (p->hp <= 0) {
        p->hp = 0;
        p->alive = 0;
        display_death(source);
    }
}

void player_heal(int amt)
{
    player_t *p = &G->player;
    p->hp += amt;
    if (p->hp > p->max_hp)
        p->hp = p->max_hp;
}

void player_tick_status(void)
{
    player_t *p = &G->player;

    /* Natural healing */
    if (p->hp < p->max_hp && rng_chance(10 + p->con))
        p->hp++;

    /* Tick down status timers */
    for (int i = 0; i < 23; i++) {
        if (p->status_timers[i] > 0) {
            p->status_timers[i]--;
            if (p->status_timers[i] <= 0) {
                unsigned int flag = 1u << i;
                if (p->status & flag) {
                    p->status &= ~flag;
                    switch (flag) {
                    case SF_BLINDED:   msg("Your eyesight returns"); break;
                    case SF_DIZZY:     msg("You no longer feel dizzy"); break;
                    case SF_CONFUSED:  msg("You no longer feel confused"); break;
                    case SF_STUNNED:   msg("You can move again"); break;
                    case SF_POISONED:  msg("You no longer feel poisoned"); break;
                    case SF_CLUMSY:    msg("You no longer feel clumsy"); break;
                    case SF_WEBBED:    msg("You no longer feel constrained as the spider webbing flakes away ..."); break;
                    case SF_SLEEPING:  msg("You wake up"); break;
                    case SF_FLOATING:  msg("You gently float back to the floor"); break;
                    case SF_SLOWED:    msg("You feel yourself speeding up again"); break;
                    case SF_SPEEDED:   msg("You feel yourself slowing down"); break;
                    case SF_WEAKENED:  msg("You feel stronger"); break;
                    case SF_PAINTED:   msg("The paint flakes away"); break;
                    default: break;
                    }
                }
            }
        }
    }

    /* Poison damage */
    if (player_has_status(SF_POISONED) && rng_chance(20)) {
        msg("You feel ill from the poison ...");
        p->hp--;
        if (p->hp <= 0) {
            p->alive = 0;
            display_death("poisoned");
        }
    }

    /* Radiation damage */
    if (player_has_status(SF_IRRADIATED) && rng_chance(10)) {
        msg("You aren't feeling too well ...");
        p->hp--;
        if (p->hp <= 0) {
            p->alive = 0;
            display_death("died from radiation exposure");
        }
    }

    /* Confused movement randomization happens in input.c */

    /* Light globe charge drain */
    for (int i = 0; i < p->inv_count; i++) {
        if (p->inventory[i].type == IT_LIGHT_GLOBE && p->inventory[i].is_active) {
            p->inventory[i].charges--;
            if (p->inventory[i].charges <= 10 && p->inventory[i].charges > 0 && rng_chance(20))
                msg("Your light globe begins to dim");
            if (p->inventory[i].charges <= 0) {
                p->inventory[i].is_active = 0;
                msg("Your light globe went out");
            }
        }
    }

    p->weight_carried = player_total_weight(p);
}

void player_add_status(unsigned int flag, int duration)
{
    player_t *p = &G->player;
    p->status |= flag;

    /* Find the bit index */
    for (int i = 0; i < 23; i++) {
        if ((1u << i) == flag) {
            if (p->status_timers[i] < duration)
                p->status_timers[i] = duration;
            break;
        }
    }
}

void player_remove_status(unsigned int flag)
{
    player_t *p = &G->player;
    p->status &= ~flag;
    for (int i = 0; i < 23; i++) {
        if ((1u << i) == flag) {
            p->status_timers[i] = 0;
            break;
        }
    }
}

int player_has_status(unsigned int flag)
{
    return (G->player.status & flag) != 0;
}
