{ config, lib, pkgs, ... }:
{
  programs.waybar = let
    workspaceModule = {
      format = "{name}";
      enable-bar-scroll = true;
      disable-scroll-wraparound = true;
      numeric-first = true;
      warp-on-scroll = false;
    };

    windowModule = {
      icon = true;
      icon-size = 15;
      all-outputs = true;
      tooltip = false;
      rewrite = {
        "(.*) — LibreWolf" = "   $1";
        "LibreWolf" = "   Firefox";
        "(.*) - LibreWolf — Firefox" = "󰗃   $1";
      };
    };

    pulseModule = with pkgs; {
      format = "{icon}  {volume}%";
      format-bluetooth = "{icon} {volume}%";
      format-muted = " muted";
      format-icons = {
        headphone = "󰋋 ";
        headset = "󰋋 ";
        default = [
          " "
          " "
        ];
      };
      on-click = "${wireplumber}/bin/wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle";
      on-click-middle = "${wireplumber}/bin/wpctl set-volume @DEFAULT_AUDIO_SINK@ 100%";
      on-click-right = "${wireplumber}/bin/wpctl set-volume @DEFAULT_AUDIO_SINK@ 60%";
      ignored-sinks = [ "Easy Effects Sink" ];
    };

    # Monitoring
    cpuModule = {
      format = "  {usage}%";
      interval = 3;
    };

    ramModule = {
      format = "  {used}G";
      tooltip = false;
      interval = 3;
    };

    vramModule = {
      exec = with pkgs; pkgs.writeScript "vramScript.sh" ''
        #!/bin/sh

        LSPCI="${pciutils}/bin/lspci"
        GREP="${gnugrep}/bin/grep"
        AWK="${gawk}/bin/awk"
        BC="${bc}/bin/bc"
        HEAD="${uutils-coreutils-noprefix}/bin/head"
        CAT="${uutils-coreutils-noprefix}/bin/cat"

        # Detect the active GPU driver
        gpu_driver="$($LSPCI -k | $GREP -Eo 'in use: (nvidia|amdgpu)' | $AWK '{print $3}')"
        
        # Exit if no supported GPU driver is in use
        if [[ -z "$gpu_driver" ]]; then
          exit 0
        fi
        
        # Get VRAM usage in MB
        if [[ "$gpu_driver" == "nvidia" ]]; then
          vram_usage_mb="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | $HEAD -n1)"
        elif [[ "$gpu_driver" == "amdgpu" ]]; then
          vram_bytes="$($CAT /sys/class/drm/card*/device/mem_info_vram_used 2>/dev/null | $HEAD -n1)"
          vram_usage_mb="$($BC <<< "$vram_bytes / 1024 / 1024")"
        fi
        
        # Format VRAM usage for display
        if [[ "$vram_usage_mb" -lt 1024 ]]; then
          vram_usage_display="''${vram_usage_mb}M"
        else
          vram_usage_gib="$($BC <<< "scale=2; $vram_usage_mb / 1024")"
          vram_usage_display="''${vram_usage_gib}G"
        fi
        
        # Output the VRAM usage
        echo "{\"text\": \"󰢮  ''${vram_usage_display}\"}"
      '';
      format = "{}";
      return-type = "json";
      interval = 3;
    };

    # Clocks
    clockModule = {
      interval = 1;
      format = "{:%a %b %d %I:%M:%S%p}";
      tooltip-format = "<tt><small>{calendar}</small></tt>";
    };

    # Misc
    trayModule.spacing = 5;

    # Wireless
    networkModule = {
      format-ethernet = "󰈀";
      format-wifi = "";
      format-disconnected = "󰖪";
      format-linked = "";
      tooltip-format-ethernet = lib.concatStrings [
        "{ipaddr}\n"
        "{ifname} "
      ];
      tooltip-format-wifi = lib.concatStrings [
        "{ipaddr}\n"
        "{essid} ({signalStrength}%)"
      ];
      tooltip-format-disconnected = "Disconnected";
    };

    bluetoothModule = {
      format = "";
      format-disabled = "";
      format-no-controller = "";
      tooltip-format-on = "No devices connected.";
      tooltip-format-connected = lib.concatStrings [
        "{num_connections} connected\n"
        "{device_enumerate}"
      ];
      tooltip-format-enumerate-connected = "{device_alias}";
      tooltip-format-enumerate-connected-battery = "{device_alias} {device_battery_percentage}%";
    };

    scratchpadModule = {
      format = "   {count}";
      show-empty = false;
      tooltip = true;
      tooltip-format = "{title}";
    };

    gamemodeModule = {
      format = "{glyph}";
      hide-not-running = true;
      use-icon = true;
      icon-size = 19;
      icon-spacing = 0;
      tooltip = true;
    };

    privacyModule = {
      icon-spacing = 5;
      icon-size = 15;
    };

    mprisModule = {
      player = "mpd";
      format = "  {title}";
      format-paused = "  {artist}";
      format-stopped = "";
      tooltip-format = lib.concatStrings [
        "{title} - {artist} - {album}\n"
        "{position}/{length}"
      ];
      interval = 2;
      max-length = 30;
    };

    notificationModule = with pkgs; {
      exec = pkgs.writeScript "notificationScript.sh" ''
        #!/bin/sh

        SED="${gnused}/bin/sed"
        MAKOCTL="${mako}/bin/makoctl"

        # Extract the second line after "default"
        mode=$(echo "$($MAKOCTL mode)" | $SED -n '/default/{n;p}')

        # Print the notification status with the tooltip
        if [[ "$mode" == "do-not-disturb" ]]; then
          printf '{"text":"󱆥  Off","class":"disabled","tooltip":"Notifications Disabled."}'
        else
          printf '{"text":"  On","tooltip":"Notifications Enabled."}';
        fi
      '';
      format = "{}";
      return-type = "json";
      interval = 2;
      on-click = "${mako}/bin/makoctl mode -t do-not-disturb";
    };

    idleModule = {
      format = "{icon}";
      format-icons = {
        activated = "  On";
        deactivated = "󰾫  Off";
        tooltip-format-activated = "Sleep inhibited.";
        tooltip-format-deactivated = "Sleep uninhibited.";
      };
    };

    weatherModule = {
      exec = "${pkgs.wttrbar}/bin/wttrbar --ampm";
      format = "{}°";
      tooltip = true;
      return-type = "json";
      interval = 3600;
    };

    # Laptop modules
    backlightModule = {
      format = "{icon}  {percent}%";
      format-icons = [
        ""
        "󰖨"
      ];
      tooltip = false;
    };

    batteryModule = {
      interval = 60;
      states = {
        warning = 30;
        critical = 15;
      };
      format = "{icon}   {capacity}%";
      format-icons = [
        ""
        ""
        ""
        ""
        ""
      ];
    };
  in {
    enable = config.home.desktop.enable;
    systemd.enable = true;
    settings = {
      displayPrimary = {
        name = "bar1";
        position = "top";
        layer = "top";
        output = [
          "!${config.displays.tower2}"
          "!${config.displays.tower3}"
          "!${config.displays.estradiol2}"
          "*"
        ];
        modules-left = [
          "sway/workspaces"
          "sway/window"
        ];
        modules-right = [
          "pulseaudio"
          "mpris"
          "custom/notifs"
          "idle_inhibitor"
          "custom/weather"
          "cpu"
          "memory"
          "custom/vram"
          "backlight"
          "battery"
          "clock"
          "gamemode"
          "sway/scratchpad"
          "privacy"
          "tray"
          "bluetooth"
          "network"
        ];
        "sway/workspaces" = workspaceModule;
        "sway/window" = windowModule;
        "pulseaudio" = pulseModule;
        "mpris" = mprisModule;
        "custom/notifs" = notificationModule;
        "idle_inhibitor" = idleModule;
        "custom/weather" = weatherModule;
        "cpu" = cpuModule;
        "memory" = ramModule;
        "custom/vram" = vramModule;
        "backlight" = backlightModule;
        "battery" = batteryModule;
        "clock" = clockModule;
        "sway/scratchpad" = scratchpadModule;
        "privacy" = privacyModule;
        "tray" = trayModule;
        "bluetooth" = bluetoothModule;
        "network" = networkModule;
      };

      displaySecondary = {
        name = "bar2";
        position = "top";
        layer = "top";
        output = [
          config.displays.tower2
          config.displays.tower3
          config.displays.estradiol2
        ];
        modules-left = [
          "sway/workspaces"
          "sway/window"
        ];
        modules-right = [
          "pulseaudio"
          "cpu"
          "memory"
          "custom/vram"
          "clock"
        ];
        "sway/workspaces" = workspaceModule;
        "sway/window" = windowModule;
        "pulseaudio" = pulseModule;
        "cpu" = cpuModule;
        "memory" = ramModule;
        "custom/vram" = vramModule;
        "clock" = clockModule;
      };
    };

    style = ''
      * {
        border: 0;
        border-radius: 0;
        min-height: 0;
        font-family: ${config.look.fonts.main}, ${config.look.fonts.mono};
        font-size: 15.5px;
        color: #${config.look.colors.text};
      }
      #waybar {
        background: #${config.look.colors.dark};
      }
      #workspaces {
        padding: 0 6px 0 0;
      }
      #tray {
        padding: 0 2px 0 5px;
      }
      #network {
        padding: 0 10px 0 4px;
      }
      #bluetooth {
        margin: 0 6px 0 4px;
        font-size: 13.4px;
      }
      #workspaces button {
        padding: 0 3px;
        color: white;
        border-bottom: 3px solid transparent;
        min-width: 20px;
      }
      #scratchpad, #privacy {
        margin-left: 4px;
      }
      #mpris, #custom-notifs, #idle_inhibitor, #custom-weather, #cpu, #memory, #custom-vram, #backlight, #battery {
        margin: 0 5px 0 2px;
      }
      #pulseaudio {
        margin-right: 5px;
      }

      #workspaces button.visible, #workspaces button.active {
        border-bottom: 3px solid #${config.look.colors.prime};
        background: #${config.look.colors.mid};
      }
      #workspaces button.urgent {
        border-bottom: 3px solid #${config.look.colors.urgent};
      }
      #workspaces button:hover {
        box-shadow: none;
        background: #${config.look.colors.light};
      }
      #mpris {
        border-bottom: 3px solid #ffb066;
      }
      #custom-notifs {
        border-bottom: 3px solid #3823C4;
      }
      #idle_inhibitor {
        border-bottom: 3px solid #941efc;
      }
      #custom-weather {
        border-bottom: 3px solid #c75bd3;
      }
      #cpu {
        border-bottom: 3px solid #f90000;
      }
      #memory {
        border-bottom: 3px solid #4bffdc;
      }
      #custom-vram {
        border-bottom: 3px solid #33FF00;
      }
      #backlight {
        border-bottom: 3px solid #5ffca3;
      }
      #battery {
        border-bottom: 3px solid #fcfc16;
      }
      #clock {
        border-bottom: 3px solid #0a6cf5;
        margin: 0 2px 0 2px;
      }

      #mpris.paused, #custom-notifs.disabled, #idle_inhibitor.deactivated {
        color: #888;
      }
      #pulseaudio.muted, #network.disconnected, #bluetooth.off {
        color: #424242;
      }
    '';
  };
}
