class PlayerManager {
  constructor() {
    this.onlinePlayers = [];
    this.offlinePlayers = [];
    this.listeners = new Set();
  }

  setInitialState(online, offline) {
    this.onlinePlayers = online || [];
    this.offlinePlayers = offline || [];

    this.notify();
  }

  handlePlayerJoined(username) {
    if (!this.onlinePlayers.includes(username)) {
      this.onlinePlayers.push(username);
      this.offlinePlayers = this.offlinePlayers.filter((u) => u !== username);
      this.notify();
    }
  }

  handlePlayerLeft(username) {
    this.onlinePlayers = this.onlinePlayers.filter((u) => u !== username);
    if (!this.offlinePlayers.includes(username)) {
      this.offlinePlayers.push(username);
    }
    this.notify();
  }

  subscribe(listener) {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  notify() {
    this.listeners.forEach((listener) =>
      listener({
        online: this.onlinePlayers,
        offline: this.offlinePlayers,
      }),
    );
  }
}

export default new PlayerManager();
