#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# shura@ameko — niri / CachyOS rice setup script
# WM: niri (Wayland tiling), Terminal: kitty, Shell: fish
# Theme: pink/magenta/purple throughout
# ─────────────────────────────────────────────────────────────────────────────

set -euo pipefail

PINK="#f472b6"
MAGENTA="#e879f9"
PURPLE="#a855f7"
BG="#1a1025"
BG2="#2d1b3d"
FG="#fde8ff"

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
info()  { echo -e "${GREEN}[+]${NC} $*"; }
warn()  { echo -e "${YELLOW}[!]${NC} $*"; }
step()  { echo -e "\n${CYAN}━━━ $* ━━━${NC}"; }
die()   { echo -e "${RED}[✗]${NC} $*"; exit 1; }

require() { command -v "$1" &>/dev/null || { warn "Missing: $1 — install it first"; return 1; }; }

# ─── DIRS ─────────────────────────────────────────────────────────────────────
mkdir -p \
    "$HOME/.config/niri" \
    "$HOME/.config/kitty" \
    "$HOME/.config/fish" \
    "$HOME/.config/waybar" \
    "$HOME/.config/htop" \
    "$HOME/.config/gtk-3.0" \
    "$HOME/.config/gtk-4.0" \
    "$HOME/.local/share/fonts"

# ─── 1. PACKAGES ──────────────────────────────────────────────────────────────
step "Installing packages"

PKGS=(
    niri          # tiling Wayland compositor
    kitty         # terminal
    fish          # shell
    waybar        # status bar
    wofi          # launcher
    mako          # notifications
    swww          # wallpaper daemon
    htop          # system monitor
    wl-clipboard  # clipboard
    grim          # screenshots
    slurp         # region select
    xdg-desktop-portal-gnome
    noto-fonts
    ttf-nerd-fonts-symbols
    ttf-jetbrains-mono-nerd
)

if command -v pacman &>/dev/null; then
    info "Installing via pacman..."
    sudo pacman -S --needed --noconfirm "${PKGS[@]}" 2>/dev/null || \
        warn "Some packages may not be in official repos — check AUR"

    AUR_PKGS=(niri-git lapifetch-git)
    if command -v yay &>/dev/null; then
        yay -S --needed --noconfirm "${AUR_PKGS[@]}" 2>/dev/null || \
            warn "AUR packages failed — install manually"
    elif command -v paru &>/dev/null; then
        paru -S --needed --noconfirm "${AUR_PKGS[@]}" 2>/dev/null || \
            warn "AUR packages failed — install manually"
    else
        warn "No AUR helper found. Install yay or paru, then: yay -S ${AUR_PKGS[*]}"
    fi
else
    warn "Not on Arch/CachyOS — install these manually: ${PKGS[*]}"
fi

# ─── 2. NIRI CONFIG ───────────────────────────────────────────────────────────
step "Writing niri config"
cat > "$HOME/.config/niri/config.kdl" <<'EOF'
input {
    keyboard {
        xkb { layout "us" }
        repeat-delay 300
        repeat-rate 50
    }
    touchpad {
        tap
        natural-scroll
        accel-speed 0.2
    }
    mouse {
        accel-speed 0.0
    }
}

output "eDP-1" {
    mode "1920x1080@144.001"
    scale 1.0
}

layout {
    gaps 8
    center-focused-column "never"
    preset-column-widths {
        proportion 0.333333
        proportion 0.5
        proportion 0.666667
        proportion 1.0
    }
    default-column-width { proportion 0.5 }
    focus-ring {
        width 2
        active-color "#f472b6"
        inactive-color "#2d1b3d"
    }
    border {
        width 1
        active-color "#e879f9"
        inactive-color "#3b2151"
    }
}

spawn-at-startup "waybar"
spawn-at-startup "swww" "init"
spawn-at-startup "mako"

prefer-no-csd

screenshot-path "~/Pictures/Screenshots/niri-%Y-%m-%d-%H-%M-%S.png"

animations {
    slowdown 0.8
}

window-rule {
    geometry-corner-radius 10
    clip-to-geometry true
}

window-rule {
    match app-id="kitty"
    opacity 0.95
}

window-rule {
    match app-id="firefox"
    opacity 1.0
}

binds {
    Mod+Return { spawn "kitty"; }
    Mod+D { spawn "wofi" "--show" "drun"; }
    Mod+Shift+Q { close-window; }
    Mod+Shift+E { quit; }

    Mod+H { focus-column-left; }
    Mod+J { focus-window-down; }
    Mod+K { focus-window-up; }
    Mod+L { focus-column-right; }

    Mod+Shift+H { move-column-left; }
    Mod+Shift+J { move-window-down; }
    Mod+Shift+K { move-window-up; }
    Mod+Shift+L { move-column-right; }

    Mod+1 { focus-workspace 1; }
    Mod+2 { focus-workspace 2; }
    Mod+3 { focus-workspace 3; }
    Mod+4 { focus-workspace 4; }
    Mod+5 { focus-workspace 5; }

    Mod+Shift+1 { move-column-to-workspace 1; }
    Mod+Shift+2 { move-column-to-workspace 2; }
    Mod+Shift+3 { move-column-to-workspace 3; }
    Mod+Shift+4 { move-column-to-workspace 4; }
    Mod+Shift+5 { move-column-to-workspace 5; }

    Mod+F { maximize-column; }
    Mod+Shift+F { fullscreen-window; }
    Mod+C { center-column; }
    Mod+R { switch-preset-column-width; }
    Mod+Minus { set-column-width "-10%"; }
    Mod+Equal { set-column-width "+10%"; }

    Print { screenshot; }
    Ctrl+Print { screenshot-screen; }
    Alt+Print { screenshot-window; }

    XF86AudioRaiseVolume { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "5%+"; }
    XF86AudioLowerVolume { spawn "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "5%-"; }
    XF86AudioMute { spawn "wpctl" "set-mute" "@DEFAULT_AUDIO_SINK@" "toggle"; }
    XF86MonBrightnessUp { spawn "brightnessctl" "set" "10%+"; }
    XF86MonBrightnessDown { spawn "brightnessctl" "set" "10%-"; }
}
EOF
info "niri config written"

# ─── 3. KITTY THEME ───────────────────────────────────────────────────────────
step "Writing kitty config (pink/purple theme)"
cat > "$HOME/.config/kitty/kitty.conf" <<EOF
font_family      JetBrainsMono Nerd Font
bold_font        auto
italic_font      auto
bold_italic_font auto
font_size        11.0

background            #1a1025
foreground            #fde8ff
selection_background  #e879f9
selection_foreground  #1a1025

cursor                #f472b6
cursor_text_color     #1a1025
cursor_shape          beam
cursor_beam_thickness 1.8

url_color             #a855f7
url_style             curly

# Black
color0  #1a1025
color8  #3b2151

# Red
color1  #f43f5e
color9  #fb7185

# Green
color2  #10b981
color10 #34d399

# Yellow
color3  #f59e0b
color11 #fbbf24

# Blue
color4  #6366f1
color12 #818cf8

# Magenta / Pink
color5  #e879f9
color13 #f472b6

# Cyan
color6  #06b6d4
color14 #22d3ee

# White
color7  #fde8ff
color15 #ffffff

background_opacity    0.95
dynamic_background_color yes

window_padding_width  8
window_border_width   1pt
active_border_color   #f472b6
inactive_border_color #3b2151

tab_bar_style         powerline
tab_powerline_style   slanted
active_tab_background   #e879f9
active_tab_foreground   #1a1025
inactive_tab_background #2d1b3d
inactive_tab_foreground #fde8ff

enable_audio_bell no
visual_bell_duration 0.1

shell fish
shell_integration enabled
EOF
info "kitty config written"

# ─── 4. FISH CONFIG ───────────────────────────────────────────────────────────
step "Writing fish config"
cat > "$HOME/.config/fish/config.fish" <<'EOF'
if status is-interactive
    set -g fish_greeting ""

    # Pink prompt colors
    set -g fish_color_command f472b6 --bold
    set -g fish_color_param fde8ff
    set -g fish_color_error f43f5e --bold
    set -g fish_color_operator e879f9
    set -g fish_color_autosuggestion 6b4e7d
    set -g fish_color_keyword a855f7 --bold
    set -g fish_color_quote 10b981
    set -g fish_color_comment 6b4e7d
    set -g fish_color_cwd f472b6
    set -g fish_color_host e879f9
    set -g fish_color_user a855f7

    # Custom prompt
    function fish_prompt
        set_color $fish_color_user
        echo -n (whoami)
        set_color normal
        echo -n "@"
        set_color $fish_color_host
        echo -n (hostname -s)
        set_color normal
        echo -n " "
        set_color $fish_color_cwd
        echo -n (prompt_pwd)
        set_color normal
        echo -n " ❯ "
    end

    function fish_right_prompt
        set_color 6b4e7d
        date "+%H:%M"
        set_color normal
    end

    # Aliases
    alias ls="ls --color=auto"
    alias la="ls -la --color=auto"
    alias ll="ls -l --color=auto"
    alias grep="grep --color=auto"
    alias cat="bat --style=plain" 2>/dev/null; or alias cat="cat"
    alias fetch="lapifetch -nc | gay -t"
    alias sfetch="shorkfetch | gay -n"
end
EOF
info "fish config written"

# ─── 5. HTOP THEME ────────────────────────────────────────────────────────────
step "Writing htop config (pink theme)"
cat > "$HOME/.config/htop/htoprc" <<EOF
htop_version=3.3.0
config_reader_min_version=3
fields=0 48 17 18 38 39 40 2 46 47 49 1
hide_kernel_threads=1
hide_userland_threads=0
highlight_base_name=1
show_program_path=0
highlight_deleted_exe=1
tree_view=0
tree_sort_key=0
tree_sort_direction=1
all_branches_collapsed=0
sort_key=46
sort_direction=-1
tree_view_always_by_pid=0
enable_mouse=1
delay=15
column_meters_0=AllCPUs2 Memory Swap
column_meter_modes_0=1 1 1
column_meters_1=Tasks LoadAverage Uptime NetworkIOMeter DiskIOMeter
column_meter_modes_1=2 2 2 2 2
color_scheme=0
# Pink color approximation via scheme 6 (Midnight Commander style)
header_margin=1
detailed_cpu_time=0
cpu_count_from_one=0
show_cpu_usage=1
show_cpu_frequency=1
show_cpu_temperature=1
degree_fahrenheit=0
update_process_names=0
account_guest_in_cpu_meter=0
color_scheme=6
EOF
info "htop config written"

# ─── 6. WAYBAR (vertical left sidebar) ────────────────────────────────────────
step "Writing waybar config"
cat > "$HOME/.config/waybar/config" <<'EOF'
{
    "layer": "top",
    "position": "left",
    "width": 48,
    "spacing": 4,
    "modules-left": ["niri/workspaces"],
    "modules-center": [],
    "modules-right": [
        "pulseaudio",
        "network",
        "cpu",
        "memory",
        "battery",
        "clock",
        "tray"
    ],
    "niri/workspaces": {
        "format": "{icon}",
        "format-icons": {
            "1": "1", "2": "2", "3": "3",
            "4": "4", "5": "5",
            "active": "",
            "default": ""
        }
    },
    "clock": {
        "format": "{:%H\n%M}",
        "tooltip-format": "{:%Y-%m-%d\n%A}"
    },
    "cpu": {
        "format": "\n{usage}%",
        "interval": 2
    },
    "memory": {
        "format": "\n{percentage}%",
        "interval": 2
    },
    "battery": {
        "format": "{icon}\n{capacity}%",
        "format-icons": ["", "", "", "", ""],
        "states": {
            "warning": 30,
            "critical": 15
        }
    },
    "network": {
        "format-wifi": "\n{signalStrength}%",
        "format-ethernet": "",
        "format-disconnected": "睊"
    },
    "pulseaudio": {
        "format": "{icon}\n{volume}%",
        "format-muted": "",
        "format-icons": { "default": ["", "", ""] }
    },
    "tray": {
        "spacing": 8
    }
}
EOF

cat > "$HOME/.config/waybar/style.css" <<EOF
* {
    font-family: "JetBrainsMono Nerd Font";
    font-size: 13px;
    border: none;
    border-radius: 0;
    min-height: 0;
}

window#waybar {
    background: rgba(26, 16, 37, 0.92);
    color: #fde8ff;
    border-right: 1px solid #3b2151;
}

#workspaces button {
    color: #6b4e7d;
    background: transparent;
    padding: 4px 8px;
    margin: 2px 0;
    border-radius: 8px;
    min-width: 32px;
}

#workspaces button.active {
    color: #1a1025;
    background: #f472b6;
}

#workspaces button:hover {
    background: #3b2151;
    color: #f472b6;
}

#clock, #cpu, #memory, #battery,
#network, #pulseaudio, #tray {
    color: #fde8ff;
    padding: 6px 8px;
    margin: 2px 4px;
    background: rgba(45, 27, 61, 0.6);
    border-radius: 8px;
    font-size: 11px;
}

#battery.warning { color: #f59e0b; }
#battery.critical { color: #f43f5e; }

#clock {
    color: #f472b6;
    font-weight: bold;
}
EOF
info "waybar config written"

# ─── 7. GTK THEME ─────────────────────────────────────────────────────────────
step "Setting GTK theme"
for gtk_ver in gtk-3.0 gtk-4.0; do
    cat > "$HOME/.config/$gtk_ver/settings.ini" <<EOF
[Settings]
gtk-application-prefer-dark-theme=true
gtk-theme-name=Adwaita-dark
gtk-icon-theme-name=Papirus-Dark
gtk-font-name=Noto Sans 10
gtk-cursor-theme-name=Adwaita
gtk-cursor-theme-size=24
EOF
done
info "GTK dark theme set"

# ─── 8. WOFI LAUNCHER ─────────────────────────────────────────────────────────
step "Writing wofi config"
mkdir -p "$HOME/.config/wofi"
cat > "$HOME/.config/wofi/config" <<EOF
width=400
height=500
location=center
show=drun
prompt=Search...
filter_rate=100
allow_markup=true
no_actions=true
halign=fill
orientation=vertical
content_halign=fill
insensitive=true
allow_images=true
image_size=24
gtk_dark=true
EOF

cat > "$HOME/.config/wofi/style.css" <<EOF
window {
    margin: 0;
    border: 1px solid #e879f9;
    background-color: rgba(26, 16, 37, 0.95);
    border-radius: 12px;
    font-family: "JetBrainsMono Nerd Font";
}
#input {
    margin: 8px;
    border: 1px solid #3b2151;
    background-color: #2d1b3d;
    color: #fde8ff;
    border-radius: 8px;
    padding: 8px 12px;
}
#inner-box {
    margin: 4px;
}
#outer-box {
    margin: 4px;
}
#entry {
    padding: 4px 8px;
    border-radius: 6px;
}
#entry:selected {
    background-color: #e879f9;
    color: #1a1025;
}
#entry:hover {
    background-color: #3b2151;
}
#text {
    color: #fde8ff;
    padding: 0 4px;
}
#text:selected {
    color: #1a1025;
}
EOF
info "wofi config written"

# ─── 9. MAKO NOTIFICATIONS ────────────────────────────────────────────────────
step "Writing mako config"
cat > "$HOME/.config/mako/config" <<EOF
background-color=#1a1025ee
text-color=#fde8ff
border-color=#f472b6
progress-color=over #e879f9aa
border-size=1
border-radius=10
default-timeout=5000
ignore-timeout=0
font=JetBrainsMono Nerd Font 11
width=320
height=110
margin=12
padding=12
icons=1
max-icon-size=32
layer=overlay
anchor=top-right

[urgency=high]
border-color=#f43f5e
default-timeout=0
EOF
info "mako config written"

# ─── 10. WALLPAPER ────────────────────────────────────────────────────────────
step "Setting wallpaper"
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"
mkdir -p "$WALLPAPER_DIR"

if command -v swww &>/dev/null; then
    # Look for any existing wallpaper, otherwise leave a note
    WP=$(find "$WALLPAPER_DIR" -type f \( -name "*.jpg" -o -name "*.png" -o -name "*.webp" \) | head -1)
    if [ -n "$WP" ]; then
        swww img "$WP" --transition-type wipe --transition-angle 30 --transition-duration 1
        info "Wallpaper set: $WP"
    else
        warn "No wallpaper found in $WALLPAPER_DIR"
        warn "Add a wallpaper there, then run: swww img ~/Pictures/Wallpapers/yourwall.png"
    fi
else
    warn "swww not installed — wallpaper not set"
fi

# ─── 11. SET fish AS DEFAULT SHELL ────────────────────────────────────────────
step "Setting fish as default shell"
FISH_PATH="$(command -v fish 2>/dev/null || echo '')"
if [ -n "$FISH_PATH" ]; then
    if ! grep -q "$FISH_PATH" /etc/shells; then
        echo "$FISH_PATH" | sudo tee -a /etc/shells
    fi
    if [ "$SHELL" != "$FISH_PATH" ]; then
        chsh -s "$FISH_PATH"
        info "Default shell changed to fish (re-login to take effect)"
    else
        info "fish is already the default shell"
    fi
else
    warn "fish not found in PATH"
fi

# ─── DONE ─────────────────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}  shura@ameko rice installed!${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "  Next steps:"
echo -e "  ${CYAN}1.${NC} Log out and start niri: add 'exec niri' to your display manager"
echo -e "     or run 'niri-session' from a TTY"
echo -e "  ${CYAN}2.${NC} Drop a wallpaper in ~/Pictures/Wallpapers/"
echo -e "  ${CYAN}3.${NC} Install lapifetch + shorkfetch from AUR for the fetch commands"
echo -e "  ${CYAN}4.${NC} Optional: install 'gay' (AUR: gay-git) for rainbow color output"
echo -e "     used in: lapifetch -nc | gay -t"
echo ""
echo -e "  Keybinds:"
echo -e "  ${PINK}Mod+Return${NC}   open kitty"
echo -e "  ${PINK}Mod+D${NC}        wofi launcher"
echo -e "  ${PINK}Mod+H/J/K/L${NC} focus windows"
echo -e "  ${PINK}Mod+Shift+Q${NC} close window"
echo -e "  ${PINK}Mod+F${NC}        maximize column"
echo -e "  ${PINK}Print${NC}        screenshot"
echo ""
