
#include "keybinds_menu.h"
#include "ui.h"

#include <stdio.h>
#include <string.h>

void keybinds_menu_draw(const KeyBindMap *kb, Display *dpy, Window win, GC gc,
                         int win_w, int win_h, int scroll_top, int selected_idx,
                         int awaiting_key, const char *status_msg) {
    int box_w = KEYBINDS_MENU_BOX_W, box_h = KEYBINDS_MENU_BOX_H;
    int x = (win_w - box_w) / 2;
    int y = (win_h - box_h) / 2;

    ui_draw_bevel(dpy, win, gc, x, y, box_w, box_h, 0);

    XSetForeground(dpy, gc, 0x000000);
    XDrawString(dpy, win, gc, x + 8, y + 18, "Keybinds", 8);

    char posbuf[32];
    snprintf(posbuf, sizeof(posbuf), "%d/%d", selected_idx + 1, KEYBINDS_MENU_NUM_ROWS);
    int pw = (int)strlen(posbuf) * 6;
    XSetForeground(dpy, gc, 0x606060);
    XDrawString(dpy, win, gc, x + box_w - pw - 8, y + 18, posbuf, (int)strlen(posbuf));

    int list_y = y + KEYBINDS_MENU_LIST_Y;
    int row_h = KEYBINDS_MENU_ROW_H;

    for (int r = 0; r < KEYBINDS_MENU_VISIBLE_ROWS; r++) {
        int idx = scroll_top + r;
        if (idx >= KEYBINDS_MENU_NUM_ROWS)
            break;
        AppAction a = keybinds_menu_row_action(idx);
        int ry = list_y + r * row_h;
        int selected = (idx == selected_idx);

        if (selected) {
            /* Same pastel blue as the TRACKS nav-context badge -- a
             * flat highlight, not a bevel, since this row isn't itself
             * a button. */
            XSetForeground(dpy, gc, 0xB0D4F0);
            XFillRectangle(dpy, win, gc, x + 4, ry, box_w - 8, row_h);
        }

        XSetForeground(dpy, gc, 0x000000);
        const char *name = keybinds_action_name(a);
        XDrawString(dpy, win, gc, x + 8, ry + row_h - 5, name, (int)strlen(name));

        int bind_x = x + KEYBINDS_MENU_BINDING_COL_X;
        if (selected && awaiting_key) {
            XSetForeground(dpy, gc, 0xE00000);
            const char *prompt = "press a key... (Esc cancels)";
            XDrawString(dpy, win, gc, bind_x, ry + row_h - 5, prompt, (int)strlen(prompt));
        } else {
            char binding_buf[96];
            keybinds_format_binding(kb, a, binding_buf, sizeof(binding_buf));
            XSetForeground(dpy, gc, 0x000000);
            XDrawString(dpy, win, gc, bind_x, ry + row_h - 5, binding_buf, (int)strlen(binding_buf));
        }
    }

    XSetForeground(dpy, gc, 0x606060);
    const char *hint = "Up/Down select -- Enter rebinds -- Delete disables (\"none\") -- Escape closes";
    XDrawString(dpy, win, gc, x + 8, y + box_h - 24, hint, (int)strlen(hint));

    if (status_msg && status_msg[0]) {
        XSetForeground(dpy, gc, 0x000000);
        XDrawString(dpy, win, gc, x + 8, y + box_h - 8, status_msg, (int)strlen(status_msg));
    }
}
