const SOUNDS = {
    jump:  new Audio('assets/sfx/jump.mp3'),
    duck:  new Audio('assets/sfx/duck.mp3'),
    coin:  new Audio('assets/sfx/coin.mp3'),
    hit:   new Audio('assets/sfx/hit.mp3'),
    powerup: new Audio('assets/sfx/powerup.mp3'),
    music: new Audio('assets/sfx/music_loop.mp3')
};

// Config
SOUNDS.jump.volume = 0.4;
SOUNDS.coin.volume = 0.3;
SOUNDS.hit.volume = 0.6;
SOUNDS.music.loop = true;
SOUNDS.music.volume = 0.2;

// Standard: Pitch beibehalten (WICHTIG für euch!)
if (SOUNDS.music.preservesPitch !== undefined) {
    SOUNDS.music.preservesPitch = true;
} else if (SOUNDS.music.mozPreservesPitch !== undefined) {
    SOUNDS.music.mozPreservesPitch = true; // Firefox Fallback
} else if (SOUNDS.music.webkitPreservesPitch !== undefined) {
    SOUNDS.music.webkitPreservesPitch = true; // Safari Fallback
}

// Mute Status laden
let isMuted = localStorage.getItem('escape_muted') === 'true';

function playSound(name) {
    if (isMuted || !SOUNDS[name]) return;
    const soundClone = SOUNDS[name].cloneNode();
    soundClone.volume = SOUNDS[name].volume;
    soundClone.play().catch(() => {});
}

function toggleMute() {
    isMuted = !isMuted;
    localStorage.setItem('escape_muted', isMuted);

    if(isMuted) SOUNDS.music.pause();
    else SOUNDS.music.play().catch(()=>{});

    return isMuted;
}

function startMusic() {
    if(!isMuted) SOUNDS.music.play().catch(e => console.log("Audio Autoplay blocked"));
}

function getMuteState() {
    return isMuted;
}

// --- GESCHWINDIGKEIT ANPASSEN ---
function setMusicSpeed(gameSpeed) {
    if (isMuted || !SOUNDS.music) return;

    const baseGameSpeed = 15.0; // Muss zu BASE_SPEED in config.js passen

    // Faktor berechnen: Speed 30 = Musik 1.3x
    let rate = 1.0 + (gameSpeed - baseGameSpeed) * 0.02;

    // Limits
    if (rate < 1.0) rate = 1.0;
    if (rate > 2.0) rate = 2.0;

    // Nur bei spürbarer Änderung anwenden
    if (Math.abs(SOUNDS.music.playbackRate - rate) > 0.05) {
        SOUNDS.music.playbackRate = rate;
    }
}

function resetMusicSpeed() {
    if (SOUNDS.music) SOUNDS.music.playbackRate = 1.0;
}