#pragma once

#include <frostbite2D/audio/music.h>
#include <frostbite2D/audio/sound.h>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>

namespace frostbite2D {

struct MapAudioTrack {
  std::string id;
  std::string path;
};

struct MapAudioState {
  std::optional<MapAudioTrack> bgmTrack;
  std::vector<MapAudioTrack> ambientLoops;
};

class MapAudioController {
public:
  static MapAudioController& get();

  void ApplyMapAudio(const MapAudioState& state);
  void ClearMapAudio();

private:
  struct ActiveAmbientLoop {
    MapAudioTrack track;
    RefPtr<Sound> sound;
    int channel = -1;
  };

  MapAudioController() = default;

  void ApplyBgmTrack(const std::optional<MapAudioTrack>& bgmTrack);
  void ApplyAmbientLoops(const std::vector<MapAudioTrack>& ambientLoops);
  void StopAmbientLoop(ActiveAmbientLoop& loop);
  static std::string NormalizeTrackKey(const MapAudioTrack& track);

  std::optional<MapAudioTrack> currentBgmTrack_;
  RefPtr<Music> currentBgmMusic_;
  std::unordered_map<std::string, ActiveAmbientLoop> activeAmbientLoops_;
};

} // namespace frostbite2D
