// ─── Imports ──────────────────────────────────────────────────────────
import { world, BlockPermutation, ItemStack, system } from '@minecraft/server';

// ─── Helpers ──────────────────────────────────────────────────────────
const GRASS_BY_BIOME = {
    sky:        'pu_biomes:sky_grass',
    toxic:      'pu_biomes:toxic_grass',
    lunar:      'pu_biomes:lunar_grass',
    enchanted:  'pu_biomes:enchanted_grass',
    horror:     'pu_biomes:horror_grass',
    orange:     'pu_biomes:orange_grass',
    red:        'pu_biomes:red_grass'
};

function stripName(name) {
    // removes leading "ground_" and/or "hollow_"
    return name.replace(/^ground_/, '').replace(/^hollow_/, '');
}

function withPrefix(prefix, base) { return `${prefix}_${base}`; }

// Removes the non‑compatible state Minecraft adds to lit camp‑fire logs
function cleanStates(states) {
    const copy = { ...states };
    delete copy['pu_biomes:is_lit'];
    return copy;
}

// ─── Axe‑stripping logic ──────────────────────────────────────────────
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
    const { block, itemStack, player } = ev;
    if (!block.hasTag('pu_biomes:custom_log')) return;                 // not our log
    if (!itemStack?.hasTag('minecraft:is_axe')) return;                // not an axe

    const [ns, rawName] = block.typeId.split(':');                     // e.g. pu_biomes:hollow_sky_log
    const bareName      = stripName(rawName);                          // sky_log
    const targetId      = `${ns}:stripped_${bareName}`;                // pu_biomes:stripped_sky_log

    const strippedPerm  = BlockPermutation.resolve(
        targetId,
        cleanStates(block.permutation.getAllStates())
    );
    if (!strippedPerm) return;

    system.run(() => {
        block.setPermutation(strippedPerm);
        player.playSound('use.wood', {volume: 0.5});

        // durability
        const d = itemStack.getComponent('durability');
        if (d) {
            d.damage++;
            if (d.damage >= d.maxDurability) {
                player.playSound('random.break');
                player.getComponent('equippable')
                      .setEquipment('Mainhand', new ItemStack('minecraft:air', 1));
            }
        }
    });
});

// ─── Placement logic ──────────────────────────────────────────────────
world.afterEvents.playerPlaceBlock.subscribe(ev => {
    const { block } = ev;
    if (!block.hasTag('pu_biomes:custom_log')) return;

    const states           = cleanStates(block.permutation.getAllStates());
    const [ns, rawName]    = block.typeId.split(':');             // pu_biomes:orange_log, hollow_red_log, ground_sky_log …
    const bareName         = stripName(rawName);                  // orange_log, red_log, sky_log …
    const [biome]          = bareName.split('_');                 // orange, red, sky …

    // ── 1.  Convert to ground_… when on matching grass ───────────────
    const below = block.below();
    if (below?.typeId === GRASS_BY_BIOME[biome] && states['minecraft:block_face'] === 'up') {
        const groundId = `${ns}:${withPrefix('ground', bareName)}`; // ground_orange_log, etc.
        block.setPermutation(BlockPermutation.resolve(groundId, states));
        return;
    }

    // ── 2.  25 % chance to become hollow_… (unless already ground_) ──
    if (!rawName.startsWith('ground_') && Math.random() < 0.25) {
        const hollowId = `${ns}:${withPrefix('hollow', bareName)}`; // hollow_orange_log …
        block.setPermutation(BlockPermutation.resolve(hollowId, states));
    }
});