import * as mc from '@minecraft/server'

const pahoehoeTriggered = new Set();
const triggerExceptions = ['ash_dino', 'light_weight', 'small_dino', 'baby'];

/**
 * 
 * @param {mc.Entity} source 
 * @param {mc.Vector3} location 
 * @returns 
 */
function isActiveChunk(source, location) {
  try {
    return !!source.dimension.getBlock(location);
  } catch {
    return false;
  }
}

export const pahoehoeBlockBehavior = {
    /**
            * 
            * @param {mc.BlockComponentStepOnEvent} e 
            */
    onStepOn(e) {
        const { block, entity } = e;
        try {
            if (!entity) return;

            for (const exception of triggerExceptions) {
                if (entity.getComponent(mc.EntityComponentTypes.TypeFamily)?.hasTypeFamily(exception)) return;
            }

            const blockPos = block.location;
            const dimension = block.dimension;
            const key = `${blockPos.x},${blockPos.y},${blockPos.z}`;
            if (pahoehoeTriggered.has(key)) return;
            pahoehoeTriggered.add(key);
            dimension.playSound('cyd_dino.block.pahoehoe_block.break', blockPos);
            const blockType = block.typeId;

            const currentState = block.permutation.getState('cyd_dino:crack_state') ?? 0;
            let currentDelay = 0;

            if (currentState < 1) {
                currentDelay += 10;
                mc.system.runTimeout(() => {
                    try {
                        const refreshed = isActiveChunk(entity, blockPos);
                        if (!refreshed) return; // chunk not loaded anymore
                        block.setPermutation(block.permutation.withState('cyd_dino:crack_state', 1));
                    } catch (err) {
                    }
                }, currentDelay)
            }

            if (currentState < 2) {
                currentDelay += 10;
                mc.system.runTimeout(() => {
                    try {
                        const refreshed = isActiveChunk(entity, blockPos);
                        if (!refreshed) return;
                        block.setPermutation(block.permutation.withState('cyd_dino:crack_state', 2));
                    } catch (err) {
                    }
                }, currentDelay)
            }

            if (currentState < 3) {
                currentDelay += 10;
                mc.system.runTimeout(() => {
                    try {
                        const refreshed = isActiveChunk(entity, blockPos);
                        if (!refreshed) return;
                        block.setPermutation(block.permutation.withState('cyd_dino:crack_state', 3));
                    } catch (err) {
                    }
                }, currentDelay)
            }

            currentDelay += 10;
            mc.system.runTimeout(async () => {
                try {
                    const refreshed = isActiveChunk(entity, blockPos);
                    if (!refreshed) return; // chunk not loaded anymore
                    if (block.typeId === 'cyd_dino:pahoehoe_lava') {
                        try {
                            await dimension.runCommandAsync(`setblock ${blockPos.x} ${blockPos.y} ${blockPos.z} lava destroy`);
                        } catch (cmdErr) {
                        }
                        if (Math.random() < 0.2) return;
                        await mc.system.waitTicks(1);
                        try {
                            // Recheck loaded before querying entities
                            const stillLoaded = isActiveChunk(entity, blockPos);
                            if (!stillLoaded) return;
                            for (const ent of dimension.getEntities({ location: blockPos, maxDistance: 2, closest: 1, type: 'minecraft:item' })) {
                                const rItems = ent.getComponent('minecraft:item');
                                if (rItems && rItems.itemStack && blockType === rItems.itemStack.typeId) ent.remove();
                            }
                        } catch (entErr) {
                        }
                    }

                } catch (err) {
                } finally {
                    pahoehoeTriggered.delete(key);
                }
            }, currentDelay);
        } catch (error) {
        }
    }
}