#pragma once

#include <extra2d/platform/iwindow.h>
#include <GLFW/glfw3.h>

namespace extra2d {

class GLFWInput;

/**
 * @brief GLFW 窗口实现
 */
class GLFWWindow : public IWindow {
public:
    GLFWWindow();
    ~GLFWWindow() override;

    bool create(const std::string& title, int width, int height, bool vsync = true) override;
    void destroy() override;

    void poll() override;
    void swap() override;
    bool shouldClose() const override;
    void close() override;

    void setTitle(const std::string& title) override;
    void setSize(int w, int h) override;
    void setPos(int x, int y) override;
    void setFullscreen(bool fs) override;
    void setVSync(bool vsync) override;
    void setVisible(bool visible) override;

    int width() const override;
    int height() const override;
    Size size() const override;
    Vec2 pos() const override;
    bool fullscreen() const override;
    bool vsync() const override;
    bool focused() const override;
    bool minimized() const override;

    float scaleX() const override;
    float scaleY() const override;

    void setCursor(Cursor cursor) override;
    void showCursor(bool show) override;
    void lockCursor(bool lock) override;

    IInput* input() const override;

    void onResize(ResizeCb cb) override;
    void onClose(CloseCb cb) override;
    void onFocus(FocusCb cb) override;

    void* native() const override;

    /**
     * @brief 获取 GLFW 窗口句柄
     */
    GLFWwindow* glfwWindow() const { return glfwWindow_; }

private:
    bool initGLFW();
    void deinitGLFW();
    void updateContentScale();
    
    // GLFW 回调函数（静态）
    static void framebufferSizeCallback(GLFWwindow* window, int width, int height);
    static void windowCloseCallback(GLFWwindow* window);
    static void windowFocusCallback(GLFWwindow* window, int focused);
    static void windowIconifyCallback(GLFWwindow* window, int iconified);
    static void cursorPosCallback(GLFWwindow* window, double xpos, double ypos);
    static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
    static void scrollCallback(GLFWwindow* window, double xoffset, double yoffset);
    static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
    static void joystickCallback(int jid, int event);

    GLFWwindow* glfwWindow_ = nullptr;
    
    UniquePtr<GLFWInput> input_;

    int width_ = 1280;
    int height_ = 720;
    bool fullscreen_ = false;
    bool vsync_ = true;
    bool focused_ = true;
    bool minimized_ = false;
    bool shouldClose_ = false;
    float scaleX_ = 1.0f;
    float scaleY_ = 1.0f;
    bool cursorVisible_ = true;
    bool cursorLocked_ = false;

    ResizeCb resizeCb_;
    CloseCb closeCb_;
    FocusCb focusCb_;
};

} // namespace extra2d
