% Language
\usepackage[american]{babel}
% \usepackage[T1]{fontenc} % Silbentrennung bei Sonderzeichen
% \usepackage[utf8]{inputenc}

% Layout
\usepackage[left=3.5cm,right=2.5cm,top=2.5cm,bottom=2.5cm]{geometry} % Typical margin
\usepackage{titling}
\usepackage{setspace} % Line stretch

% Bibliography
\usepackage[backend=biber,urldate=iso,date=iso,seconds=true]{biblatex}
\bibliography{references}
\usepackage[nottoc,notlof,notlot]{tocbibind} % Include bibliography in ToC, nottoc disables the "Contents" entry for the ToC itself

% Figures
\usepackage{graphicx} % Required for inserting images
\usepackage[font=small,labelfont=bf,labelsep=endash,margin=1cm,hypcap]{caption}
\usepackage[margin=1cm,hypcap]{subcaption} % Mehrere Figuren in einer
% \usepackage{float} % [H] floating/positioning von Figuren
\usepackage{floatbytocbasic} % float for komascript
% \usepackage[bottom,multiple]{footmisc} % Bottom not below footnote
\usepackage{flafter}
\usepackage{placeins} % \FloatBarrier to flush floats

% Math
\usepackage{amsmath,amsthm} % Don't load amssymb with concmath-otf
\usepackage{mathtools} % Extension of amsmath
% \usepackage{upgreek} % For non italic greek (vectors/matrices)
\usepackage{unicode-math}
\usepackage{lualatex-math}

% Tables
\usepackage{booktabs}
% \usepackage{tabularx}
% \usepackage{tablefootnote}
% \usepackage{makecell}
% \usepackage{color,colortbl}

% Code
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{shadings, backgrounds}
\usepackage[minted]{tcolorbox}
\tcbuselibrary{skins} % breakable

% Typography
% \usepackage{fontspec}
\usepackage{concmath-otf}
\usepackage[babel,final,protrusion=true,expansion=true,tracking=false,kerning=false,spacing=false]{microtype}
\setmonofont{MonoLisa Alt}[Scale=MatchLowercase]

% Pagestyle
\KOMAoptions{%
  chapterprefix,
  appendixprefix,
  headsepline,
  % footsepline,
  % cleardoublepage=current,
  method=right, % start chapters on the right
  cleardoublepage=plain, % linenumbers on interleaf pages
  footnotes=multiple, % TODO: Doesn't work, maybe because of hyperref?
}

% Various stuff
\usepackage[page]{appendix} % [toc]
\usepackage{lipsum}
\usepackage[inkscapelatex=false]{svg} % Don't touch fonts
% \usepackage{comment}
\usepackage{pdfpages}
\usepackage{luatodonotes}
\usepackage{siunitx}
\sisetup{detect-all}
\usepackage[l2tabu,orthodox]{nag}
% \usepackage{etoolbox} % For \ifstrequal
\usepackage[autostyle]{csquotes} % Correct quotation marks with \textquote{}
\usepackage{silence} % Silence warnings
% \usepackage[intoc]{nomencl} % Nomenclature
\usepackage[luatex,hidelinks]{hyperref} % Load late
\usepackage[acronym,automake,nonumberlist,nogroupskip,toc]{glossaries} % Load after hyperref, toc
\usepackage{xurl} % xurl does url-line-breaks in contrast to url

% Multi-file
\usepackage{subfiles} % Load last

% Settings
\setstretch{1.25}
\clubpenalty=10000
\widowpenalty=10000
\displaywidowpenalty=10000

% Allow more (and larger) floats on text pages
\renewcommand{\topfraction}{0.9}  % use up to ..% of space on top
\renewcommand{\bottomfraction}{0.8}  % use up to ..% of space on bottom
\setcounter{topnumber}{4} % place up to .. on top
\setcounter{bottomnumber}{1} % place up to .. on bottom
\setcounter{totalnumber}{4} % place up to .. total
\renewcommand{\textfraction}{0.07} % allow down to ..% of text
\renewcommand{\floatpagefraction}{0.7} % fill at least ..% of float pages (must be less than \topfraction)

\mathtoolsset{showonlyrefs}
\usepackage{xpatch}
\makeatletter
\xpretocmd\HyRef@autoref{\noeqref{#2}}{}{} % showonlyrefs mit \autoref
\makeatother

\makeatletter\newcommand{\tcb@cnt@codeblockautorefname}{Listing}\makeatother

% Silence some warning spam
% \WarningFilter{biblatex}{The following entry could not be found} % Those are duplicated at the actual \cite usage
% \WarningFilter{latexfont}{Font shape `T1/zi4/m/it' undefined}
% \WarningFilter{latexfont}{Font shape `TS1/zi4/m/it' undefined}
% \WarningFilter{latexfont}{Some font shapes were not available}

% Macros
\let\oldurl\url%
\let\url\undefined%
\newcommand{\url}[2][\PackageError{Thesis}{URL requires 2 arguments: \url[date]{address}, e.g.\ \url[07/27/2024]{https://github.com}}{}]{\oldurl{#2} (visited on #1)}

\let\oldref\ref%
\let\ref\undefined%
\newcommand{\ref}[1]{\PackageError{Thesis}{REF:\ Use \autoref{label} instead}{}}

\let\oldcite\cite%
\let\cite\undefined%
\newcommand{\cite}[1]{\PackageError{Thesis}{CITE:\ Use \autocite{ref} instead}{}}

\newcommand{\sansbf}[1]{{\usekomafont{disposition}#1}}

\renewcommand{\author}[1]{\gdef\theauthor{#1}}
\renewcommand{\title}[1]{\gdef\thetitle{#1}}
\newcommand{\germantitle}[1]{\gdef\thegermantitle{#1}}
\newcommand{\thesistype}[1]{\gdef\thethesistype{#1}}
\newcommand{\thesisid}[1]{\gdef\thethesisid{#1}}
\newcommand{\thesiscite}[1]{\gdef\thethesiscite{#1}}
\newcommand{\birthday}[1]{\gdef\thebirthday{#1}}
\newcommand{\birthplace}[1]{\gdef\thebirthplace{#1}}
\newcommand{\thesisstart}[1]{\gdef\thethesisstart{#1}}
\newcommand{\thesisend}[1]{\gdef\thethesisend{#1}}
\newcommand{\advisors}[1]{\gdef\theadvisors{#1}}
\newcommand{\dean}[1]{\gdef\thedean{#1}}

% Hyphenation
\hyphenation{Web-Assembly}

% Default start and end for each subfile (the main.tex is also a subfile!)
\AtBeginDocument{%
  % Capitalize all the section names (has to be placed after \begin{document})
  \renewcommand{\chapterautorefname}{Chapter}
  \renewcommand{\sectionautorefname}{Section}
  \renewcommand{\subsectionautorefname}{Section}
  \renewcommand{\subsubsectionautorefname}{Section}
  \renewcommand{\paragraphautorefname}{Paragraph}
  \renewcommand{\figureautorefname}{Figure}
  \renewcommand{\tableautorefname}{Table}
  \renewcommand{\partautorefname}{Part}
  \renewcommand{\theoremautorefname}{Theorem}
  \renewcommand{\equationautorefname}{Equation}
  \renewcommand{\appendixautorefname}{Appendix}
  \newcommand{\algorithmautorefname}{Algorithm}

  \hypersetup{
    pdfauthor={\@author},
    pdftitle={\@title},
    % pdfkeywords={\@thesiskeywords},
    pdfproducer={LaTeX},
    pdfcreator={LuaLaTeX}
  }

  % Starting pages
  \pagestyle{empty}
  \pagenumbering{gobble}
  \input{titlepage}
  \cleardoublepage%

  \frontmatter%
  \pagestyle{plain}
  % \pagenumbering{Roman}
  % \tableofcontents{\thispagestyle{plain}}
  \tableofcontents%
  \cleardoublepage%

  \setacronymstyle{short-long}
  \printglossary[type=\acronymtype]
  \cleardoublepage%
  \printglossary%

  \mainmatter%
  \pagestyle{headings}
  % \pagenumbering{arabic}
}
\AtEndDocument{
  \backmatter%
  \pagestyle{plain}

  \let\url\undefined%
  \let\url\oldurl%
  \let\cite\undefined%
  \let\cite\oldcite%

  \printbibliography[heading=bibintoc]
  % \printbibliography%
  \cleardoublepage%

  \phantomsection%
  \addcontentsline{toc}{chapter}{Lists}

  \listoffigures%
  \addcontentsline{toc}{section}{List of Figures}
  \cleardoublepage%

  \listofalgorithms%
  \addcontentsline{toc}{section}{List of Algorithms}
  \cleardoublepage%

  \tcblistof[\chapter*]{listings}{List of Listings}
  \addcontentsline{toc}{section}{List of Listings}
  \cleardoublepage%

  \listoftables%
  \addcontentsline{toc}{section}{List of Tables}
  \cleardoublepage%

  \phantomsection%
  \addcontentsline{toc}{chapter}{Statutory Declaration}
  \includepdf[pages=-]{declaration.pdf}
}

% Colors
\definecolor{tuCorporateGreen}{HTML}{639A00}
\definecolor{tuCorporateOrange}{HTML}{CA7406}
\colorlet{titlebg}{tuCorporateGreen} % Color mixing
\colorlet{titlecolor}{gray!5!white}
\colorlet{codebg}{white}
\colorlet{languagebg}{tuCorporateGreen!30!white}
\colorlet{linenumberbg}{gray!20!white}

% Math Environments
% \newtheorem*{theorem}{Theorem}
% \newtheorem*{definition}{Definition}

% Code Environment

% This box surrounds the language name (e.g., C#)
\newtcbox{\languagehighlight}{
  nobeforeafter,
  boxrule=0pt,
  colback=languagebg,
  arc=2pt,
  boxsep=0pt,
  left=3pt,
  right=3pt,
  top=3pt,
  bottom=3pt,
  tcbox raise base
}

% This command is used in the codeblock box to quickly insert the languagehighlight box
\newcommand{\codelang}[1]{\languagehighlight{\texttt{#1}}}

% The main box for listings
\newtcolorbox[auto counter,list inside=listings,number within=chapter]{codeblock}[3][]
{%
  enhanced,
  % float,
  % floatplacement=bth,
  colbacktitle=titlebg,
  coltitle=titlecolor,
  colframe=titlebg,
  interior style={%
      top color=codebg,
      bottom color=codebg
    },
  boxrule=0.5pt, % Border width
  arc=2pt, % Rounded corners
  width=\linewidth,
  fonttitle=\normalsize,
  adjusted title=\textbf{\texttt{\thetcbcounter}\hspace{0.75em}\texttt{#2}},
  list entry=\thetcbcounter\quad\texttt{#2}, % List of listings
  list text={\hspace*{1ex}#2}, % Chapter - Caption spacing in list of listings
  after title={% Display used language
      \hfill\setlength{\fboxsep}{2pt}
      \codelang{#3}
    },
  overlay={% Line number background
      \begin{tcbclipinterior}\fill[linenumberbg] (frame.south west)
        rectangle ([xshift=5mm]frame.north west);
      \end{tcbclipinterior}
    },
  top=1mm,
  bottom=1mm,
  right=0mm,
  left=5mm,
  #1 % Extra args, e.g. a label
}

% Options for the listing itself, syntax highlighted using minted/pygmentize
\setminted{
  linenos,
  autogobble,
  breaklines=true,
  breaksymbol=,
  breakindent=4mm,
  breakbefore=.,
  breakbeforesymbolpre=,
  breakbeforesymbolpost=,
  baselinestretch=0.8,
  % escapeinside=||,
  framesep=5mm,
  numbersep=7pt,
  fontsize=\small,
}

% A box surrounding inline code-type text
\newtcbox{\codehighlight}{nobeforeafter,boxrule=.5pt,colback=black!5,colframe=black!35,
  arc=2pt,boxsep=0pt,left=2pt,right=2pt,top=2pt,bottom=2pt, tcbox raise base}

% Quickly place inline codehighlight boxes
\newcommand{\code}[1]{\codehighlight{\texttt{\small{#1}}}}

% A box surrounding figures
\tcolorboxenvironment{figure}{
  enhanced,
  float=htb,
  arc=2pt,
  boxrule=0.5pt,
  colframe=black,
  colback=white,
  before skip=\intextsep,
  after skip=\intextsep,
}
