#pragma once

#include <SDL3/SDL.h>

#include <cstdint>
#include <memory>

#include "core/rendering/shader_backend.hpp"

class Screen {
   public:
    static void init();
    static void destroy();
    static auto get() -> Screen*;

    // Presentació — rep el buffer ARGB de 320x200 de JD8
    void present(Uint32* pixel_data);

    // Gestió de finestra
    void toggleFullscreen();
    void incZoom();
    void decZoom();
    void setZoom(int zoom);

    // Shaders i vídeo
    void toggleShaders();
    void toggleSupersampling();
    void toggleAspectRatio();
    void toggleIntegerScale();
    void toggleStretchFilter();
    void nextShaderType();  // Cicla PostFX ↔ CrtPi (F7)
    void prevShaderType();  // Cicla al revés
    void nextPreset();      // Cicla presets del shader actiu (F8)
    void prevPreset();      // Cicla presets al revés
    [[nodiscard]] auto getCurrentPresetName() const -> const char*;
    void setActiveShader(Rendering::ShaderType type);
    void applyCurrentPostFXPreset();
    void applyCurrentCrtPiPreset();

    // Getters
    [[nodiscard]] auto isFullscreen() const -> bool { return fullscreen_; }
    [[nodiscard]] auto getZoom() const -> int { return zoom_; }
    [[nodiscard]] auto isHardwareAccelerated() const -> bool;
    [[nodiscard]] auto getActiveShaderName() const -> const char*;
    [[nodiscard]] auto getWindow() -> SDL_Window* { return window_; }
    [[nodiscard]] auto getRenderer() -> SDL_Renderer* { return renderer_; }

   private:
    Screen();
    ~Screen();

    void adjustWindowSize();
    void calculateMaxZoom();
    void initShaders();

    static Screen* instance_;

    SDL_Window* window_{nullptr};
    SDL_Renderer* renderer_{nullptr};
    SDL_Texture* texture_{nullptr};  // 320x200 streaming, ABGR8888 (fallback SDL_Renderer)

    // Backend GPU (nullptr si no disponible o desactivat)
    std::unique_ptr<Rendering::ShaderBackend> shader_backend_;

    void updateRenderInfo();

    struct FPS {
        Uint32 ticks{0};
        int frame_count{0};
        int last_value{0};

        void increment() { frame_count++; }
        auto calculate(Uint32 current_ticks) -> int {
            if (current_ticks - ticks >= 1000) {
                last_value = frame_count;
                frame_count = 0;
                ticks = current_ticks;
            }
            return last_value;
        }
    };

    int zoom_{3};
    int max_zoom_{6};
    bool fullscreen_{false};
    FPS fps_;
    std::string gpu_driver_;

    static constexpr int GAME_WIDTH = 320;
    static constexpr int GAME_HEIGHT = 200;
};
