#pragma once

#include "GTile.h"
#include "warfactory/ASerializable.h"

namespace warfactory {

class GMap : public ASerializable {
private:
    int width, height;
    GTile* tiles; // Contiguous memory block: tiles[y * width + x]

public:
    GMap(int w, int h);
    ~GMap();

    // Prevent copy (expensive with large maps)
    GMap(const GMap&) = delete;
    GMap& operator=(const GMap&) = delete;

    // Move constructor/assignment for efficiency
    GMap(GMap&& other) noexcept;
    GMap& operator=(GMap&& other) noexcept;

    // ========================================
    // MAP ACCESS
    // ========================================

    GTile* getTile(int x, int y);
    const GTile* getTile(int x, int y) const;

    bool isValidCoordinate(int x, int y) const {
        return x >= 0 && x < width && y >= 0 && y < height;
    }

    int getWidth() const { return width; }
    int getHeight() const { return height; }

    // ========================================
    // BULK OPERATIONS (Phase 1 specific)
    // ========================================

    /**
     * @brief Apply cooling to all tiles
     */
    void coolAllTiles(float cooling_rate_celsius);

    /**
     * @brief Apply impact effects to circular area
     */
    void applyImpactToArea(float center_x, float center_y, float radius_meters,
                          float heat_celsius, uint16_t crater_depth, uint8_t crater_scale);

    /**
     * @brief Apply volcanic heat to specific location
     */
    void applyVolcanicHeat(float x, float y, float heat_celsius, float radius_meters);

    /**
     * @brief Get average temperature across map
     */
    float getAverageTemperature() const;

    /**
     * @brief Get average elevation across map
     */
    float getAverageElevation() const;

    // ========================================
    // ITERATION SUPPORT (cache-friendly)
    // ========================================

    GTile* begin() { return tiles; }
    GTile* end() { return tiles + (width * height); }
    const GTile* begin() const { return tiles; }
    const GTile* end() const { return tiles + (width * height); }

    // ========================================
    // SERIALIZATION
    // ========================================

    json serialize() const override;
    void deserialize(const json& data) override;

private:
    void allocateTiles();
    void deallocateTiles();
};

} // namespace warfactory