#pragma once

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

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

class crDevText;
class crFontAtlas;

class crBatchedTexts
{
public:
    // interleaved per-instance stream — must match quad_instanced.vert locations 2..6 (shared with sprites)
    struct GlyphInstance
    {
        float2 pos;      // screen pixels (pivot point)
        float2 size;     // screen pixels
        float2 cosSin;   // always (1, 0) for text
        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<GlyphInstance> _instances;
    crArray<uint8_t>       _pages;      // parallel to _instances; atlas page per glyph (for per-page texture binding)

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

public:
    void Init();
    void Cleanup();

    void Begin();
    void Add( const GlyphInstance& instance, uint8_t page );
    // lay out a UTF-8 string (multi-line, pivot) at a pixel-ortho anchor (bottom-left, Y-up) and queue
    // its glyphs. devText != nullptr adds the dev overlay boxes (world-anchored path); UI passes nullptr
    void AddString( crFontAtlas* atlas, const char* utf8, float2 anchorPx, int32_t font, color4 color, float scale, float2 pivot, crDevText* devText );
    void Flush( GLuint program, float4x4 proj, const crFontAtlas* atlas );
};
