# Save clap-generated function so we can delegate non-dynamic cases.
functions[_rsp_clap]=$functions[_rsp]

_rsp() {
    case $words[2] in
        play|queue)
            if (( CURRENT > 2 )); then
                local cur="${words[$CURRENT]}"
                if [[ "$words[2]" == "play" && "$cur" == -* ]]; then
                    local -a flags
                    flags=('-i' '--now' '-n' '--next' '-a' '--album')
                    _describe 'flags' flags
                    return 0
                fi
                _rsp_complete_args
                return 0
            fi
            ;;
    esac
    _rsp_clap "$@"
}

_rsp_complete_args() {
    local -a args=("${(@)words[3,$CURRENT]}")
    local cur="${(j: :)args}"
    # No completion if this is a flag (handled above)
    [[ "$words[2]" == "play" && "$cur" == -* ]] && return 1
    local cur_clean="${cur//\\/}"
    local -a suggestions
    suggestions=("${(@f)"$(rsp db-complete "$cur" 2>/dev/null)"}")
    local -a filtered=()
    for s in "${suggestions[@]}"; do
        if [[ -n "$s" ]]; then
            filtered+=("$s")
        fi
    done
    suggestions=("${filtered[@]}")
    if (( ${#suggestions} )); then
        local noslash="${cur_clean//\/}"
        local n_slashes=$(( ${#cur_clean} - ${#noslash} ))
        local -a display=()
        local -a vals=()
        for s in "${suggestions[@]}"; do
            vals+=("$s")
            if [[ "$cur_clean" == */ ]]; then
                local stripped="$s"
                local i=0
                while (( i < n_slashes )); do
                    stripped="${stripped#*/}"
                    (( i++ ))
                done
                display+=("$stripped")
            else
                display+=("$s")
            fi
        done
        if (( ${#suggestions} > 1 )); then
            if [[ -n "$compstate[old_list]" ]]; then
                compstate[insert]=menu
            else
                compstate[insert]=
            fi
        fi
        if [[ ${vals[1]} == */ ]]; then
            compadd -U -S '' -M 'm:{a-z}={A-Z} l:|=*' -d display -- "${vals[@]}"
        else
            compadd -U -M 'm:{a-z}={A-Z} l:|=*' -d display -- "${vals[@]}"
        fi
    else
        compadd -U -S ''
    fi
}
