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

world.beforeEvents.worldInitialize.subscribe((Initiate) => {
    Initiate.blockComponentRegistry.registerCustomComponent("ecbl_bc:stair_test", {
        onStepOn: (e) => {
            e.block.setPermutation(e.block.permutation.withState('ecbl_bc:full_block', true));
            if (e.entity.getVelocity().y <= 0) return;
            if (Math.floor(e.entity.location.y) == Math.floor(e.block.location.y)) {
                // const vel = e.entity.getVelocity();
                // e.entity.teleport({ ...e.entity.location, y: e.entity.location.y + 0.5 });
                // const length = Math.sqrt(vel.x * vel.x + vel.z * vel.z);
                // const directionX = length !== 0 ? vel.x / length : 0;
                // const directionZ = length !== 0 ? vel.z / length : 0;

                // // Choose your strengths (you can adjust these values as needed)
                // const horizontalStrength = Math.sqrt(vel.x * vel.x + vel.z * vel.z); // or a fixed value
                // const verticalStrength = 0; // or a fixed vertical boost

                //e.entity.applyKnockback(directionX, directionZ, horizontalStrength, verticalStrength);

                const direction = e.block.permutation.getState('minecraft:cardinal_direction');
                const directionToVector = {
                    'north': { x: 0, z: 1 },
                    'south': { x: 0, z: -1 },
                    'east': { x: -1, z: 0 },
                    'west': { x: 1, z: 0 }
                }

                e.entity.applyKnockback(0, 0, 0, 0.36);
                system.runTimeout(() => {
                    try {
                        const vector = directionToVector[direction];
                        e.entity.applyKnockback(vector.x, vector.z, 0.2, 0.05)
                    } catch { }
                }, 2);
            }
        },
        onStepOff: (e) => {
            const resetStairs = () => {
                const { entity, block } = e
                const entityLocation = entity.location;
                const blockCenter = block.center;

                const dx = entityLocation.x - blockCenter.x;
                const dz = entityLocation.z - blockCenter.z;
                const distance = Math.sqrt(dx * dx + dz * dz);

                if (distance < 0.6) throw new error();

                e.block.setPermutation(e.block.permutation.withState('ecbl_bc:full_block', false));
            }

            const d = system.runInterval(() => {
                try {
                    resetStairs();
                    system.clearRun(d);
                } catch (e) { }
            }, 15)
        }
    });
});