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

const WEAPONS = {
    'addon:glock18': 'glock18/glock18_hold',
    'addon:deagle': 'deagle/deagle_hold',
    'addon:ak105': 'ak105/ak105_hold',
    'addon:m17': 'm17/m17_hold',
    'addon:mac10': 'mac10/mac10_hold',
    'addon:mp7': 'mp7/mp7_hold',
    'addon:p226': 'p226/p226_hold',
    'addon:scarh': 'scarh/scarh_hold',
    'addon:sig_m7': 'sig_m7/sig_m7_hold',
    'addon:m500': 'm500/m500_hold',
    'addon:glock17': 'glock17/glock17_hold'
};

const CHECK_INTERVAL = 2;

system.runInterval(() => {
    const players = world.getPlayers();
    
    for (const player of players) {
        if (!player.isValid()) continue;
        
        const currentHeldItem = getHeldItem(player);
        const command = WEAPONS[currentHeldItem];
        
        if (command) {
            player.runCommandAsync(`function ${command}`)
                .catch(() => {});
        }
    }
}, CHECK_INTERVAL);

function getHeldItem(player) {
    try {
        const inventory = player.getComponent('minecraft:inventory');
        if (inventory?.container) {
            const selectedSlot = player.selectedSlot;
            const heldItem = inventory.container.getSlot(selectedSlot);
            return heldItem?.typeId || null;
        }
    } catch (error) {
        try {
            const equipment = player.getComponent('minecraft:equippable');
            if (equipment) {
                const mainhand = equipment.getEquipment('Mainhand');
                return mainhand?.typeId || null;
            }
        } catch (e) {}
    }
    return null;
}