import { Gtk } from "ags/gtk4";
import { createEffect } from "ags";
import { niriAction, niriEvent } from "../../lib/niri";

/**
 * Bar widget showing niri workspaces as clickable buttons.
 */
export function NiriWorkspaces() {
    const root = new Gtk.Box({
        cssClasses: ["niri-workspaces"],
    });

    createEffect(() => {
        const workspaces = niriEvent.workspaces();
        const focusedId = niriEvent.focusedWorkspaceId();

        // Remove existing children
        let child = root.get_first_child();
        while (child) {
            const next = child.get_next_sibling();
            root.remove(child);
            child = next;
        }

        // Sort by idx (the display number)
        const sorted = [...workspaces].sort((a, b) => a.idx - b.idx);

        for (const ws of sorted) {
            const isFocused = ws.id === focusedId;
            const cssClasses = ["workspace-btn"];

            if (isFocused) {
                cssClasses.push("active");
            } else if (ws.is_urgent) {
                cssClasses.push("urgent");
            } else {
                cssClasses.push("inactive");
            }

            const btn = new Gtk.Button({
                label: `${ws.idx}`,
                cssClasses,
            });

            btn.connect("clicked", () => {
                // Use the action client instead of subprocess
                niriAction.send({ Action: { FocusWorkspace: { reference: { Index: ws.idx } } } })
                    .catch(err => console.error(err));
            });

            root.append(btn);
        }
    });

    return root;
}