A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
I can see from the query plan, you are running the RTM version of SQL 2017. You need to update to a current patch level.
Do you really need "SELECT DISTINCT" in your sub queries? This is very costly in your query.