#pragma once

#if defined( __EMSCRIPTEN__ ) || defined( __ANDROID__ )
#include <GLES3/gl3.h>
#else
#include <glad/glad.h>
#endif

#include "crArray.h"
#include "crStruct.h"

class crGraphics;

class crBatchedSprites
{
public:
    // interleaved per-instance stream — must match quad_instanced.vert locations 2..6
    struct SpriteInstance
    {
        float2 pos;      // world (pivot point)
        float2 size;     // world meters
        float2 cosSin;
        color4 color;
        float2 uvMin;
        float2 uvMax;
        float2 pivot;    // image-space 0..1
    };   // 64B = one cache line per instance

private:
    static constexpr int32_t INITIAL_RESERVE = 1000;

    crArray<SpriteInstance> _instances;
    crArray<uint8_t>        _atlases;      // per-instance atlas id — draw routing only, never uploaded

    const char* _name     = "";
    int32_t     _runsPrev = 0;

    GLuint _vao         = 0;
    GLuint _quadVbo     = 0;
    GLuint _instanceVbo = 0;

public:
    void Init( const char* name );
    void Cleanup();

    void Begin();
    void Add( const SpriteInstance& instance, int32_t atlasId );
    void Flush( GLuint program, float4x4 proj, const crGraphics* graphics );   // one draw per consecutive-atlas run, submission order preserved

    int32_t RunsLastFlush() const { return _runsPrev; }   // 1 = fully batched
};
