#pragma once

// --- Includes ---
#include <SDL3/SDL.h>

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

#define STB_VORBIS_HEADER_ONLY
// NOLINTNEXTLINE(bugprone-suspicious-include) — stb_vorbis és single-file: la macro de dalt limita a només-declaracions.
#include "external/stb_vorbis.c"  // Para stb_vorbis_open_memory i streaming

// Deleter stateless per a buffers reservats amb `SDL_malloc` / `SDL_LoadWAV*`.
// Compatible amb `std::unique_ptr<Uint8[], SdlFreeDeleter>` — zero size
// overhead gràcies a EBO, igual que un unique_ptr amb default_delete.
struct SdlFreeDeleter {
    void operator()(Uint8* p) const noexcept {
        if (p != nullptr) { SDL_free(p); }
    }
};

namespace Ja {

    // --- Public Enums ---
    enum class ChannelState : std::uint8_t {
        INVALID,
        FREE,
        PLAYING,
        PAUSED,
        DISABLED,
    };

    enum class MusicState : std::uint8_t {
        INVALID,
        PLAYING,
        PAUSED,
        STOPPED,
        DISABLED,
    };

    // --- Constants ---
    inline constexpr int MAX_SIMULTANEOUS_CHANNELS = 20;
    inline constexpr int MAX_GROUPS = 2;
    inline constexpr SDL_AudioSpec DEFAULT_SPEC{.format = SDL_AUDIO_S16, .channels = 2, .freq = 48000};

    // --- Struct Definitions ---
    struct Sound {
        SDL_AudioSpec spec{DEFAULT_SPEC};
        Uint32 length{0};
        // Buffer descomprimit (PCM) propietat del sound. Reservat per SDL_LoadWAV
        // via SDL_malloc; el deleter `SdlFreeDeleter` allibera amb SDL_free.
        std::unique_ptr<Uint8[], SdlFreeDeleter> buffer;
    };

    // L'ordre (punters primer, ints després, enum de 8 bits al final) minimitza
    // el padding a 64-bit (evita avisos de clang-analyzer-optin.performance.Padding).
    struct Channel {
        Sound* sound{nullptr};
        SDL_AudioStream* stream{nullptr};
        int pos{0};
        int times{0};
        int group{0};
        ChannelState state{ChannelState::FREE};
    };

    struct Music {
        SDL_AudioSpec spec{DEFAULT_SPEC};

        // OGG comprimit en memòria. Propietat nostra; es copia des del buffer
        // d'entrada una sola vegada en loadMusic i es descomprimix en chunks
        // per streaming. Com que stb_vorbis guarda un punter persistent al
        // `.data()` d'aquest vector, no el podem resize'jar un cop establert
        // (una reallocation invalidaria el punter que el decoder conserva).
        std::vector<Uint8> ogg_data;
        stb_vorbis* vorbis{nullptr};  // handle del decoder, viu tot el cicle del Music

        std::string filename;

        int times{0};  // loops restants (-1 = infinit, 0 = un sol play)
        SDL_AudioStream* stream{nullptr};
        MusicState state{MusicState::INVALID};
    };

    struct FadeState {
        bool active{false};
        Uint64 start_time{0};
        int duration_ms{0};
        float initial_volume{0.0F};
    };

    struct OutgoingMusic {
        SDL_AudioStream* stream{nullptr};
        FadeState fade;
    };

    // --- Internal Global State (inline, C++17) ---
    inline Music* current_music{nullptr};
    inline Channel channels[MAX_SIMULTANEOUS_CHANNELS];

    inline SDL_AudioSpec audio_spec{DEFAULT_SPEC};
    inline float music_volume{1.0F};
    inline float sound_volume[MAX_GROUPS];
    inline bool music_enabled{true};
    inline bool sound_enabled{true};
    inline SDL_AudioDeviceID sdl_audio_device{0};

    inline OutgoingMusic outgoing_music;
    inline FadeState incoming_fade;

    // --- Forward Declarations ---
    inline void stopMusic();
    inline void stopChannel(int channel);
    inline auto playSoundOnChannel(Sound* sound, int channel, int loop = 0, int group = 0) -> int;
    inline void crossfadeMusic(Music* music, int crossfade_ms, int loop = -1);

    // --- Music streaming internals ---
    // Bytes-per-sample per canal (sempre s16)
    inline constexpr int MUSIC_BYTES_PER_SAMPLE = 2;
    // Quants shorts decodifiquem per crida a get_samples_short_interleaved.
    // 8192 shorts = 4096 samples/channel en estèreo ≈ 85ms de so a 48kHz.
    inline constexpr int MUSIC_CHUNK_SHORTS = 8192;
    // Umbral d'audio per davant del cursor de reproducció. Mantenim ≥ 0.5 s a
    // l'SDL_AudioStream per absorbir jitter de frame i evitar underruns.
    inline constexpr float MUSIC_LOW_WATER_SECONDS = 0.5F;

    // Decodifica un chunk del vorbis i el volca a l'stream. Retorna samples
    // decodificats per canal (0 = EOF de l'stream vorbis).
    inline auto feedMusicChunk(Music* music) -> int {
        if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return 0; }

        short chunk[MUSIC_CHUNK_SHORTS];
        const int NUM_CHANNELS = music->spec.channels;
        const int SAMPLES_PER_CHANNEL = stb_vorbis_get_samples_short_interleaved(
            music->vorbis,
            NUM_CHANNELS,
            chunk,
            MUSIC_CHUNK_SHORTS);
        if (SAMPLES_PER_CHANNEL <= 0) { return 0; }

        const int BYTES = SAMPLES_PER_CHANNEL * NUM_CHANNELS * MUSIC_BYTES_PER_SAMPLE;
        SDL_PutAudioStreamData(music->stream, chunk, BYTES);
        return SAMPLES_PER_CHANNEL;
    }

    // Reompli l'stream fins que tinga ≥ MUSIC_LOW_WATER_SECONDS bufferats.
    // En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
    inline void pumpMusic(Music* music) {
        if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return; }

        const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
        const int LOW_WATER_BYTES = static_cast<int>(MUSIC_LOW_WATER_SECONDS * static_cast<float>(BYTES_PER_SECOND));

        while (SDL_GetAudioStreamAvailable(music->stream) < LOW_WATER_BYTES) {
            const int DECODED = feedMusicChunk(music);
            if (DECODED > 0) { continue; }

            // EOF: si queden loops, rebobinar; si no, tallar i deixar drenar.
            if (music->times != 0) {
                stb_vorbis_seek_start(music->vorbis);
                if (music->times > 0) { music->times--; }
            } else {
                break;
            }
        }
    }

    // Pre-carrega `duration_ms` de so dins l'stream actual abans que l'stream
    // siga robat per outgoing_music (crossfade o fade-out). Imprescindible amb
    // streaming: l'stream robat no es pot re-alimentar perquè perd la referència
    // al seu vorbis decoder. No aplica loop — si el vorbis s'esgota abans, parem.
    inline void preFillOutgoing(Music* music, int duration_ms) {
        if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return; }

        const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
        const int NEEDED_BYTES = static_cast<int>((static_cast<std::int64_t>(duration_ms) * BYTES_PER_SECOND) / 1000);

        while (SDL_GetAudioStreamAvailable(music->stream) < NEEDED_BYTES) {
            const int DECODED = feedMusicChunk(music);
            if (DECODED <= 0) { break; }  // EOF: deixem drenar el que hi haja
        }
    }

    // --- update() helpers ---
    inline void updateOutgoingFade() {
        if ((outgoing_music.stream == nullptr) || !outgoing_music.fade.active) { return; }

        const Uint64 NOW = SDL_GetTicks();
        const Uint64 ELAPSED = NOW - outgoing_music.fade.start_time;
        if (ELAPSED >= static_cast<Uint64>(outgoing_music.fade.duration_ms)) {
            SDL_DestroyAudioStream(outgoing_music.stream);
            outgoing_music.stream = nullptr;
            outgoing_music.fade.active = false;
        } else {
            const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(outgoing_music.fade.duration_ms);
            SDL_SetAudioStreamGain(outgoing_music.stream, outgoing_music.fade.initial_volume * (1.0F - PERCENT));
        }
    }

    inline void updateIncomingFade() {
        if (!incoming_fade.active) { return; }

        const Uint64 NOW = SDL_GetTicks();
        const Uint64 ELAPSED = NOW - incoming_fade.start_time;
        if (ELAPSED >= static_cast<Uint64>(incoming_fade.duration_ms)) {
            incoming_fade.active = false;
            SDL_SetAudioStreamGain(current_music->stream, music_volume);
        } else {
            const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(incoming_fade.duration_ms);
            SDL_SetAudioStreamGain(current_music->stream, music_volume * PERCENT);
        }
    }

    inline void updateCurrentMusic() {
        if (!music_enabled || (current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }

        updateIncomingFade();

        // Streaming: rellenem l'stream fins al low-water-mark i parem si el
        // vorbis s'ha esgotat i no queden loops.
        pumpMusic(current_music);
        if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
            stopMusic();
        }
    }

    inline void updateSoundChannels() {
        if (!sound_enabled) { return; }

        for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; ++i) {
            auto& ch = channels[i];
            if (ch.state != ChannelState::PLAYING) { continue; }

            if (ch.times != 0) {
                if (static_cast<Uint32>(SDL_GetAudioStreamAvailable(ch.stream)) < (ch.sound->length / 2)) {
                    SDL_PutAudioStreamData(ch.stream, ch.sound->buffer.get(), ch.sound->length);
                    if (ch.times > 0) { ch.times--; }
                }
            } else {
                if (SDL_GetAudioStreamAvailable(ch.stream) == 0) { stopChannel(i); }
            }
        }
    }

    inline void update() {
        updateOutgoingFade();
        updateCurrentMusic();
        updateSoundChannels();
    }

    inline void init(int freq, SDL_AudioFormat format, int num_channels) {
        audio_spec = {.format = format, .channels = num_channels, .freq = freq};
        if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
        sdl_audio_device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_spec);
        if (sdl_audio_device == 0) { std::cout << "Failed to initialize SDL audio!" << '\n'; }
        for (auto& ch : channels) { ch.state = ChannelState::FREE; }
        std::ranges::fill(sound_volume, 0.5F);
    }

    inline void quit() {
        if (outgoing_music.stream != nullptr) {
            SDL_DestroyAudioStream(outgoing_music.stream);
            outgoing_music.stream = nullptr;
        }
        if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
        sdl_audio_device = 0;
    }

    // --- Music Functions ---
    inline auto loadMusic(const Uint8* buffer, Uint32 length) -> Music* {
        if ((buffer == nullptr) || length == 0) { return nullptr; }

        // Allocem el Music primer per aprofitar el seu `std::vector<Uint8>`
        // com a propietari del OGG comprimit. stb_vorbis guarda un punter
        // persistent al buffer; com que ací no el resize'jem, el .data() és
        // estable durant tot el cicle de vida del music.
        auto* music = new Music();
        music->ogg_data.assign(buffer, buffer + length);

        int vorbis_error = 0;
        music->vorbis = stb_vorbis_open_memory(music->ogg_data.data(),
            static_cast<int>(length),
            &vorbis_error,
            nullptr);
        if (music->vorbis == nullptr) {
            std::cout << "loadMusic: stb_vorbis_open_memory failed (error " << vorbis_error << ")" << '\n';
            delete music;
            return nullptr;
        }

        const stb_vorbis_info INFO = stb_vorbis_get_info(music->vorbis);
        music->spec.channels = INFO.channels;
        music->spec.freq = static_cast<int>(INFO.sample_rate);
        music->spec.format = SDL_AUDIO_S16;
        music->state = MusicState::STOPPED;

        return music;
    }

    // Overload amb filename — els callers l'usen per poder comparar la música
    // en curs amb getMusicFilename() i no rearrancar-la si ja és la mateixa.
    inline auto loadMusic(Uint8* buffer, Uint32 length, const char* filename) -> Music* {
        Music* music = loadMusic(static_cast<const Uint8*>(buffer), length);
        if ((music != nullptr) && (filename != nullptr)) { music->filename = filename; }
        return music;
    }

    inline auto loadMusic(const char* filename) -> Music* {
        // Carreguem primer el arxiu en memòria i després el descomprimim.
        FILE* f = std::fopen(filename, "rb");
        if (f == nullptr) { return nullptr; }
        std::fseek(f, 0, SEEK_END);
        const long FSIZE = std::ftell(f);
        std::fseek(f, 0, SEEK_SET);
        if (FSIZE <= 0) {
            std::fclose(f);
            return nullptr;
        }
        auto* buffer = static_cast<Uint8*>(std::malloc(static_cast<size_t>(FSIZE) + 1));
        if (buffer == nullptr) {
            std::fclose(f);
            return nullptr;
        }
        if (std::fread(buffer, FSIZE, 1, f) != 1) {
            std::fclose(f);
            std::free(buffer);
            return nullptr;
        }
        std::fclose(f);

        Music* music = loadMusic(static_cast<const Uint8*>(buffer), static_cast<Uint32>(FSIZE));
        if (music != nullptr) { music->filename = filename; }

        std::free(buffer);

        return music;
    }

    inline void playMusic(Music* music, int loop = -1) {
        if (!music_enabled || (music == nullptr) || (music->vorbis == nullptr)) { return; }

        stopMusic();

        current_music = music;
        current_music->state = MusicState::PLAYING;
        current_music->times = loop;

        // Rebobinem l'stream de vorbis al principi. Cobreix tant play-per-primera-
        // vegada com replays/canvis de track que tornen a la mateixa pista.
        stb_vorbis_seek_start(current_music->vorbis);

        current_music->stream = SDL_CreateAudioStream(&current_music->spec, &audio_spec);
        if (current_music->stream == nullptr) {
            std::cout << "Failed to create audio stream!" << '\n';
            current_music->state = MusicState::STOPPED;
            return;
        }
        SDL_SetAudioStreamGain(current_music->stream, music_volume);

        // Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
        pumpMusic(current_music);

        if (!SDL_BindAudioStream(sdl_audio_device, current_music->stream)) {
            std::cout << "[ERROR] SDL_BindAudioStream failed!" << '\n';
        }
    }

    inline auto getMusicFilename(const Music* music = nullptr) -> const char* {
        if (music == nullptr) { music = current_music; }
        if ((music == nullptr) || music->filename.empty()) { return nullptr; }
        return music->filename.c_str();
    }

    inline void pauseMusic() {
        if (!music_enabled) { return; }
        if ((current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }

        current_music->state = MusicState::PAUSED;
        SDL_UnbindAudioStream(current_music->stream);
    }

    inline void resumeMusic() {
        if (!music_enabled) { return; }
        if ((current_music == nullptr) || current_music->state != MusicState::PAUSED) { return; }

        current_music->state = MusicState::PLAYING;
        SDL_BindAudioStream(sdl_audio_device, current_music->stream);
    }

    inline void stopMusic() {
        // Limpiar outgoing crossfade si existe
        if (outgoing_music.stream != nullptr) {
            SDL_DestroyAudioStream(outgoing_music.stream);
            outgoing_music.stream = nullptr;
            outgoing_music.fade.active = false;
        }
        incoming_fade.active = false;

        if ((current_music == nullptr) || current_music->state == MusicState::INVALID || current_music->state == MusicState::STOPPED) { return; }

        current_music->state = MusicState::STOPPED;
        if (current_music->stream != nullptr) {
            SDL_DestroyAudioStream(current_music->stream);
            current_music->stream = nullptr;
        }
        // Deixem el handle de vorbis viu — es tanca en deleteMusic.
        // Rebobinem perquè un futur playMusic comence des del principi.
        if (current_music->vorbis != nullptr) {
            stb_vorbis_seek_start(current_music->vorbis);
        }
    }

    inline void fadeOutMusic(int milliseconds) {
        if (!music_enabled) { return; }
        if ((current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }

        // Destruir outgoing anterior si existe
        if (outgoing_music.stream != nullptr) {
            SDL_DestroyAudioStream(outgoing_music.stream);
            outgoing_music.stream = nullptr;
        }

        // Pre-omplim l'stream amb `milliseconds` de so: un cop robat, ja no
        // tindrà accés al vorbis decoder i només podrà drenar el que tinga.
        preFillOutgoing(current_music, milliseconds);

        // Robar el stream del current_music al outgoing
        outgoing_music.stream = current_music->stream;
        outgoing_music.fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = milliseconds, .initial_volume = music_volume};

        // Dejar current_music sin stream (ya lo tiene outgoing)
        current_music->stream = nullptr;
        current_music->state = MusicState::STOPPED;
        if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
        incoming_fade.active = false;
    }

    inline void crossfadeMusic(Music* music, int crossfade_ms, int loop) {
        if (!music_enabled || (music == nullptr) || (music->vorbis == nullptr)) { return; }

        // Destruir outgoing anterior si existe (crossfade durante crossfade)
        if (outgoing_music.stream != nullptr) {
            SDL_DestroyAudioStream(outgoing_music.stream);
            outgoing_music.stream = nullptr;
            outgoing_music.fade.active = false;
        }

        // Robar el stream de la musica actual al outgoing para el fade-out.
        // Pre-omplim amb `crossfade_ms` de so perquè no es quede en silenci
        // abans d'acabar el fade (l'stream robat ja no pot alimentar-se).
        if ((current_music != nullptr) && current_music->state == MusicState::PLAYING && (current_music->stream != nullptr)) {
            preFillOutgoing(current_music, crossfade_ms);
            outgoing_music.stream = current_music->stream;
            outgoing_music.fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = crossfade_ms, .initial_volume = music_volume};
            current_music->stream = nullptr;
            current_music->state = MusicState::STOPPED;
            if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
        }

        // Iniciar la nueva pista con gain=0 (el fade-in la sube gradualmente)
        current_music = music;
        current_music->state = MusicState::PLAYING;
        current_music->times = loop;

        stb_vorbis_seek_start(current_music->vorbis);
        current_music->stream = SDL_CreateAudioStream(&current_music->spec, &audio_spec);
        if (current_music->stream == nullptr) {
            std::cout << "Failed to create audio stream for crossfade!" << '\n';
            current_music->state = MusicState::STOPPED;
            return;
        }
        SDL_SetAudioStreamGain(current_music->stream, 0.0F);
        pumpMusic(current_music);  // pre-carrega abans de bindejar
        SDL_BindAudioStream(sdl_audio_device, current_music->stream);

        // Configurar fade-in
        incoming_fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = crossfade_ms, .initial_volume = 0.0F};
    }

    inline auto getMusicState() -> MusicState {
        if (!music_enabled) { return MusicState::DISABLED; }
        if (current_music == nullptr) { return MusicState::INVALID; }

        return current_music->state;
    }

    inline void deleteMusic(Music* music) {
        if (music == nullptr) { return; }
        if (current_music == music) {
            stopMusic();
            current_music = nullptr;
        }
        if (music->stream != nullptr) { SDL_DestroyAudioStream(music->stream); }
        if (music->vorbis != nullptr) { stb_vorbis_close(music->vorbis); }
        // ogg_data (std::vector) i filename (std::string) s'alliberen sols
        // al destructor de Music.
        delete music;
    }

    inline auto setMusicVolume(float volume) -> float {
        music_volume = SDL_clamp(volume, 0.0F, 1.0F);
        if ((current_music != nullptr) && (current_music->stream != nullptr)) {
            SDL_SetAudioStreamGain(current_music->stream, music_volume);
        }
        return music_volume;
    }

    inline void setMusicPosition(float /*value*/) {
        // No implementat amb el backend de streaming.
    }

    inline auto getMusicPosition() -> float {
        return 0.0F;
    }

    inline void enableMusic(bool value) {
        if (!value && (current_music != nullptr) && (current_music->state == MusicState::PLAYING)) { stopMusic(); }
        music_enabled = value;
    }

    // --- Sound Functions ---
    inline auto loadSound(std::uint8_t* buffer, std::uint32_t size) -> Sound* {
        auto sound = std::make_unique<Sound>();
        Uint8* raw = nullptr;
        if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), true, &sound->spec, &raw, &sound->length)) {
            std::cout << "Failed to load WAV from memory: " << SDL_GetError() << '\n';
            return nullptr;
        }
        sound->buffer.reset(raw);  // adopta el SDL_malloc'd buffer
        return sound.release();
    }

    inline auto loadSound(const char* filename) -> Sound* {
        auto sound = std::make_unique<Sound>();
        Uint8* raw = nullptr;
        if (!SDL_LoadWAV(filename, &sound->spec, &raw, &sound->length)) {
            std::cout << "Failed to load WAV file: " << SDL_GetError() << '\n';
            return nullptr;
        }
        sound->buffer.reset(raw);  // adopta el SDL_malloc'd buffer
        return sound.release();
    }

    inline auto playSound(Sound* sound, int loop = 0, int group = 0) -> int {
        if (!sound_enabled || (sound == nullptr)) { return -1; }

        int channel = 0;
        while (channel < MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != ChannelState::FREE) { channel++; }
        if (channel == MAX_SIMULTANEOUS_CHANNELS) {
            // No hi ha canal lliure, reemplacem el primer
            channel = 0;
        }

        return playSoundOnChannel(sound, channel, loop, group);
    }

    inline auto playSoundOnChannel(Sound* sound, int channel, int loop, int group) -> int {
        if (!sound_enabled || (sound == nullptr)) { return -1; }
        if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return -1; }

        stopChannel(channel);

        channels[channel].sound = sound;
        channels[channel].times = loop;
        channels[channel].pos = 0;
        channels[channel].group = group;
        channels[channel].state = ChannelState::PLAYING;
        channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &audio_spec);

        if (channels[channel].stream == nullptr) {
            std::cout << "Failed to create audio stream for sound!" << '\n';
            channels[channel].state = ChannelState::FREE;
            return -1;
        }

        SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer.get(), channels[channel].sound->length);
        SDL_SetAudioStreamGain(channels[channel].stream, sound_volume[group]);
        SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);

        return channel;
    }

    inline void deleteSound(Sound* sound) {
        if (sound == nullptr) { return; }
        for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; i++) {
            if (channels[i].sound == sound) { stopChannel(i); }
        }
        // buffer es destrueix automàticament via RAII (SdlFreeDeleter).
        delete sound;
    }

    inline void pauseChannel(int channel) {
        if (!sound_enabled) { return; }

        if (channel == -1) {
            for (auto& ch : channels) {
                if (ch.state == ChannelState::PLAYING) {
                    ch.state = ChannelState::PAUSED;
                    SDL_UnbindAudioStream(ch.stream);
                }
            }
        } else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
            if (channels[channel].state == ChannelState::PLAYING) {
                channels[channel].state = ChannelState::PAUSED;
                SDL_UnbindAudioStream(channels[channel].stream);
            }
        }
    }

    inline void resumeChannel(int channel) {
        if (!sound_enabled) { return; }

        if (channel == -1) {
            for (auto& ch : channels) {
                if (ch.state == ChannelState::PAUSED) {
                    ch.state = ChannelState::PLAYING;
                    SDL_BindAudioStream(sdl_audio_device, ch.stream);
                }
            }
        } else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
            if (channels[channel].state == ChannelState::PAUSED) {
                channels[channel].state = ChannelState::PLAYING;
                SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);
            }
        }
    }

    inline void stopChannel(int channel) {
        if (channel == -1) {
            for (auto& ch : channels) {
                if (ch.state != ChannelState::FREE) {
                    if (ch.stream != nullptr) { SDL_DestroyAudioStream(ch.stream); }
                    ch.stream = nullptr;
                    ch.state = ChannelState::FREE;
                    ch.pos = 0;
                    ch.sound = nullptr;
                }
            }
        } else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
            if (channels[channel].state != ChannelState::FREE) {
                if (channels[channel].stream != nullptr) { SDL_DestroyAudioStream(channels[channel].stream); }
                channels[channel].stream = nullptr;
                channels[channel].state = ChannelState::FREE;
                channels[channel].pos = 0;
                channels[channel].sound = nullptr;
            }
        }
    }

    inline auto getChannelState(int channel) -> ChannelState {
        if (!sound_enabled) { return ChannelState::DISABLED; }
        if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return ChannelState::INVALID; }

        return channels[channel].state;
    }

    inline auto setSoundVolume(float volume, int group = -1) -> float {
        const float V = SDL_clamp(volume, 0.0F, 1.0F);

        if (group == -1) {
            std::ranges::fill(sound_volume, V);
        } else if (group >= 0 && group < MAX_GROUPS) {
            sound_volume[group] = V;
        } else {
            return V;
        }

        // Aplicar volum als canals actius.
        for (auto& ch : channels) {
            if ((ch.state == ChannelState::PLAYING) || (ch.state == ChannelState::PAUSED)) {
                if (group == -1 || ch.group == group) {
                    if (ch.stream != nullptr) {
                        SDL_SetAudioStreamGain(ch.stream, sound_volume[ch.group]);
                    }
                }
            }
        }
        return V;
    }

    inline void enableSound(bool value) {
        if (!value) {
            stopChannel(-1);
        }
        sound_enabled = value;
    }

    inline auto setVolume(float volume) -> float {
        const float V = setMusicVolume(volume);
        setSoundVolume(V, -1);
        return V;
    }

}  // namespace Ja
