/**
 * @typedef {import("../units/types.js").ExplorerData} ExplorerData
 * @typedef {import("../units/types.js").RosterSaveData} RosterSaveData
 */

/**
 * RosterManager.js
 * Manages the persistent pool of Explorer units (The Barracks).
 * Handles recruitment, death, and selection for missions.
 * @class
 */

export class RosterManager {
  constructor() {
    /** @type {ExplorerData[]} */
    this.roster = []; // List of active Explorer objects (Data only)
    /** @type {ExplorerData[]} */
    this.graveyard = []; // List of dead units
    /** @type {number} */
    this.rosterLimit = 12;
  }

  /**
   * Initializes the roster from saved data.
   * @param {RosterSaveData} saveData - Saved roster data
   */
  load(saveData) {
    this.roster = saveData.roster || [];
    this.graveyard = saveData.graveyard || [];
  }

  /**
   * Serializes for save file.
   * @returns {RosterSaveData} - Serialized roster data
   */
  save() {
    return {
      roster: this.roster,
      graveyard: this.graveyard,
    };
  }

  /**
   * Adds a new unit to the roster.
   * @param {Partial<ExplorerData>} unitData - The unit definition (Class, Name, Stats)
   * @returns {Promise<ExplorerData | false>} - The recruited unit or false if roster is full
   */
  async recruitUnit(unitData) {
    if (this.roster.length >= this.rosterLimit) {
      console.warn("Roster full. Cannot recruit.");
      return false;
    }

    // Lazy import name generator only when needed
    const { generateCharacterName } = await import("../utils/nameGenerator.js");

    // Generate a character name and set className from the existing name property
    const characterName = generateCharacterName();
    const className = unitData.name || unitData.className; // Use name as className if provided

    const newUnit = {
      id: `UNIT_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
      ...unitData,
      name: characterName, // Generated character name
      className: className, // Class name (e.g., "Vanguard", "Weaver")
      status: "READY", // READY, INJURED, DEPLOYED
      history: { missions: 0, kills: 0 },
    };

    this.roster.push(newUnit);
    return newUnit;
  }

  /**
   * Marks a unit as dead and moves them to the graveyard.
   * @param {string} unitId - Unit ID to mark as dead
   */
  handleUnitDeath(unitId) {
    const index = this.roster.findIndex((u) => u.id === unitId);
    if (index > -1) {
      const unit = this.roster[index];
      unit.status = "DEAD";
      this.graveyard.push(unit);
      this.roster.splice(index, 1);
    }
  }

  /**
   * Returns units eligible for a mission.
   * Filters out injured or dead units.
   * @returns {ExplorerData[]} - Array of deployable units
   */
  getDeployableUnits() {
    return this.roster.filter((u) => u.status === "READY");
  }

  /**
   * Clears the roster and graveyard. Used when starting a new game.
   */
  clear() {
    this.roster = [];
    this.graveyard = [];
  }
}
