#pragma once
#include "raylib.h"
#include <string>

// UI 状态上下文
class UIContext
{
public:
	void NewFrame();
	bool ConsumeMousePress();
	bool IsMousePressConsumed() const;
	bool ConsumeMouseRelease();
	bool IsMouseReleaseConsumed() const;
	void CapturePressOn(RLRectangle rect);
	bool IsPressCapturedOn(RLRectangle rect) const;

private:
	bool m_mousePressConsumed = false;
	bool m_mouseReleaseConsumed = false;
	RLRectangle m_pressCapturedRect = { 0 };
	bool m_pressCaptured = false;
};

struct WidgetState
{
	bool hover;
	bool pressed;
	bool clicked;
	bool released;
};

struct TextboxState {
    std::string text;
    bool active = false;
    int cursor = 0;
    int selectStart = 0;
    int selectEnd = 0;
    bool selecting = false;
    double lastInputTime = -1.0;
    bool password = false;
};

// 控件管理器
class WidgetManager
{
public:
	static WidgetManager* Get();

	void NewFrame();
	UIContext& Ctx() { return m_ctx; }

	// Per-widget pre-processing: registers drag block, computes hover/pressed/clicked
	WidgetState BeginWidget(RLRectangle rect);

	// IME composition window positioning (Windows)
	static void UpdateImePosition(int x, int y);

	// Controls
	bool Button(const char* label, RLRectangle rect, bool disabled);
	bool Toggle(const char* label, RLRectangle rect, bool* state);
	bool Textbox(const char* id, RLRectangle rect, TextboxState* state);
	void Label(const char* label, RLVector2 Vec, int FontSize, int spacing);

private:
	WidgetManager() = default;
	~WidgetManager() = default;

	UIContext m_ctx;
};

// 控件接口
class Framework
{
public:
	static Framework* Get();

	void NewFrame();
	bool Button(const char* label, RLRectangle Rect, bool disabled = false);
	bool Toggle(const char* label, RLRectangle Rect, bool* state);
	bool Textbox(const char* id, RLRectangle rect, TextboxState* state);
	void Label(const char* label, RLVector2 Vec, int FontSize, int spacing = 0);

	UIContext& Ctx() { return WidgetManager::Get()->Ctx(); }

private:
	Framework() = default;
	~Framework() = default;
};

typedef struct {
    RLColor color;
    float offset;
} GradientStop;

// 渲染接口
class Render
{
public:
	static Render* Get();
	void Gradient(RLRectangle Rect, RLColor LColor, RLColor ROtherColor, bool Vertical, bool Antialias = false);
	void CustomGradientBar(int x, int y, int width, int height, GradientStop* stops, int stopCount);

private:
	Render() = default;
	~Render() = default;
};

inline int ClampInt(int val, int min, int max) {
    if (val < min) return min;
    if (val > max) return max;
    return val;
}

inline float ClampF(float v, float a, float b) {
    return v < a ? a : (v > b ? b : v);
}