#pragma once

#include "RmlUi/Core/Element.h"
#include "RmlUi/Core/StringUtilities.h"

namespace UI::Button {

class Component : public Rml::Element {

  public:
    Component(const Rml::String &tag) : Rml::Element(tag) {
        Update();
    }

  protected:
    void OnAttributeChange(const Rml::ElementAttributes &changed) override {
        Rml::Element::OnAttributeChange(changed);

        bool dirty = false;
        if (auto it = changed.find("variant"); it != changed.end()) {
            variant = it->second.Get<Rml::String>();
            dirty = true;
        }

        if (auto it = changed.find("size"); it != changed.end()) {
            size = it->second.Get<Rml::String>();
            dirty = true;
        }

        if (changed.find("disabled") != changed.end()) {
            disabled = ReadBoolAttribute("disabled");
            dirty = true;
        }

        if (changed.find("active") != changed.end()) {
            active = ReadBoolAttribute("active");
            dirty = true;
        }

        if (dirty) {
            Update();
        }
    }

  private:
    std::string variant = "primary";
    std::string size = "md";
    bool disabled = false;
    bool active = false;

    bool ReadBoolAttribute(const Rml::String &name) {
        if (!HasAttribute(name)) return false;
        Rml::String value = GetAttribute<Rml::String>(name, "");
        Rml::String lower = Rml::StringUtilities::ToLower(value);
        return !(lower == "0" || lower == "false");
    }

    void Update() {
        SetClass("button-variant-primary", variant == "primary");
        SetClass("button-variant-secondary", variant == "secondary");
        SetClass("button-variant-danger", variant == "danger");
        SetClass("button-variant-ghost", variant == "ghost");

        SetClass("button-size-sm", size == "sm");
        SetClass("button-size-md", size == "md");
        SetClass("button-size-lg", size == "lg");
        SetClass("button-size-chip", size == "chip");

        SetPseudoClass("disabled", disabled);
        SetPseudoClass("checked", active);
    }
};

} // namespace UI::Button
