/**
 * Galaxy Strike Online - Fleet System
 * Manages player fleets, ship roster, and galaxy movement
 */
class FleetSystem {
  constructor(contentLoader) {
    this.contentLoader = contentLoader;
  }

  /** Return all ship templates from ContentLoader */
  getAllShipTemplates() {
    const items = this.contentLoader.getAllItems ? this.contentLoader.getAllItems() : [];
    return items.filter(i => i.type === 'ship');
  }

  /** Build fleet summary from playerData */
  getFleetData(playerData) {
    const ships = playerData.inventory?.filter(i => i.type === 'ship') || [];
    const activeShipId = playerData.stats?.activeShipId || null;
    return {
      ships,
      activeShipId: activeShipId || (ships[0]?.id ?? null),
      maxFleetSize: 5 + Math.floor((playerData.stats?.level || 1) / 10),
    };
  }

  /** Set active ship — returns updated stats block */
  setActiveShip(playerData, shipId) {
    const ship = (playerData.inventory || []).find(i => i.id === shipId && i.type === 'ship');
    if (!ship) throw new Error('Ship not found in inventory');
    playerData.stats = playerData.stats || {};
    playerData.stats.activeShipId = shipId;
    // Apply ship stats to player combat stats
    playerData.stats.attack  = (playerData.stats.baseAttack  || 10) + (ship.stats?.attack  || 0);
    playerData.stats.defense = (playerData.stats.baseDefense || 5)  + (ship.stats?.defense || 0);
    playerData.stats.speed   = (playerData.stats.baseSpeed   || 10) + (ship.stats?.speed   || 0);
    return playerData.stats;
  }

  /** Repair a ship (full restore of hull) */
  repairShip(playerData, shipId, creditsAvailable) {
    const ship = (playerData.inventory || []).find(i => i.id === shipId && i.type === 'ship');
    if (!ship) throw new Error('Ship not found');
    const missingHull = (ship.stats?.maxHull || ship.stats?.hull || 100) - (ship.stats?.currentHull || ship.stats?.hull || 100);
    const repairCost = Math.ceil(missingHull * 2);
    if (creditsAvailable < repairCost) throw new Error(`Need ${repairCost} credits to repair`);
    ship.stats = ship.stats || {};
    ship.stats.currentHull = ship.stats.maxHull || ship.stats.hull || 100;
    return { repairCost, ship };
  }
}

module.exports = FleetSystem;
