#include "core/app_card.h"

namespace fn_ui {

static ImU32 with_alpha(ImU32 c, float a) {
    ImVec4 v = ImGui::ColorConvertU32ToFloat4(c);
    v.w = a;
    return ImGui::ColorConvertFloat4ToU32(v);
}

bool app_card(const AppCardData& data, ImVec2 size) {
    ImGui::PushID(data.id);
    ImVec2 pos = ImGui::GetCursorScreenPos();
    ImGui::InvisibleButton("##card", size);
    bool hovered = ImGui::IsItemHovered();
    bool held    = ImGui::IsItemActive();
    bool clicked = ImGui::IsItemClicked();

    ImDrawList* dl = ImGui::GetWindowDrawList();
    ImVec2 p0 = pos;
    ImVec2 p1 = ImVec2(pos.x + size.x, pos.y + size.y);

    ImU32 bg = with_alpha(data.accent, hovered ? 0.28f : 0.16f);
    if (held) bg = with_alpha(data.accent, 0.40f);
    ImU32 border = with_alpha(data.accent, hovered ? 0.95f : 0.55f);
    const float rounding = 8.0f;

    dl->AddRectFilled(p0, p1, bg, rounding);
    dl->AddRect(p0, p1, border, rounding, 0, 1.5f);

    const float stripe_w = 6.0f;
    dl->AddRectFilled(p0, ImVec2(p0.x + stripe_w, p1.y), data.accent, rounding,
                      ImDrawFlags_RoundCornersLeft);

    // Clip everything past this point so wrapped text never spills out.
    dl->PushClipRect(ImVec2(p0.x + stripe_w + 2.0f, p0.y + 2.0f),
                     ImVec2(p1.x - 2.0f, p1.y - 2.0f), true);

    const float pad_x = stripe_w + 10.0f;
    const float pad_y = 10.0f;

    // Optional icon on the left
    float text_left = p0.x + pad_x;
    if (data.icon != (ImTextureID)0) {
        float icon_size = size.y - 2.0f * pad_y;
        if (icon_size > 64.0f) icon_size = 64.0f;
        ImVec2 icon_p0(p0.x + pad_x, p0.y + (size.y - icon_size) * 0.5f);
        ImVec2 icon_p1(icon_p0.x + icon_size, icon_p0.y + icon_size);
        dl->AddImageRounded(data.icon, icon_p0, icon_p1,
                            ImVec2(0, 0), ImVec2(1, 1),
                            IM_COL32_WHITE, 6.0f);
        text_left = icon_p1.x + 10.0f;
    }

    ImVec2 title_pos = ImVec2(text_left, p0.y + pad_y);
    ImU32 title_col = IM_COL32(245, 245, 250, 255);
    if (data.title) {
        dl->AddText(title_pos, title_col, data.title);
    }

    if (data.description && data.description[0] != '\0') {
        ImVec2 desc_pos = ImVec2(text_left,
                                 title_pos.y + ImGui::GetTextLineHeight() + 4.0f);
        ImU32 desc_col = IM_COL32(195, 200, 210, 230);
        float wrap_w = (p1.x - 8.0f) - text_left;
        if (wrap_w < 20.0f) wrap_w = 20.0f;
        dl->AddText(NULL, 0.0f, desc_pos, desc_col,
                    data.description, NULL, wrap_w);
    }

    dl->PopClipRect();
    ImGui::PopID();
    return clicked;
}

}  // namespace fn_ui
