// spawn_controller.hpp - Controlador de spawn de enemigos
// © 2026 JailDesigner

#pragma once

#include <array>
#include <cstdint>
#include <vector>

#include "core/types.hpp"
#include "game/entities/enemy.hpp"
#include "stage_config.hpp"

namespace StageSystem {

// Informació de spawn planificat
struct SpawnEvent {
        float temps_spawn;  // Temps absolut (segons) per spawnejar
        EnemyType type;  // Tipo de enemy
        bool spawnejat;     // Ya s'ha processat?
};

class SpawnController {
    public:
        SpawnController();

        // Configuration
        void configure(const StageConfig* config);  // Set stage config
        void start();                              // Generate spawn schedule
        void reset();                                // Clear all pending spawns

        // Update
        void update(float delta_time, std::array<Enemy, 15>& orni_array, bool pausar = false);

        // Status queries
        [[nodiscard]] auto allEnemiesSpawned() const -> bool;
        [[nodiscard]] auto allEnemiesDestroyed(const std::array<Enemy, 15>& orni_array) const -> bool;
        // Estático: solo recorre el array pasado; no consulta estado del controller.
        [[nodiscard]] static auto getAliveEnemyCount(const std::array<Enemy, 15>& orni_array) -> uint8_t;
        [[nodiscard]] auto countSpawnedEnemies() const -> uint8_t;

        // [NEW] Set ship position reference for safe spawn
        void setShipPosition(const Vec2* ship_pos) { ship_position_ = ship_pos; }

    private:
        const StageConfig* config_{nullptr};  // Non-owning pointer to current stage config
        std::vector<SpawnEvent> spawn_queue_;
        float temps_transcorregut_{0.0F};   // Elapsed time since stage start
        uint8_t index_spawn_actual_{0};  // Next spawn to process

        // Spawn generation
        void generateSpawnEvents();
        [[nodiscard]] auto selectRandomType() const -> EnemyType;
        void spawnEnemy(Enemy& enemy, EnemyType type, const Vec2* ship_pos = nullptr);
        void applyMultipliers(Enemy& enemy) const;
        const Vec2* ship_position_{nullptr};  // [NEW] Non-owning pointer to ship position
};

}  // namespace StageSystem
