import { system, world } from "@minecraft/server";
import { Saturation_control } from "./dungeonsaturation_control";

const MAX_SATURATION = 16;
const INITIAL_SATURATION = 5;

// Sistema de regeneración basado en saturación
system.runInterval(() => {
    world.getAllPlayers().forEach((player) => {
        const saturation = player.getDynamicProperty("dungeon:saturation") || 0;
        const healthComponent = player.getComponent("health");

        if (healthComponent.currentValue > 0 && healthComponent.currentValue < healthComponent.effectiveMax && saturation >= 6) {
            healthComponent.setCurrentValue(healthComponent.currentValue + 0.5);
            player.setDynamicProperty("dungeon:saturation", saturation - 0.5);
        }
    });
}, 10);

// Manejo del consumo de alimentos
world.afterEvents.itemCompleteUse.subscribe((event) => {
    const { itemStack, source: player } = event;
    const saturationGain = Saturation_control[itemStack.typeId] || 0;
    if (saturationGain === 0) return;

    const currentSaturation = player.getDynamicProperty("dungeon:saturation") || 0;
    player.setDynamicProperty("dungeon:saturation", Math.min(currentSaturation + saturationGain, MAX_SATURATION));
});

// Restablecimiento de saturación al morir
world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
    if (deadEntity?.typeId === "minecraft:player") {
        deadEntity.setDynamicProperty("dungeon:saturation", INITIAL_SATURATION);
    }
});

// Establecer saturación inicial al aparecer
world.afterEvents.playerSpawn.subscribe(({ player }) => {
    if (!player.hasTag("dungeon:saturation_spawned")) {
        player.setDynamicProperty("dungeon:saturation", INITIAL_SATURATION);
        player.addTag("dungeon:saturation_spawned");
    }
});
