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

const shootingPlayers = new Map();
const SHOOT_INTERVAL = 90;
const lastShootTimes = new Map();

function startShooting(player) {
    const playerId = player.id;
    const currentTime = Date.now();
    
    if (shootingPlayers.has(playerId)) {
        return;
    }
    
    const playerLastShootTime = lastShootTimes.get(playerId) || 0;
    
    if (currentTime - playerLastShootTime < SHOOT_INTERVAL) {
        return;
    }
    
    lastShootTimes.set(playerId, currentTime);
    
    const makeShot = () => {
        if (!player.isValid()) return;
        
        const command = player.isSneaking ? 
            'execute as @s[scores={sig_m7=1..}, has_property={addon:sig_m7_reload=0}] run function sig_m7/sig_m7_scope' : 
            'execute as @s[scores={sig_m7=1..}, has_property={addon:sig_m7_reload=0}] run function sig_m7/sig_m7_noscope';
        
        player.runCommandAsync(command).catch(() => {});
        
        system.runTimeout(() => {
            if (player.isValid()) {
                player.runCommandAsync('execute as @s run fill ~3 ~3 ~3 ~-3 ~-3 ~-3 air replace block:custom_light').catch(() => {});
            }
        }, 5);
        
        lastShootTimes.set(playerId, Date.now());
    };
    
    makeShot();
    
    const intervalId = system.runInterval(() => {
        if (!player.isValid()) {
            stopShooting(playerId);
            return;
        }
        
        const currentTime = Date.now();
        if (currentTime - lastShootTimes.get(playerId) >= SHOOT_INTERVAL) {
            makeShot();
        }
    }, 1);
    
    shootingPlayers.set(playerId, intervalId);
}

function stopShooting(playerId) {
    const intervalId = shootingPlayers.get(playerId);
    if (intervalId) {
        system.clearRun(intervalId);
        shootingPlayers.delete(playerId);
    }
}

world.afterEvents.itemUse.subscribe(({ itemStack, source }) => {
    if (itemStack.typeId === 'addon:sig_m7') {
        startShooting(source);
    }
});

world.afterEvents.itemStopUse.subscribe(({ source }) => {
    stopShooting(source.id);
});

world.afterEvents.playerLeave.subscribe(({ playerId }) => {
    stopShooting(playerId);
    lastShootTimes.delete(playerId);
});