{
  config,
  pkgs,
  myConfig,
  ...
}: let
  # --- POPUP SCRIPTS ---
  # FIXME: must be centered
  hakase-launch-or-focus = pkgs.writeShellScriptBin "hakase-launch-or-focus" ''
    if (($# == 0)); then
      echo "Usage: hakase-launch-or-focus [window-pattern] [launch-command]"
      exit 1
    fi

    WINDOW_PATTERN="$1"
    # Escaped Nix interpolation for shell default value logic
    LAUNCH_COMMAND="''${2:- \"uwsm-app -- $WINDOW_PATTERN\"}"

    # Locate window address via hyprctl and jq
    WINDOW_ADDRESS=$(${pkgs.hyprland}/bin/hyprctl clients -j | ${pkgs.jq}/bin/jq -r --arg p "$WINDOW_PATTERN"
      '.[] | select((.class | test("\\b" + $p + "\\b"; "i")) or (.title | test("\\b" + $p + "\\b"; "i"))) | .address' | head -n1)

    if [[ -n $WINDOW_ADDRESS ]]; then
      # If found, focus the existing window
      ${pkgs.hyprland}/bin/hyprctl dispatch focuswindow "address:$WINDOW_ADDRESS"
    else
      # If not found, execute the launch command
      eval exec setsid $LAUNCH_COMMAND
    fi
  '';

  hakase-launch-tui = pkgs.writeShellScriptBin "hakase-launch-tui" ''
    APP_NAME=$(basename "$1")
    # Using org.hakase prefix so the focus script can find it via class name
    exec setsid uwsm-app -- xdg-terminal-exec --app-id=org.hakase."$APP_NAME" -e "$@"
  '';

  hakase-focus-wrapper = pkgs.writeShellScriptBin "hakase-focus-wrapper" ''
    APP_NAME=$(basename "$1")
    WINDOW_PATTERN="org.hakase.$APP_NAME"
    LAUNCH_CMD="hakase-launch-tui $*"

    exec hakase-launch-or-focus "$WINDOW_PATTERN" "$LAUNCH_CMD"
  '';

  hakase-launch-wifi = pkgs.writeShellScriptBin "hakase-launch-wifi" ''
    # Use the focus wrapper to launch or switch to Impala
    exec hakase-focus-wrapper impala
  '';

  hakase-launch-bluetooth = pkgs.writeShellScriptBin "hakase-launch-bluetooth" ''
    exec hakase-focus-wrapper bluetui
  '';

  hakase-launch-popup = pkgs.writeShellScriptBin "hakase-launch-popup" ''
    if (($# < 3)); then
      echo "Usage: hakase-launch-popup [width] [height] [command...]"
      exit 1
    fi

    # --- ARGS & CONFIG ---
    WIN_WIDTH="$1"
    WIN_HEIGHT="$2"
    shift 2

    MARGIN=10
    BAR_HEIGHT=40
    # ---------------------

    CMD_NAME=$(basename "$1")
    TARGET_CLASS="org.hakase.popup.$CMD_NAME"

    # 1. SINGLETON LOGIC: Check for ANY existing hakase popup
    EXISTING_JSON=$(${pkgs.hyprland}/bin/hyprctl clients -j | ${pkgs.jq}/bin/jq -r '.[] | select(.class | startswith("org.hakase.popup."))')

    if [[ -n "$EXISTING_JSON" ]]; then
      OLD_ADDR=$(echo "$EXISTING_JSON" | ${pkgs.jq}/bin/jq -r '.address')
      OLD_CLASS=$(echo "$EXISTING_JSON" | ${pkgs.jq}/bin/jq -r '.class')

      # Close the existing popup
      ${pkgs.hyprland}/bin/hyprctl dispatch closewindow "address:$OLD_ADDR"

      if [[ "$OLD_CLASS" == "$TARGET_CLASS" ]]; then
        exit 0
      fi
      sleep 0.15
    fi

    # 2. Calculate Geometry
    MONITOR_INFO=$(${pkgs.hyprland}/bin/hyprctl monitors -j | ${pkgs.jq}/bin/jq '.[] | select(.focused == true)')
    MON_X=$(echo "$MONITOR_INFO" | ${pkgs.jq}/bin/jq '.x')
    MON_Y=$(echo "$MONITOR_INFO" | ${pkgs.jq}/bin/jq '.y')
    MON_WIDTH=$(echo "$MONITOR_INFO" | ${pkgs.jq}/bin/jq '.width')

    TARGET_X=$((MON_X + MON_WIDTH - WIN_WIDTH - MARGIN))
    TARGET_Y=$((MON_Y + BAR_HEIGHT + MARGIN))

    # 3. Launch with Rules
    RULE="[float;pin;size $WIN_WIDTH $WIN_HEIGHT;move $TARGET_X $TARGET_Y]"
    ${pkgs.hyprland}/bin/hyprctl dispatch exec "$RULE xdg-terminal-exec --app-id=$TARGET_CLASS -e $@"

    # 4. Background Listener (Close on Blur)
    (
      TIMEOUT=0
      WINDOW_ADDR=""
      while [[ -z "$WINDOW_ADDR" && $TIMEOUT -lt 20 ]]; do
        sleep 0.1
        WINDOW_ADDR=$(${pkgs.hyprland}/bin/hyprctl clients -j | ${pkgs.jq}/bin/jq -r --arg c "$TARGET_CLASS" '.[] | select(.class == $c) | .address')
        ((TIMEOUT++))
      done

      if [[ -n "$WINDOW_ADDR" ]]; then
        ${pkgs.socat}/bin/socat -U - UNIX-CONNECT:"$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" | while read -r line; do
          if [[ "$line" == "activewindow>>"* ]]; then
            NEW_FOCUS="0x$(echo "$line" | cut -d '>' -f3 | cut -d ',' -f1)"
            if [[ "$WINDOW_ADDR" != "$NEW_FOCUS" ]]; then
               ${pkgs.hyprland}/bin/hyprctl dispatch closewindow "address:$WINDOW_ADDR"
               break
            fi
          fi
        done
      fi
    ) &

    exit 0
  '';

  hakase-popup-wifi = pkgs.writeShellScriptBin "hakase-popup-wifi" ''
    exec hakase-launch-popup 800 500 impala
  '';

  hakase-popup-bluetooth = pkgs.writeShellScriptBin "hakase-popup-bluetooth" ''
    exec hakase-launch-popup 600 500 bluetui
  '';

  hakase-popup-volume = pkgs.writeShellScriptBin "hakase-popup-volume" ''
    exec hakase-launch-popup 800 300 wiremix
  '';
in {
  wayland.windowManager.hyprland.settings = {
    exec-once = [
      "uwsm app -- waybar"
    ];
  };
  imports = [
    ./style.nix
  ];

  home.packages = [
    pkgs.jq
    pkgs.socat
    pkgs.util-linux
    pkgs.bluetui
    pkgs.impala
    pkgs.wiremix
    pkgs.pamixer

    hakase-launch-popup
    hakase-popup-wifi
    hakase-popup-bluetooth
    hakase-popup-volume

    hakase-launch-or-focus
    hakase-launch-tui
    hakase-focus-wrapper
    hakase-launch-wifi
    hakase-launch-bluetooth
  ];

  programs.waybar = {
    enable = true;
    settings = {
      mainBar = {
        reload_style_on_change = true;
        layer = "top";
        position = "top";
        spacing = 0;
        height = 26;

        modules-left = ["custom/omarchy" "hyprland/workspaces" "hyprland/workspaces#special"];
        modules-center = ["clock" "custom/update" "custom/screenrecording-indicator"];
        modules-right = [
          "group/tray-expander"
          "bluetooth"
          "network"
          "pulseaudio"
          "cpu"
          "battery"
        ];

        "hyprland/workspaces" = {
          on-click = "activate";
          show-special = false;
          all-outputs = true;
          format = "{icon}";
          format-icons = {
            "default" = "";
            "1" = "1";
            "2" = "2";
            "3" = "3";
            "4" = "4";
            "5" = "5";
            "6" = "6";
            "7" = "7";
            "8" = "8";
            "9" = "9";
            "10" = "0";
            "active" = "󱓻";
          };
          persistent-workspaces = {
            "1" = [];
            "2" = [];
            "3" = [];
            "4" = [];
            "5" = [];
          };
        };

        "hyprland/workspaces#special" = {
          on-click = "activate";
          show-special = true;
          special-visible-only = true;
          all-outputs = true;
          ignore-workspaces = ["1" "2" "3" "4" "5" "6" "7" "8" "9" "10"];
          format = "{icon}";
          format-icons = {
            "special:youtube" = "󰗃";
            "special:music" = "󰎆";
            "special:steam" = "󰓓";
          };
        };

        "custom/omarchy" = {
          format = "";
          on-click = "vicinae toggle"; # TODO: add fallback
          on-click-right = "xdg-terminal-exec";
          tooltip-format = "Omarchy Menu\n\nSuper + Alt + Space";
        };

        "cpu" = {
          interval = 5;
          format = "󰍛";
          on-click = "hakase-focus-wrapper btop";
          on-click-right = "xdg-terminal-exec";
        };

        "clock" = {
          format = "{:%H:%M %a %b %d}";
          format-alt = "{:L%d %B W%V %Y}";
          tooltip = false;
          on-click-right = "omarchy-launch-floating-terminal-with-presentation omarchy-tz-select";
        };

        "network" = {
          format-icons = ["󰤯" "󰤟" "󰤢" "󰤥" "󰤨"];
          format = "{icon}";
          format-wifi = "{icon}";
          format-ethernet = "󰀂";
          format-disconnected = "󰤮";
          tooltip-format-wifi = "{essid} ({frequency} GHz)\n⇣{bandwidthDownBytes}  ⇡{bandwidthUpBytes}";
          tooltip-format-ethernet = "⇣{bandwidthDownBytes}  ⇡{bandwidthUpBytes}";
          tooltip-format-disconnected = "Disconnected";
          interval = 3;
          spacing = 1;
          on-click = "hakase-popup-wifi";
        };

        "battery" = {
          format = "{capacity}% {icon}";
          format-discharging = "{icon}";
          format-charging = "{icon}";
          format-plugged = "";
          format-icons = {
            charging = ["󰢜" "󰂆" "󰂇" "󰂈" "󰢝" "󰂉" "󰢞" "󰂊" "󰂋" "󰂅"];
            default = ["󰁺" "󰁻" "󰁼" "󰁽" "󰁾" "󰁿" "󰂀" "󰂁" "󰂂" "󰁹"];
          };
          format-full = "󰂅";
          tooltip-format-discharging = "{power:>1.0f}W↓ {capacity}%";
          tooltip-format-charging = "{power:>1.0f}W↑ {capacity}%";
          interval = 5;
          on-click = "omarchy-menu power";
          states = {
            warning = 20;
            critical = 10;
          };
        };

        "bluetooth" = {
          format = "";
          format-disabled = "󰂲";
          format-connected = "󰂱";
          format-no-controller = "";
          tooltip-format = "Devices connected: {num_connections}";
          on-click = "hakase-popup-bluetooth";
        };

        "pulseaudio" = {
          format = "{icon}";
          on-click = "hakase-popup-volume";
          on-click-right = "pamixer -t";
          tooltip-format = "Playing at {volume}%";
          scroll-step = 5;
          format-muted = "";
          format-icons = {
            default = ["" "" ""];
          };
        };

        "group/tray-expander" = {
          orientation = "inherit";
          drawer = {
            transition-duration = 600;
            children-class = "tray-group-item";
          };
          modules = ["custom/expand-icon" "tray"];
        };

        "custom/expand-icon" = {
          format = "";
          tooltip = false;
        };

        "custom/screenrecording-indicator" = {
          on-click = "omarchy-cmd-screenrecord";
          exec = "$OMARCHY_PATH/default/waybar/indicators/screen-recording.sh";
          signal = 8;
          return-type = "json";
        };

        "tray" = {
          icon-size = 12;
          spacing = 17;
        };
      };
    };
  };
}
