# ╔══════════════════════════════════════════════════════════════════╗
# ║  arch-dev :: zshrc                                              ║
# ║  Kanagawa Wave · 256-color · mobile-aware · AUR-powered         ║
# ╚══════════════════════════════════════════════════════════════════╝

# ── Environment ───────────────────────────────────────────────────────────────
export EDITOR=nvim
export VISUAL=nvim
export PAGER="less"
export MANPAGER="nvim +Man!"
export TERM=xterm-256color
export PATH="$HOME/.local/bin:$HOME/perl5/bin:/usr/local/bin:$PATH"
export DOCKER_BUILDKIT=1

# NO truecolor — Termius renders hex RGB as purple
unset COLORTERM

# ── History ───────────────────────────────────────────────────────────────────
HISTSIZE=50000
SAVEHIST=50000
HISTFILE="${HISTFILE:-$HOME/.zsh_history}"
setopt share_history hist_ignore_dups hist_ignore_space
setopt hist_reduce_blanks extended_history

# ── ZSH Options ───────────────────────────────────────────────────────────────
setopt auto_cd correct interactive_comments no_beep

# ── Completion ────────────────────────────────────────────────────────────────
autoload -Uz compinit && compinit
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
zstyle ':completion:*:descriptions' format '%F{yellow}── %d ──%f'

# ── Plugins ───────────────────────────────────────────────────────────────────
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
source /usr/share/zsh/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh
source /usr/share/zsh/plugins/zsh-history-substring-search/zsh-history-substring-search.zsh

bindkey '^[[A' history-substring-search-up
bindkey '^[[B' history-substring-search-down

# ── zsh-syntax-highlighting: 256-color only (no hex/truecolor) ────────────────
# Kanagawa Wave approximations in 256-color palette
# 110 = steel blue (crystalBlue)   106 = olive green (springGreen)
# 139 = medium purple (oniViolet)  173 = tan (boatYellow)
# 167 = indian red (peachRed)       66 = cadet blue (waveAqua)
ZSH_HIGHLIGHT_STYLES[default]='none'
ZSH_HIGHLIGHT_STYLES[unknown-token]='fg=167,bold'
ZSH_HIGHLIGHT_STYLES[reserved-word]='fg=139'
ZSH_HIGHLIGHT_STYLES[command]='fg=110'
ZSH_HIGHLIGHT_STYLES[builtin]='fg=110'
ZSH_HIGHLIGHT_STYLES[function]='fg=110'
ZSH_HIGHLIGHT_STYLES[alias]='fg=106'
ZSH_HIGHLIGHT_STYLES[path]='fg=66'
ZSH_HIGHLIGHT_STYLES[single-quoted-argument]='fg=173'
ZSH_HIGHLIGHT_STYLES[double-quoted-argument]='fg=173'
ZSH_HIGHLIGHT_STYLES[comment]='fg=242'
ZSH_HIGHLIGHT_STYLES[globbing]='fg=139'

# ── Autosuggestion style ──────────────────────────────────────────────────────
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=242'
ZSH_AUTOSUGGEST_STRATEGY=(history completion)
ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=20

# ── Smart Tools ───────────────────────────────────────────────────────────────
eval "$(zoxide init zsh)"
source <(fzf --zsh)

# FZF — 256-color theme
export FZF_DEFAULT_OPTS="
  --color=bg+:236,bg:234,spinner:139,hl:173
  --color=fg:250,header:242,info:110,pointer:167
  --color=marker:139,fg+:250,prompt:110,hl+:167
  --border=rounded --prompt='❯ ' --pointer='▶' --marker='✔'
"
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'

# ── Mobile Detection ──────────────────────────────────────────────────────────
if [[ "${MOBILE:-0}" == "1" ]]; then
    export STARSHIP_CONFIG="$HOME/.config/starship-mobile.toml"
    alias mux='screen -RD'
    alias muxls='screen -ls'
    if [[ -z "$STY" && -z "$TMUX" ]]; then
        screen -RD arch-dev 2>/dev/null || screen -S arch-dev
    fi
else
    export STARSHIP_CONFIG="$HOME/.config/starship.toml"
    alias mux='tmux new-session -A -s main'
    alias muxls='tmux ls'
fi

# ── Prompt ────────────────────────────────────────────────────────────────────
eval "$(starship init zsh)"

# ── Aliases ───────────────────────────────────────────────────────────────────
source ~/.aliases

# ── arch-dev snapshot system ──────────────────────────────────────────────────
# Git-backed rollback for /home/dev. State lives in ~/.arch-dev-state/
# (separate git dir so it doesn't conflict with project git repos).
export ARCH_DEV_GITDIR="$HOME/.arch-dev-state"

_archdev_git() {
    git --git-dir="$ARCH_DEV_GITDIR" --work-tree="$HOME" "$@"
}

# Take a named snapshot
snapshot() {
    if [[ -z "$1" ]]; then
        echo "usage: snapshot <name> [message]"
        echo "  e.g. snapshot node-working 'NodeJS environment with nvm + pnpm'"
        return 1
    fi
    local name="$1"
    local msg="${2:-snapshot: $name}"
    _archdev_git add -A
    _archdev_git commit -q -m "$msg" || { echo "nothing to snapshot"; return 1; }
    _archdev_git tag -f "$name"
    echo "✓ snapshot '$name' saved"
}

# List snapshots
snapshots() {
    echo "── arch-dev snapshots ──"
    _archdev_git tag -l --format='  %(refname:short)  %(taggerdate:short)  %(subject)'
    echo ""
    echo "── recent commits ──"
    _archdev_git log --oneline -10
}

# Roll back to a snapshot
rollback() {
    if [[ -z "$1" ]]; then
        echo "usage: rollback <name>"
        snapshots
        return 1
    fi
    local name="$1"
    if ! _archdev_git rev-parse "$name" >/dev/null 2>&1; then
        echo "✗ snapshot '$name' not found"
        snapshots
        return 1
    fi
    echo "⚠ rolling back to '$name' will discard uncommitted changes"
    echo -n "  proceed? [y/N] "
    read -r reply
    [[ "$reply" =~ ^[Yy]$ ]] || { echo "cancelled"; return 1; }

    # Auto-snapshot current state before rollback
    _archdev_git add -A 2>/dev/null
    _archdev_git commit -q -m "auto: pre-rollback $(date +%Y%m%d-%H%M%S)" 2>/dev/null || true

    _archdev_git reset --hard "$name"
    echo "✓ rolled back to '$name'"
}

# What's changed since last snapshot
diff-state() {
    _archdev_git status --short
    echo ""
    _archdev_git diff --stat HEAD
}

# Delete a snapshot
unsnapshot() {
    if [[ -z "$1" ]]; then
        echo "usage: unsnapshot <name>"
        return 1
    fi
    _archdev_git tag -d "$1" && echo "✓ snapshot '$1' removed"
}

# Show what's in a snapshot
show-snapshot() {
    if [[ -z "$1" ]]; then
        echo "usage: show-snapshot <name>"
        return 1
    fi
    _archdev_git show --stat "$1"
}

# ── Key Bindings ──────────────────────────────────────────────────────────────
bindkey -e
bindkey '^[[1;5C' forward-word
bindkey '^[[1;5D' backward-word
