#!/usr/bin/env bash

# 1. Get active tmux sessions
sessions=$(tmux list-sessions -F "#S" 2>/dev/null)

# 2. Get directories from key work paths
dirs=$(find ~ ~/.config ~/Projects ~/dotfiles ~/personal \
    -mindepth 1 -maxdepth 4 \
    \( -name ".git" -o -name "node_modules" -o -name ".cache" -o -name "Library" \) -prune \
    -o -type d -print 2>/dev/null)

# 3. Dynamic Previewer (Tree view for folders, Window list for sessions)
preview_cmd='
if [ -d {} ]; then
    if command -v eza &>/dev/null; then
        eza --tree --level=2 --icons --color=always {}
    elif command -v tree &>/dev/null; then
        tree -C -L 2 {}
    else
        ls -la --color=always {}
    fi
else
    tmux list-windows -t {} 2>/dev/null
fi'

# 4. Kanagawa Wave Themed FZF Selector
selected=$(printf "%s\n%s" "$sessions" "$dirs" | grep -v '^$' | fzf \
    --layout=reverse \
    --border=rounded \
    --margin=1 \
    --padding=1 \
    --height=100% \
    --prompt="󱇗 " \
    --color="bg:#1F1F28,bg+:#223249,fg:#DCD7BA,fg+:#DCD7BA" \
    --color="hl:#2D4F67,hl+:#7E9CD8,prompt:#957FB8,pointer:#7E9CD8" \
    --color="info:#98BB6C,spinner:#957FB8,header:#7AA89F,border:#54546D" \
    --color="marker:#98BB6C" \
    --preview="$preview_cmd" \
    --preview-window="right:55%:border-left")

# Exit if fzf was cancelled
[[ -z "$selected" ]] && exit 0

# 5. Handle Session Creation / Switching
if [[ -d "$selected" ]]; then
    # Selection is a DIRECTORY -> Create session named after folder
    session_name=$(basename "$selected" | tr '.: ' '_')

    if ! tmux has-session -t "=$session_name" 2>/dev/null; then
        tmux new-session -d -s "$session_name" -c "$selected"
    fi
else
    # Selection is an EXISTING SESSION -> Connect directly
    session_name="$selected"
fi

# 6. Attach or Switch
if [[ -z "$TMUX" ]]; then
    exec tmux attach-session -t "$session_name"
else
    tmux switch-client -t "$session_name"
fi
