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

const TTAV_SOUND_CONFIGS = [
    {
        minDist: 0,
        maxDist: 20,
        sounds: [
            { name: "ttavExplodeClose", pitch: 1.0, volume: 2 },
            { name: "ttavExplodeBuzzing", pitch: 1.0, volume: 2 }
        ],
        shake: { intensity: 2, duration: 1 }
    },
    {
        minDist: 20,
        maxDist: 35,
        sounds: [
            { name: "ttavExplodeClose", pitch: 1.0, volume: 1.5 },
            { name: "ttavExplodeBuzzing", pitch: 1.0, volume: 1.5 }
        ],
        shake: { intensity: 1.6, duration: 1 }
    },
    {
        minDist: 35,
        maxDist: 50,
        sounds: [
            { name: "ttavExplodeClose", pitch: 1.0, volume: 1.5 },
            { name: "ttavExplodeBuzzing", pitch: 1.0, volume: 1 }
        ],
        shake: { intensity: 0.2, duration: 1 }
    },
    {
        minDist: 50,
        maxDist: 65,
        sounds: [
            { name: "ttavExplodeFar", pitch: 1.0, volume: 1.5 },
            { name: "ttavExplodeBuzzing", pitch: 1.0, volume: 0.3 }
        ],
        shake: { intensity: 0.8, duration: 0.7 }
    },
    {
        minDist: 65,
        maxDist: 80,
        sounds: [
            { name: "ttavExplodeFar", pitch: 1.0, volume: 1.0 },
            { name: "ttavExplodeBuzzing", pitch: 1.0, volume: 0.1 }
        ],
        shake: { intensity: 0.4, duration: 0.7 }
    },
    {
        minDist: 80,
        maxDist: 100,
        sounds: [
            { name: "ttavExplodeFar", pitch: 1.0, volume: 0.5 }
        ],
        shake: { intensity: 0.2, duration: 0.5 }
    }
];

function calculateDistance(pos1, pos2) {
    const dx = pos1.x - pos2.x;
    const dy = pos1.y - pos2.y;
    const dz = pos1.z - pos2.z;
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

export function playTTAVLargeExplosionSounds(source) {
    const sourcePos = source.location;
    for (const player of world.getAllPlayers()) {
        const distance = calculateDistance(sourcePos, player.location);
        const config = TTAV_SOUND_CONFIGS.find(cfg =>
            distance >= cfg.minDist && distance < cfg.maxDist
        );
        
        if (config) {
            for (const sound of config.sounds) {
                player.playSound(sound.name, {
                    pitch: sound.pitch,
                    volume: sound.volume
                });
            }
            
            if (config.shake) {
                player.runCommand(`camerashake add @s ${config.shake.intensity} ${config.shake.duration}`);
            }
        }
    }
}
