
// Función principal de info
export function info(player) {
    const hits = player.getEntitiesFromViewDirection({ maxDistance: 48 });

    if (hits.length > 0) {
        const target = hits[0].entity;

        if (target) {
            handleEntityDisplay(player, target);
        }
    }
}

function hptext(currentHealth, maxHealth) {
    if (!maxHealth || maxHealth <= 0) return "";

    const heartsPerRow = 20;   // salto de línea cada 24
    const maxRows = 1;         // máximo de filas visibles en modo compacto
    const maxVisibleHearts = heartsPerRow * maxRows; 

    if (maxHealth <= 22) {
        const maxHearts = Math.ceil(maxHealth / 2);
        const fullHearts = Math.floor(currentHealth / 2);
        const hasHalfHeart = (currentHealth % 2) === 1;
        const emptyHearts = Math.max(0, maxHearts - fullHearts - (hasHalfHeart ? 1 : 0));

        const heartsArray = [
            ..."".repeat(fullHearts),
            ...(hasHalfHeart ? [""] : []),
            ..."".repeat(emptyHearts),
        ];

        let hearts = "";
        for (let i = 0; i < heartsArray.length; i++) {
            if (i > 0 && i % heartsPerRow === 0) hearts += "\n";
            hearts += heartsArray[i];
        }
// / ${maxHealth}
        return `${hearts} §2${currentHealth}§7§r`;
    }

    let hpPerHeart = Math.ceil(maxHealth / maxVisibleHearts);
    if (hpPerHeart % 2 !== 0) hpPerHeart += 1; // múltiplo de 2 para permitir medio corazón

    const maxHearts = Math.ceil(maxHealth / hpPerHeart);
    const halfUnit = hpPerHeart / 2;

    const fullHearts = Math.floor(currentHealth / hpPerHeart);
    const remainder = currentHealth - (fullHearts * hpPerHeart);
    const hasHalfHeart = remainder >= halfUnit;
    const emptyHearts = Math.max(0, maxHearts - fullHearts - (hasHalfHeart ? 1 : 0));

    let heartsArray = [];
    for (let i = 0; i < fullHearts; i++) heartsArray.push("");
    if (hasHalfHeart && heartsArray.length < maxHearts) heartsArray.push("");
    for (let i = 0; i < emptyHearts; i++) heartsArray.push("");

    let hearts = "";
    for (let i = 0; i < heartsArray.length; i++) {
        if (i > 0 && i % heartsPerRow === 0) hearts += "\n";
        hearts += heartsArray[i];
    }

    const pct = Math.max(0, Math.min(100, Math.floor((currentHealth / maxHealth) * 100)));

    return `${hearts} §2${currentHealth}§7§r`;
}



function handleEntityDisplay(player, entity) {
    const isMinecraftNamespace = entity.typeId.split(":")[0] === "minecraft";
    const health = entity.getComponent("minecraft:health");

   if (
    entity.typeId !== "dungeon:player_controller" &&
    entity.typeId !== "minecraft:item" &&
    entity.typeId !== "dungeon:fireball" &&
    entity.typeId !== "dungeon:beam" &&
    entity.typeId !== "dungeon:stinger_entity" &&
    entity.typeId !== "dungeon:magic_ball"
) {
        player.addTag("viewing_info");
        // Mostrar información de la entidad en la barra de acción
        player.onScreenDisplay.setActionBar([
            { text: "fear;" },
            {
                translate: entity.typeId === "minecraft:player"
                    ? "".concat(entity.name)
                    : `entity.${isMinecraftNamespace ? entity.typeId.split(":")[1] : entity.typeId}.name`
            },
            {
                text: entity.hasComponent("minecraft:movement")
                    ? "\n" // Aquí se agrega el salto de línea fuera de la traducción
                    : null
            },
            {
                translate: entity.hasComponent("minecraft:navigation.walk")
                    ? `dungeon.langcode.navigation.walk.canbreakdoors.${entity.getComponent("minecraft:navigation.walk").canBreakDoors ? "yes" : "no"}`
                    : null
            },
            {
                text: entity.hasComponent("minecraft:navigation.walk")
                    ? "\n" // Aquí se agrega el salto de línea fuera de la traducción
                    : null
            },
           // {
               // translate: entity.hasComponent("minecraft:movement")
              //      ? "dungeon.langcode.speed" // El valor de la velocidad se colocará aquí
            //        : null
          //  },
        //    {
                //text: entity.hasComponent("minecraft:movement")
               //     ? `: ${(entity.getComponent("minecraft:movement").currentValue * 100).toFixed(2)}%`
             //       : null
           // },
            {
                translate: entity.hasComponent("minecraft:fire_immune")
                    ? `dungeon.langcode.fireinmune.${entity.getComponent("minecraft:fire_immune") ? "yes" : "yes"}`
                    : null
            },
            {
                translate: entity.hasComponent("minecraft:fire_immune")
                    ? "\n" // Aquí se agrega el salto de línea fuera de la traducción
                    : null
            },
            {
                translate: entity.hasComponent("minecraft:health")
                    ? `dungeon.langcode.health`
                    : null

            },
            {
                translate: entity.hasComponent("minecraft:health")
                    ? "\n" 
                    : null

            },
            {
                translate: entity.hasComponent("minecraft:health")
                    ? `${hptext(Math.round(health.currentValue), health.effectiveMax)}`
                    : null

            },
        ]);
    }
}
const maxDistance = 6;

export function detectDungeonBlocks(player) {
    const blockHit = player.getBlockFromViewDirection({ maxDistance });

    if (blockHit?.block) {
        const block = blockHit.block;
        const toolInfo = getinformation(block);

        player.addTag("viewing_info");

        const namespace = block.typeId.split(":")[0];
        const blockId = block.typeId.split(":")[1];
        const blockTranslationKey = `tile.${namespace}:${blockId}.name`;

        if (namespace === "dungeon" || namespace === "otherworldly_winter") {
            player.onScreenDisplay.setActionBar([
                { text: "fear;" },
                { translate: blockTranslationKey },
                {
                    text: toolInfo.tool !== "none" ? "" : null
                },
                {
                    text: toolInfo.tool !== undefined
                        ? "\n" // Agregar salto de línea si hay una herramienta
                        : null
                },
                {
                    translate: toolInfo.tool !== "\n"
                        ? "dungeon.langcode.tool.correct_tool"
                        : "dungeon.langcode.tool.none",
                    with: [toolInfo.tool]
                },
                {
                    translate: toolInfo.tool !== "none"
                        ? `dungeon.langcode.tool.${toolInfo.tool.toLowerCase()}`
                        : "dungeon.langcode.tool.none",
                    with: [toolInfo.tool]
                }
            ]);
        } else {
            // Limpiar barra
        }
    } else {
        // Limpiar barra
    }
}

function getinformation(block) {
    if (!block) return { tool: "none", farmable: false };

    const toolCriteria = [
        {
            tool: "Wood",
            matches: [
                "log", "planks", "oak_wood", "birch_wood", "spruce_wood", "jungle_wood", "acacia_wood", "dark_oak_wood", "coal_ore", "stone", "coal_ore", "deepslate", "spidernest", "solid_sand", "cold_stone", "jungle_stone",
            ],
            tags: ["minecraft:wood", "wooden_tier", "dungeon:is_pickaxe_item_destructible"],
        },
        {
            tool: "Stone",
            matches: ["iron_ore", "copper_ore", "silver_ore", "cobalt_ore"],
            tags: ["minecraft:stone", "minecraft:coal_ore", "minecraft:iron_ore"],
        },
        {
            tool: "Iron",
            matches: ["gold_ore", "luminarite_ore","lapis_ore", "redstone_ore", "diamond_ore", "vitalife_ore", "emerald_ore", "quartz_ore"],
            tags: ["minecraft:gold_ore", "minecraft:lapis_ore", "minecraft:redstone_ore", "minecraft:iron_tier_destructible"],
        },
        {
            tool: "Diamond",
            matches: ["netherite_ore", "ancient_debris","jade_ore"],
            tags: ["minecraft:netherite_ore", "minecraft:ancient_debris","minecraft:jade_ore"],
        },
        {
            tool: "Netherite",
            matches: [],
            tags: [],
        },
        {
            tool: "Glimmerite",
            matches: ["glimmerite_ore",],
            tags: ["minecraft:glimmerite_ore"],
        },
        {
            tool: "Viritum",
            matches: ["glimmerite_ore","viritum_ore"],
            tags: ["minecraft:viritum_ore","minecraft:glimmerite_ore"],
        },
        {
            tool: "Silvirum",
            matches: ["purplebrickinfested", "bluebrickinfested", "titanium_ore","purplebrick_crackedinfested"],
            tags: ["dungeon:infestedblockstier2", "dungeon:infestedblockstier1", "dungeon:infestedblockstier0"],
        },
        {
            tool: "none",
            matches: [""],
            tags: [],
        },
    ];

    for (const criteria of toolCriteria) {
        const { tool, matches, tags, exclusions = [], farmable = false } = criteria;

        if (
            matches.some((match) =>
                block.typeId.includes(match) &&
                !exclusions.some((exclude) => block.typeId.includes(exclude))
            )
        ) {
            return { tool: tool, farmable };
        }

        if (tags.some((tag) => block.hasTag(tag))) {
            return { tool: tool, farmable };
        }
    }

    if (block.hasTag("minecraft:crop") || block.hasTag("dirt") || block.hasTag("grass_block") || block.hasTag("wood")) {
        return { tool: "none", farmable: true };
    }

    return { tool: "none", farmable: false };
}







