#pragma once
#include "Engine.h"
#include "Input.h"
#include "Json.h"
#include <iostream>
#include <functional>

// MainMenu: JSON-driven menu rendered with the Font system.
//
// JSON schema:
// {
//   "title": "My Game",
//   "background_color": [0.05, 0.05, 0.12],
//   "title_color": [1.0, 0.8, 0.2],
//   "item_color": [0.8, 0.8, 0.8],
//   "selected_color": [1.0, 1.0, 0.0],
//   "title_size": 28,
//   "item_size": 16,
//   "line_spacing": 50,
//   "items": [
//     { "label": "Play Landscape", "action": "landscape" },
//     { "label": "Scene Demo",     "action": "demo" },
//     { "label": "Quit",           "action": "quit" }
//   ]
// }

class MainMenu : public Engine {
public:
    using LaunchCallback = std::function<void(const std::string& action)>;

    MainMenu(const json::Value& config, LaunchCallback onLaunch)
        : Engine(1920, 1080, "ZoomEngine")
        , config_(config)
        , onLaunch_(onLaunch)
    {
        title_ = config_.get_string("title", "ZoomEngine");
        titleSize_ = config_.get_float("title_size", 56.0f);
        itemSize_  = config_.get_float("item_size", 32.0f);
        lineSpacing_ = config_.get_float("line_spacing", 70.0f);

        auto readColor = [&](const std::string& key, glm::vec3 def) -> glm::vec3 {
            if (config_.has(key) && config_[key].is_array()) {
                auto& a = config_[key].as_array();
                if (a.size() >= 3) return {a[0].as_float(), a[1].as_float(), a[2].as_float()};
            }
            return def;
        };
        bg_color_    = readColor("background_color", {0.05f, 0.05f, 0.12f});
        title_color_ = readColor("title_color",      {1.0f, 0.85f, 0.2f});
        item_color_  = readColor("item_color",        {0.65f, 0.65f, 0.7f});
        sel_color_   = readColor("selected_color",    {1.0f, 1.0f, 0.3f});

        if (config_.has("items") && config_["items"].is_array()) {
            for (auto& item : config_["items"].as_array()) {
                MenuItem mi;
                mi.label  = item.get_string("label", "???");
                mi.action = item.get_string("action", "");
                items_.push_back(mi);
            }
        }
    }

    bool OnInitialize() override {
        show_overlay_ = false;
        return true;
    }

    void OnUpdate(float dt) override {
        time_ += dt;

        // Keyboard navigation
        if (Input::IsKeyPressed(GLFW_KEY_UP) || Input::IsKeyPressed(GLFW_KEY_W))
            selected_ = (selected_ + (int)items_.size() - 1) % (int)items_.size();
        if (Input::IsKeyPressed(GLFW_KEY_DOWN) || Input::IsKeyPressed(GLFW_KEY_S))
            selected_ = (selected_ + 1) % (int)items_.size();
        if (Input::IsKeyPressed(GLFW_KEY_ENTER) || Input::IsKeyPressed(GLFW_KEY_SPACE))
            activate();

        // Gamepad navigation
        if (Input::IsGamepadConnected()) {
            if (Input::IsGamepadButtonPressed(Input::GamepadButton::DPadUp))
                selected_ = (selected_ + (int)items_.size() - 1) % (int)items_.size();
            if (Input::IsGamepadButtonPressed(Input::GamepadButton::DPadDown))
                selected_ = (selected_ + 1) % (int)items_.size();
            if (Input::IsGamepadButtonPressed(Input::GamepadButton::Cross))
                activate();

            float ly = Input::GetGamepadAxis(Input::GamepadAxis::LeftY);
            if (std::fabs(ly) > 0.5f) {
                if (!stick_held_) {
                    stick_held_ = true;
                    if (ly < -0.5f) selected_ = (selected_ + (int)items_.size() - 1) % (int)items_.size();
                    if (ly >  0.5f) selected_ = (selected_ + 1) % (int)items_.size();
                }
            } else {
                stick_held_ = false;
            }
        }

        if (Input::IsKeyPressed(GLFW_KEY_ESCAPE))
            glfwSetWindowShouldClose(window_, GLFW_TRUE);
    }

    void OnRender() override {
        glClearColor(bg_color_.r, bg_color_.g, bg_color_.b, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        font_.begin(width_, height_);

        float centerX = width_ * 0.5f;
        float startY  = height_ * 0.6f;

        // Title
        font_.drawTextCentered(title_, centerX, startY, titleSize_, title_color_, 4.0f);

        // Subtitle
        font_.drawTextCentered("Press Enter or Cross to select", centerX,
                               startY - 60.0f, 18.0f, item_color_ * 0.6f, 1.5f);

        // Menu items
        for (int i = 0; i < (int)items_.size(); ++i) {
            float y = startY - 120.0f - i * lineSpacing_;
            glm::vec3 color = (i == selected_) ? sel_color_ : item_color_;
            std::string label = items_[i].label;

            if (i == selected_) {
                float pulse = 0.7f + 0.3f * std::sin(time_ * 4.0f);
                color *= pulse;
                label = "> " + label + " <";
            }

            font_.drawTextCentered(label, centerX, y, itemSize_, color, 3.0f);
        }

        // Version / footer
        font_.drawText("ZoomEngine v0.1", 14.0f, 14.0f, 14.0f, item_color_ * 0.4f, 1.5f);

        font_.end();
    }

private:
    struct MenuItem {
        std::string label;
        std::string action;
    };

    json::Value config_;
    LaunchCallback onLaunch_;
    std::string title_ = "ZoomEngine";
    std::vector<MenuItem> items_;
    int selected_ = 0;
    float time_ = 0.0f;
    bool stick_held_ = false;

    float titleSize_ = 56.0f;
    float itemSize_  = 32.0f;
    float lineSpacing_ = 70.0f;

    glm::vec3 bg_color_    = {0.05f, 0.05f, 0.12f};
    glm::vec3 title_color_ = {1.0f, 0.85f, 0.2f};
    glm::vec3 item_color_  = {0.65f, 0.65f, 0.7f};
    glm::vec3 sel_color_   = {1.0f, 1.0f, 0.3f};

    std::string selected_action_;

    void activate() {
        if (items_.empty()) return;
        const std::string& action = items_[selected_].action;
        if (action == "quit") {
            glfwSetWindowShouldClose(window_, GLFW_TRUE);
        } else {
            glfwSetWindowShouldClose(window_, GLFW_TRUE);
            selected_action_ = action;
        }
    }

public:
    const std::string& getSelectedAction() const { return selected_action_; }
};
