zmodload zsh/datetime 2>/dev/null
typeset -gF __ZSH_START_TIME=$EPOCHREALTIME

export LANG="en_US.UTF-8"
export EDITOR="nvim"
export VISUAL="$EDITOR"
export HOMEBREW_NO_ENV_HINTS=1
export BAT_THEME="Catppuccin Mocha"
export MANPAGER='sh -c "col -bx | bat -l man -p"'
export PIP_REQUIRE_VIRTUALENV=true
export UV_PROJECT_ENVIRONMENT=".venv"
export ZSH_COMPDUMP="$HOME/.cache/zsh/.zcompdump"

mkdir -p "$HOME/.cache/zsh"

typeset -U path fpath
fpath=("$HOME/.cache/zsh" $fpath)

for dir in \
  "$HOME/.local/bin" \
  "/opt/homebrew/opt/binutils/bin" \
  "/usr/local/go/bin" \
  "/usr/local/share/dotnet" \
  "/Applications/Ghostty.app/Contents/MacOS"
do
  [[ -d "$dir" ]] && path=("$dir" $path)
done
export PATH

if (( $+commands[uv] )); then
  alias uv='noglob uv'
  alias uva='uv add'
  alias uvp='uv pip'
  alias uvpy='uv python'
  alias uvr='uv run'
  alias uvs='uv sync'
  alias uvv='uv venv'
  [[ -f "$HOME/.cache/zsh/_uv" ]] || uv generate-shell-completion zsh >| "$HOME/.cache/zsh/_uv"
  [[ -f "$HOME/.cache/zsh/_uvx" ]] || uvx --generate-shell-completion zsh >| "$HOME/.cache/zsh/_uvx"
fi

if (( $+commands[fnm] )); then
  [[ -f "$HOME/.cache/zsh/_fnm" ]] || fnm completions --shell=zsh >| "$HOME/.cache/zsh/_fnm"
fi

if (( $+commands[oh-my-posh] )) && [[ -r "$HOME/.config/oh-my-posh/config.json" ]]; then
  eval "$(oh-my-posh init zsh --config "$HOME/.config/oh-my-posh/config.json")"
fi

autoload -Uz add-zsh-hook
typeset -gi __LOADTIME_PRINTED=${__LOADTIME_PRINTED:-0}

# --- zsh history ---
HISTFILE="$HOME/.zsh_history"
HISTSIZE=100000
SAVEHIST=100000

setopt APPEND_HISTORY
setopt EXTENDED_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_FIND_NO_DUPS
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_REDUCE_BLANKS
setopt HIST_SAVE_NO_DUPS
setopt HIST_VERIFY
setopt SHARE_HISTORY

autoload -Uz up-line-or-beginning-search
autoload -Uz down-line-or-beginning-search

zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search

bindkey "^[[A" up-line-or-beginning-search
bindkey "^[[B" down-line-or-beginning-search

setopt AUTO_CD
setopt AUTO_LIST
setopt LIST_AMBIGUOUS
setopt EXTENDED_GLOB
unsetopt BEEP

zstyle ':completion:*' menu select
zstyle ':completion:*' group-name ''
zstyle ':completion:*' verbose yes
zstyle ':completion:*:descriptions' format '%F{blue}%B-- %d --%b%f'
zstyle ':completion:*' list-prompt '%F{yellow}%S-- more matches --%s%f'
zstyle ':completion:*' select-prompt '%F{cyan}%S%p%s%f'

# --- completions ---
autoload -Uz compinit
if [[ -s "$ZSH_COMPDUMP" ]]; then
  compinit -C -d "$ZSH_COMPDUMP"
else
  compinit -d "$ZSH_COMPDUMP"
fi

export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
export FZF_ALT_C_COMMAND='fd --type d --hidden --follow --exclude .git'
export FZF_DEFAULT_OPTS=$'\n  --height 40% --layout=reverse --border\n  --color=bg+:#313244,bg:#1e1e2e,spinner:#f5e0dc,hl:#f38ba8\n  --color=fg:#cdd6f4,header:#f38ba8,info:#cba6f7,pointer:#f5e0dc\n  --color=marker:#f5e0dc,fg+:#cdd6f4,prompt:#cba6f7,hl+:#f38ba8\n  --bind ctrl-/:toggle-preview\n  --preview-window right:50%:hidden'
export FZF_CTRL_R_OPTS=$'\n  --preview "echo {}" --preview-window down:3:hidden:wrap\n  --bind ctrl-/:toggle-preview\n  --bind ctrl-y:execute-silent(echo -n {2..} | pbcopy)+abort\n  --color header:italic\n  --header "Press CTRL-Y to copy command into clipboard"'

if [[ -r "$HOME/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh" ]]; then
  source "$HOME/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh"
fi

if (( $+commands[thefuck] )); then
  [[ -s "$HOME/.cache/zsh/thefuck.alias.zsh" ]] || thefuck --alias >| "$HOME/.cache/zsh/thefuck.alias.zsh"
  source "$HOME/.cache/zsh/thefuck.alias.zsh"
fi

command_not_found_handler() {
  local fix

  if (( $+commands[thefuck] )); then
    if fix=$(thefuck --yes "$@" 2>/dev/null); then
      [[ -n "$fix" ]] || return 127
      print -u2 -P "%F{yellow}did you mean:%f %B$fix%b"
      return 127
    fi

    print -u2 -P "%F{yellow}thefuck:%f no rule for %B$1%b"
    return 127
  fi

  print -u2 -P "%F{red}command not found:%f %B$1%b"
  return 127
}

alias ls='eza --icons --group-directories-first'
alias la='eza -a --icons --group-directories-first'
alias ll='eza -lah --icons --group-directories-first --git'
alias lt='eza --tree --icons --level=2'
alias llt='eza -lah --tree --icons --level=2 --git'
alias top='btop'
alias vim='nvim'
alias pip='noglob pip3'
alias lg='lazygit'

ff() {
  local file
  file=$(fd --type f --hidden --follow --exclude .git "$@" | \
    fzf --preview 'bat --style=numbers --color=always --line-range :200 {}') || return
  print -r -- "$file"
}

vf() {
  local file
  file=$(ff "$@") || return
  "$EDITOR" "$file"
}

cdf() {
  local dir
  dir=$(fd --type d --hidden --follow --exclude .git "$@" | fzf) || return
  cd "$dir" || return
}

fbr() {
  local target
  target=$(fd --hidden --follow --exclude .git "$@" | \
    fzf --preview 'if [[ -d {} ]]; then eza -lah --icons --group-directories-first {}; else bat --style=numbers --color=always --line-range :200 {}; fi') || return
  print -r -- "$target"
}

typeset -gi __FAST_INIT_DONE=0

# Initialize zoxide before first prompt so `z` is recognized by syntax highlighting.
if (( $+commands[zoxide] )); then
  eval "$(zoxide init zsh)"
fi

_fast_shell_init() {
  (( __FAST_INIT_DONE )) && return
  __FAST_INIT_DONE=1
  add-zsh-hook -d preexec _fast_shell_init

  if (( $+commands[fzf] )); then
    eval "$(fzf --zsh)"
  fi

  if (( $+commands[fnm] )); then
    eval "$(fnm env --use-on-cd --shell zsh)"
  fi

  YSU_MESSAGE_POSITION="after"
  if [[ -r "$HOME/.local/share/zinit/plugins/MichaelAquilina---zsh-you-should-use/you-should-use.plugin.zsh" ]]; then
    source "$HOME/.local/share/zinit/plugins/MichaelAquilina---zsh-you-should-use/you-should-use.plugin.zsh"
  fi

  if (( $+functions[_zsh_highlight_bind_widgets] )); then
    _zsh_highlight_bind_widgets
  fi

}

add-zsh-hook preexec _fast_shell_init

if [[ -r "$HOME/.local/share/zinit/plugins/zsh-users---zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" ]]; then
  source "$HOME/.local/share/zinit/plugins/zsh-users---zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
fi

if (( ! __LOADTIME_PRINTED )); then
  __LOADTIME_PRINTED=1
  typeset -F __elapsed_ms
  typeset __elapsed_label __tone
  __elapsed_ms=$(( (EPOCHREALTIME - __ZSH_START_TIME) * 1000 ))
  __elapsed_label=$(printf '%.0f' "$__elapsed_ms")

  if (( __elapsed_ms < 120 )); then
    __tone='green'
  elif (( __elapsed_ms < 250 )); then
    __tone='yellow'
  else
    __tone='red'
  fi

  print -P "%F{244}boot%f %B%F{39}zsh%f%b %F{244}in%f %B%F{$__tone}${__elapsed_label}ms%f%b"
  unset __elapsed_ms __elapsed_label __tone
fi
