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

const GunShootComponent = {
    onUse({ itemStack, source }) {
        if (!source || !itemStack) return;

        const typeId = itemStack.typeId;

        if (typeId === "fw:10mm_pistol") {
            // Remove Ammo
            source.runCommandAsync("scoreboard players remove @s 10mm_pistol 1").catch(() => {});

            // Fire bullet
            system.run(() => {
                try {
                    const viewDir = source.getViewDirection();
                    const headLoc = source.getHeadLocation();
                    const dimension = source.dimension;

                    if (!viewDir || !headLoc || !dimension) return;

                    const spawnPos = {
                        x: headLoc.x + viewDir.x * 1,
                        y: headLoc.y - 0.05, // Near head height
                        z: headLoc.z + viewDir.z * 1,
                    };

                    const velocity = {
                        x: viewDir.x * 8,
                        y: viewDir.y * 8,
                        z: viewDir.z * 8,
                    };

                    const bullet = dimension.spawnEntity("fw:b10mm_bullet", spawnPos);
                    if (bullet) bullet.applyImpulse(velocity);
                } catch (e) {
                    console.warn("Error firing bullet:", e);
                }
            });
        }
    },
};

world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
    itemComponentRegistry.registerCustomComponent("fw:gun_shoot", GunShootComponent);
});
