# ── zinit ─────────────────────────────────────────────────────────────────────
if [[ ! -f $HOME/.local/share/zinit/zinit.git/zinit.zsh ]]; then
    print -P "%F{33} %F{220}Installing zinit…%f"
    command mkdir -p "$HOME/.local/share/zinit" && command chmod g-rwX "$HOME/.local/share/zinit"
    command git clone https://github.com/zdharma-continuum/zinit "$HOME/.local/share/zinit/zinit.git"
fi
source "$HOME/.local/share/zinit/zinit.git/zinit.zsh"
autoload -Uz _zinit
(( ${+_comps} )) && _comps[zinit]=_zinit

# ── Plugins ───────────────────────────────────────────────────────────────────
zinit light zsh-users/zsh-autosuggestions
zinit light zsh-users/zsh-syntax-highlighting
zinit light zsh-users/zsh-completions

# ── PATH ──────────────────────────────────────────────────────────────────────
export PATH="/usr/local/bin:$HOME/.local/bin:/usr/bin:$HOME/.atuin/bin:$PATH"

# ── Historique ────────────────────────────────────────────────────────────────
HISTSIZE=50000
HISTFILESIZE=100000
HISTFILE=~/.zsh_history
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_FIND_NO_DUPS
setopt SHARE_HISTORY
setopt APPEND_HISTORY
setopt EXTENDED_HISTORY

# ── Options zsh ───────────────────────────────────────────────────────────────
setopt AUTO_CD            # cd en tapant juste le nom du dossier
setopt CORRECT            # correction de typos
setopt GLOB_DOTS          # inclure fichiers caches dans les globs
setopt NO_BEEP            # silence
setopt INTERACTIVE_COMMENTS # commentaires en mode interactif

# ── Completion ────────────────────────────────────────────────────────────────
autoload -Uz compinit && compinit
zstyle ':completion:*' menu select
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
zstyle ':completion:*' group-name ''
zstyle ':completion:*:descriptions' format '%F{#c9a0ff}── %d ──%f'

# ── Couleurs grep ─────────────────────────────────────────────────────────────
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

# ── eza (remplace ls) ────────────────────────────────────────────────────────
alias ls='eza --icons --color=always --group-directories-first'
alias ll='eza -l --icons --git --group-directories-first'
alias la='eza -la --icons --git --group-directories-first'
alias lt='eza --tree --icons --level=3'
export LS_COLORS="$(bash ~/.local/share/violet-chaton/violet-chaton-ls-colors.sh)"

# ── bat (remplace cat) ───────────────────────────────────────────────────────
alias bat='batcat'
alias cat='batcat --paging=never'
export MANPAGER="sh -c 'col -bx | batcat -l man -p'"

# ── fd (remplace find) ───────────────────────────────────────────────────────
alias fd='fdfind'

# ── Outils modernes ──────────────────────────────────────────────────────────
alias lg='lazygit'
alias rg='rg --color=always'
alias disk='dust'                         # analyse disque (remplace ncdu)
alias tl='tldr'                           # man pages simplifiees (man reste intact)
alias pipes='pipes.sh'
alias top='btop'
fuck() { eval "$(thefuck --alias 2>/dev/null)"; fuck "$@"; }

# ── fzf ──────────────────────────────────────────────────────────────────────
[ -f /usr/share/doc/fzf/examples/key-bindings.zsh ] && source /usr/share/doc/fzf/examples/key-bindings.zsh
[ -f /usr/share/doc/fzf/examples/completion.zsh ]   && source /usr/share/doc/fzf/examples/completion.zsh

# Raccourcis fzf
bindkey -r '^T'
bindkey -r '\ec'
bindkey '^G' fzf-file-widget
bindkey '^F' fzf-cd-widget
export FZF_DEFAULT_COMMAND='fdfind --type f --hidden --follow --exclude .git --exclude .cache --search-path $HOME'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
export FZF_ALT_C_COMMAND='fdfind --type d --hidden --follow --exclude .git --exclude .cache --search-path $HOME'
export FZF_DEFAULT_OPTS="
  --height 40% --layout=reverse --border rounded --info=hidden
  --preview 'batcat --color=always --style=plain --line-range=:80 {}'
  --preview-window 'right:50%:wrap'
  --color=bg+:#5a3875,bg:#261537,spinner:#ff4da6,hl:#a4b4ff
  --color=fg:#f0eaf8,header:#ff4da6,info:#c9a0ff,pointer:#ff4da6
  --color=marker:#9adba8,fg+:#f0eaf8,prompt:#c9a0ff,hl+:#a4b4ff"

# ── zoxide (remplace cd) ────────────────────────────────────────────────────
eval "$(zoxide init zsh --cmd cd)"

# ── direnv (charge .envrc automatiquement) ───────────────────────────────────
command -v direnv &>/dev/null && eval "$(direnv hook zsh)"

# ── fnm (Node.js version manager — lazy load) ───────────────────────────────
if [ -d "$HOME/.local/share/fnm" ]; then
    export PATH="$HOME/.local/share/fnm:$PATH"
    eval "$(fnm env --use-on-cd --shell zsh)"
fi

# ── Fastfetch ────────────────────────────────────────────────────────────────
alias fetch='fastfetch --config ~/.config/fastfetch/config.jsonc --raw <(chafa --size 44x22 --symbols vhalf --color-space rgb "$HOME/.config/fastfetch/violet-chaton-logo.png") --logo-width 52'
[[ -z "$TMUX" && -z "$INSIDE_EMACS" && -z "$VSCODE_INJECTION" ]] && fetch

# ── zsh-autosuggestions ──────────────────────────────────────────────────────
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=#716686"
ZSH_AUTOSUGGEST_STRATEGY=(history completion)
ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=20
bindkey '^ ' autosuggest-accept

# ── zsh-syntax-highlighting (couleurs violet-chaton v2) ──────────────────────
ZSH_HIGHLIGHT_STYLES[command]='fg=#a4b4ff'
ZSH_HIGHLIGHT_STYLES[builtin]='fg=#ff4da6'
ZSH_HIGHLIGHT_STYLES[alias]='fg=#c9a0ff'
ZSH_HIGHLIGHT_STYLES[function]='fg=#a4b4ff'
ZSH_HIGHLIGHT_STYLES[string]='fg=#9adba8'
ZSH_HIGHLIGHT_STYLES[path]='fg=#f0eaf8,underline'
ZSH_HIGHLIGHT_STYLES[unknown-token]='fg=#f25c7a,bold,standout'
ZSH_HIGHLIGHT_STYLES[reserved-word]='fg=#ff4da6'
ZSH_HIGHLIGHT_STYLES[single-hyphen-option]='fg=#e8c87a'
ZSH_HIGHLIGHT_STYLES[double-hyphen-option]='fg=#e8c87a'
ZSH_HIGHLIGHT_STYLES[back-quoted-argument]='fg=#c9a0ff'
ZSH_HIGHLIGHT_STYLES[dollar-quoted-argument]='fg=#9adba8'
ZSH_HIGHLIGHT_STYLES[assign]='fg=#f0eaf8'
ZSH_HIGHLIGHT_STYLES[redirection]='fg=#ff4da6,bold'
ZSH_HIGHLIGHT_STYLES[commandseparator]='fg=#ff4da6'

# ── Vi-mode — cursor shape adaptatif ────────────────────────────────────────
bindkey -v
export KEYTIMEOUT=1

# Beam en insert, block en normal
zle-keymap-select() {
    case $KEYMAP in
        vicmd)      echo -ne '\e[1 q' ;;  # block clignotant
        viins|main) echo -ne '\e[5 q' ;;  # beam clignotant
    esac
}
zle -N zle-keymap-select

# Reset beam au demarrage de chaque prompt
zle-line-init() { echo -ne '\e[5 q' }
zle -N zle-line-init

# Garder les keybindings essentiels en mode insert
bindkey '^A' beginning-of-line
bindkey '^E' end-of-line
bindkey '^K' kill-line
bindkey '^U' backward-kill-line
bindkey '^W' backward-kill-word
bindkey '^Y' yank
bindkey '^R' history-incremental-search-backward
bindkey '^P' up-line-or-history
bindkey '^N' down-line-or-history
bindkey '^?' backward-delete-char
bindkey '^H' backward-delete-char
ZSH_HIGHLIGHT_STYLES[comment]='fg=#716686,italic'
ZSH_HIGHLIGHT_STYLES[globbing]='fg=#e8c87a'
ZSH_HIGHLIGHT_STYLES[history-expansion]='fg=#e8c87a'

# ── fzf pimped — git log picker, process killer ─────────────────────────────

# Git log browser — Ctrl+L en mode normal
fzf-git-log() {
    git log --oneline --color=always --decorate --graph 2>/dev/null |
        fzf --ansi --no-sort --reverse --preview \
            'git show --color=always $(echo {} | grep -oP "[a-f0-9]{7,}" | head -1)' \
            --preview-window='right:60%:wrap' \
            --bind='enter:execute(echo {} | grep -oP "[a-f0-9]{7,}" | head -1 | tr -d "\n" | xclip -selection clipboard)+abort'
}
alias glog='fzf-git-log'

# Process killer — fzf powered
fkill() {
    local pid
    pid=$(procs --color=always 2>/dev/null || ps aux) |
        fzf --ansi --header="Select process to kill" \
            --preview-window='hidden' |
        awk '{print $1}'
    [ -n "$pid" ] && kill -9 "$pid" && echo "Killed $pid"
}

# ── Shell functions — violet-chaton toolkit ──────────────────────────────────

# mkcd — creer un dossier et y aller
mkcd() { mkdir -p "$1" && cd "$1" }

# Project switcher — fzf dans ~/Dev
proj() {
    local dir
    dir=$(find ~/Dev -maxdepth 3 -name ".git" -type d 2>/dev/null | sed 's|/.git$||' |
        fzf --preview 'eza -la --icons --color=always --group-directories-first {}' \
            --preview-window='right:50%')
    [ -n "$dir" ] && cd "$dir"
}

# Palette preview — affiche violet-chaton v2 dans le terminal
colors() {
    echo ""
    echo -e "  \033[1mviolet-chaton v2\033[0m"
    echo ""
    echo -e "  \033[38;2;255;77;166m████\033[0m magenta   #ff4da6"
    echo -e "  \033[38;2;201;160;255m████\033[0m lilac     #c9a0ff"
    echo -e "  \033[38;2;154;219;168m████\033[0m mitsuri   #9adba8"
    echo -e "  \033[38;2;164;180;255m████\033[0m lavande   #a4b4ff"
    echo -e "  \033[38;2;232;200;122m████\033[0m champagne #e8c87a"
    echo ""
    echo -e "  \033[38;2;242;92;122m████\033[0m danger    #f25c7a"
    echo -e "  \033[38;2;232;200;122m████\033[0m warning   #e8c87a"
    echo -e "  \033[38;2;154;219;168m████\033[0m success   #9adba8"
    echo -e "  \033[38;2;164;180;255m████\033[0m info      #a4b4ff"
    echo ""
    echo -e "  \033[38;2;240;234;248m████\033[0m text      #f0eaf8"
    echo -e "  \033[38;2;196;184;212m████\033[0m subtext1  #c4b8d4"
    echo -e "  \033[38;2;154;143;173m████\033[0m subtext0  #9a8fad"
    echo -e "  \033[38;2;113;102;134m████\033[0m muted     #716686"
    echo ""
    echo -e "  Gradient: \033[38;2;255;77;166m██\033[38;2;226;118;212m██\033[38;2;201;160;255m██\033[38;2;182;168;255m██\033[38;2;164;180;255m██\033[38;2;159;200;212m██\033[38;2;154;219;168m██\033[38;2;130;232;160m██\033[0m"
    echo ""
}

# Yazi — wrapper qui cd dans le dernier dossier visite
y() {
    local tmp="$(mktemp -t "yazi-cwd.XXXXXX")"
    yazi "$@" --cwd-file="$tmp"
    if cwd="$(cat -- "$tmp")" && [ -n "$cwd" ] && [ "$cwd" != "$PWD" ]; then
        cd "$cwd"
    fi
    rm -f "$tmp"
}

# Weather — meteo rapide
weather() { curl -s "wttr.in/${1:-Paris}?format=3" }

# Cheatsheet — raccourcis violet-chaton
hotkeys() {
    echo ""
    echo -e "  \033[38;2;255;77;166m\033[1m── kitty ──\033[0m"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+\\\033[0m   split vertical"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+-\033[0m    split horizontal"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+Z\033[0m    zoom (stack toggle)"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+←→↑↓\033[0m naviguer splits"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+1-5\033[0m  layouts (tall/fat/grid/h/v)"
    echo -e "  \033[38;2;201;160;255mCtrl+Shift+T\033[0m    nouvel onglet"
    echo ""
    echo -e "  \033[38;2;255;77;166m\033[1m── zsh ──\033[0m"
    echo -e "  \033[38;2;154;219;168mEsc\033[0m             vi normal mode (hjkl, w, b)"
    echo -e "  \033[38;2;154;219;168mi\033[0m               retour insert"
    echo -e "  \033[38;2;154;219;168mCtrl+G\033[0m          fzf fichier"
    echo -e "  \033[38;2;154;219;168mCtrl+F\033[0m          fzf dossier"
    echo -e "  \033[38;2;154;219;168mCtrl+Space\033[0m      accepter suggestion"
    echo ""
    echo -e "  \033[38;2;255;77;166m\033[1m── commandes ──\033[0m"
    echo -e "  \033[38;2;164;180;255mproj\033[0m            project switcher fzf"
    echo -e "  \033[38;2;164;180;255mglog\033[0m            git log fzf"
    echo -e "  \033[38;2;164;180;255mfkill\033[0m           process killer fzf"
    echo -e "  \033[38;2;164;180;255my\033[0m               yazi (cd au dossier visite)"
    echo -e "  \033[38;2;164;180;255mcolors\033[0m          palette violet-chaton v2"
    echo -e "  \033[38;2;164;180;255mweather [ville]\033[0m meteo rapide"
    echo -e "  \033[38;2;164;180;255mhotkeys\033[0m         cette aide"
    echo ""
}

# ── atuin (remplace Ctrl+R) ──────────────────────────────────────────────────
[[ -f ~/.atuin/bin/env ]] && source ~/.atuin/bin/env
command -v atuin &>/dev/null && eval "$(atuin init zsh --disable-up-arrow)"

# ── starship ─────────────────────────────────────────────────────────────────
command -v starship &>/dev/null && eval "$(starship init zsh)"
