// spawn_controller.hpp - Controlador de spawn de enemigos
// © 2025 Orni Attack

#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]] bool tots_enemics_spawnejats() const;
        [[nodiscard]] bool tots_enemics_destruits(const std::array<Enemy, 15>& orni_array) const;
        [[nodiscard]] uint8_t get_enemics_vius(const std::array<Enemy, 15>& orni_array) const;
        [[nodiscard]] uint8_t get_enemics_spawnejats() const;

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

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

        // Spawn generation
        void generar_spawn_events();
        [[nodiscard]] EnemyType seleccionar_tipus_aleatori() const;
        void spawn_enemic(Enemy& enemy, EnemyType type, const Vec2* ship_pos = nullptr);
        void aplicar_multiplicadors(Enemy& enemy) const;
        const Vec2* ship_position_;  // [NEW] Non-owning pointer to ship position
};

}  // namespace StageSystem
