%\DocumentMetadata{}
\documentclass[USenglish,12pt,BCOR=10mm]{scrbook}

\usepackage[defaultfeatures={%
    Ligatures={TeX,Common,Discretionary}
  },nomath]{libertinus}
\usepackage{xcolor}
\usepackage{babel}
\usepackage{csquotes}
\usepackage{selnolig}
\usepackage{amsmath,amsthm}
\usepackage{mathtools}
\usepackage[colon=literal]{unicode-math} % TODO get rid of this since it messes up math italic correction
\usepackage{enumitem}
%\usepackage{graphicx}
\usepackage{tcolorbox}
\usepackage[style=ext-alphabetic]{biblatex}
\usepackage[intoc]{nomencl}
\usepackage{makeidx}
\usepackage{idxlayout}
\usepackage{hyperref}
\usepackage{bookmark}
\usepackage{hypdestopt}
\usepackage[capitalize,nameinlink]{cleveref}
%\usepackage{refcheck}

% ---------- fontspec
\setfontfamily\fausansoffice{FAUSansOffice}
\setmathfont[Scale=MatchLowercase]{New Computer Modern Math}
% restore traditional bb and cal glyphs
\let\mathbb\relax\DeclareMathAlphabet\mathbb{U}{msb}{m}{n}
\let\mathcal\relax\DeclareMathAlphabet\mathcal{OMS}{cmsy}{m}{n}

% ---------- xcolor
\definecolor{faunat}{RGB}{29,134,73}
\definecolor{linkcolor}{RGB}{134,29,38} % split complementary method

% ---------- koma-script
\KOMAoptions{%
  numbers=noenddot,
  toc=bib,
  toc=idx,
  %chapterprefix,
  headings=normal,
  overfullrule,
}
\addtokomafont{sectioning}{\fausansoffice\color{faunat}}
% keep layout when removing BCOR=10mm
%\areaset{426.8pt}{635.5pt}

% https://tex.stackexchange.com/questions/693750/modified-bourbaki-problem
\newcommand*{\trailingtext}[1]{%
   \unskip
   \hskip 1.5em plus 1fill
   \penalty100\null\nobreak \hskip 0pt plus 1fill
   \discretionary
   {}%
   {\vtop{%
  % shorter line (if you like)
  \leftskip 20pt
  #1\par
  % reset last line flush right
  \setbox0\lastbox
  \nointerlineskip
  \hbox to \hsize{\hfill\unhbox0\unskip\unskip}}%
    }%
   {\hbox{#1}}%
}

% ---------- csquotes
\SetBlockThreshold{0}
\SetCiteCommand{\textcite}
\renewcommand*{\mkcitation}[1]{\trailingtext{---\mkbibnamegiven{#1}}}
\renewcommand*{\mkccitation}[1]{\trailingtext{---#1}}
\renewcommand*{\mkblockquote}[4]{\small#1#2#4#3}

% ---------- selnolig
\nolig{tz}{t|z}
%\debugon

% ---------- amsmath
\numberwithin{equation}{chapter}
\DeclareMathOperator{\supp}{supp}
\DeclareMathOperator{\dom}{dom}
% extend amsmath's proof environment
\NewDocumentEnvironment{myproof}{Ob}{\IfNoValueTF{#1}{\begin{proof}}{\begin{proof}[\proofname\ of \Cref{#1}]}}{\end{proof}}

% ---------- mathtools
\DeclarePairedDelimiter\abs{\lvert}{\rvert}
\DeclarePairedDelimiter\norm{\lVert}{\rVert}
\DeclarePairedDelimiter\parens{\lparen}{\rparen}
\DeclarePairedDelimiter\bracks{\lbrack}{\rbrack}
\DeclarePairedDelimiter\braces{\lbrace}{\rbrace}
\DeclarePairedDelimiter\angles{\langle}{\rangle}
% TODO set macro with proper spacing
\DeclarePairedDelimiter\bra{\lvert}{\rangle}
\DeclarePairedDelimiter\ket{\langle}{\rvert}
\DeclarePairedDelimiterX\innerp[2]{\langle}{\rangle}{#1,#2}
\DeclarePairedDelimiterX\LorentzBF[2]{\lparen}{\rparen}{#1,#2}

% ---------- tcolorbox
\tcbuselibrary{skins,theorems,breakable} % add breakable library?
\tcbset{%
  beforeafter skip balanced=0.4\baselineskip,
  mythmstyle/.style={%
    enhanced,
    breakable,
    sharp corners=all,
    interior hidden,
    borderline west={3pt}{0pt}{#1},
    colframe=#1!25,
    coltitle=black,
    fonttitle=\bfseries,
    toptitle=0.6ex,
    left=3pt+0.6ex,
    bottom=0.6ex,
    top=0.6ex,
    theorem style=break,
    separator sign={\ \mdseries---},
    description delimiters none,
    terminator sign none,
  }
}
\newcounter{enunciation}
\newcommand*{\newenunciation}[2]{%
  \newtcbtheorem[%
    use counter=enunciation,%
    number within=chapter,%
    Crefname={\MakeTitlecase{#1}}{\MakeTitlecase{#1s}}%
    ]{#1}{\MakeTitlecase{#1}}{mythmstyle=#2}{#1}%
}
% theorem style
\newenunciation{corollary}{faunat}
\newenunciation{lemma}{faunat}
\newenunciation{proposition}{faunat}
\newenunciation{theorem}{faunat}
% definition style
\newenunciation{definition}{gray}
\newenunciation{example}{gray}
\newenunciation{remark}{gray}

%\theoremstyle{definition}
%\newtheorem{defin}
%\renewenvironment{definition}[2]{\begin{defin}[#1]\label{#2}}{\end{defin}}

% ---------- biblatex
\addbibresource[glob]{bib/*.bib}
\ExecuteBibliographyOptions{%
  refsegment=chapter,
  sorting=none,
  defernumbers,
  giveninits,
  backref,
}
\defbibheading{chapterbib}[\refname]{%
  \hypertarget{refbm:\arabic{refsegment}}{}
  \subsection*{#1\addspace{for}\addspace\Cref*{refsegment:\therefsection\therefsegment}}
  \bookmark[level=section,italic,dest=refbm:\arabic{refsegment}]{#1}
}
\newcommand*{\chapterbib}{\printbibliography[segment=\therefsegment,heading=chapterbib]}
\DefineBibliographyStrings{english}{%
  backrefpage={ref.\ on \pno}, %TODO use \addspace ?
  backrefpages={ref.\ on \ppno}
}
\DeclareFieldFormat[article]{volume}{\textbf{#1}}
\DeclareFieldFormat[article]{title}{\textit{#1}}
%\DeclareFieldFormat{bracketswithperiod}{\mkbibbrackets{#1\addperiod}}
\renewcommand{\mkbibnamefamily}[1]{\textsc{#1}}
\renewcommand{\mkbibnamegiven}[1]{\textsc{#1}}
\renewcommand{\mkbibnameprefix}[1]{\textsc{#1}}
\renewcommand{\mkbibnamesuffix}[1]{\textsc{#1}}
\renewcommand*{\finentrypunct}{}
% https://tex.stackexchange.com/questions/574292
\renewcommand*{\subtitlepunct}{\addcolon\space}
\DeclarePunctuationPairs{colon}{*}

% ---------- nomencl
\makenomenclature
\renewcommand*{\nomname}{List of Symbols}
\def\pagedeclaration#1{, \hyperlink{page.#1}{page\nobreakspace#1}}

% ---------- makeidx
\makeindex

% ---------- hyperref
\hypersetup{%
  colorlinks,
  allcolors=linkcolor,
  linktoc=all,
  bookmarksnumbered,
  bookmarksopen,
  bookmarksopenlevel=2,
  hypertexnames=false,
  pdfpagelabels,
  pdftitle={Title},
  pdfauthor={Justin Gassner},
  pdfsubject={Subject},
  pdfkeywords={Keyword1, Keyword2},
}

% ---------- more pdf stuff
\pdfvariable minorversion 6
\pdfvariable suppressoptionalinfo \numexpr
        0
    +   1   % PTEX.FullBanner
    +   2   % PTEX.FileName
    +   4   % PTEX.PageNumber
    +   8   % PTEX.InfoDict
    +  16   % Creator
    +  32   % CreationDate
    +  64   % ModDate
    + 128   % Producer
    + 256   % Trapped
    + 512   % ID
\relax

% Make @ behave as per catcode 13 (active). The TeXbook, p. 155.
\mathcode`@="8000
{\catcode`\@=\active\gdef@{\mkern1mu}}

% ---------- misc
%\renewcommand\phi\varphi
%\renewcommand\epsilon\varepsilon
% number systems
\newcommand*{\NN}{\mathbb{N}}
\newcommand*{\ZZ}{\mathbb{Z}}
\newcommand*{\QQ}{\mathbb{Q}}
\newcommand*{\RR}{\mathbb{R}}
\newcommand*{\CC}{\mathbb{C}}

% don't use Fraktur for the real and imaginary parts
% TODO Why does this not work?
\renewcommand{\Re}{\operatorname{Re}}
\renewcommand{\Im}{\operatorname{Im}}
\newcommand{\Imag}{\operatorname{Im}}

% emphasis for defined terms
\newcommand*{\defn}[1]{\textbf{\textit{#1}}}

\newcommand*{\ts}[1]{\textnormal{#1}} % textual subscript

% monomials
\newcommand{\Mon}{\operatorname{Mon}}

% Infinitesimal Weyl algebra
\newcommand{\WeylAlg}{\mathcal{W}}
\newcommand{\weylannihilator}{A}
\newcommand{\weylcreator}{\weylannihilator^\dagger}

% Fourier transformation
% ----------------------
\newcommand*{\ft}[1]{\hat{#1}}
\newcommand*{\FT}[1]{\mathcal{F}\parens*{#1}}
\newcommand*{\iFT}[1]{\mathcal{F}^{-1}\parens*{#1}}

% Hilbert spaces
% --------------
\newcommand*{\hilb}[1]{\mathcal{#1}}
\newcommand*{\Hilb}[1]{\mathcal{#1}}
% algebraic dircet sum
\newcommand{\AlgebraicDirectSum}[1]{\sideset{}{_{\!\ts{alg}}}\bigoplus#1}
% Hilbert space direct sum
%\newcommand{\AlgebraicDirectSum}[1]{\sideset{}{_{\!\ts{Hilb}}}\bigoplus #1}

% Test functions and distributions
% --------------
\newcommand*{\testfun}[1]{\mathcal{D}(#1)}
\newcommand*{\distrib}[1]{\mathcal{D}'(#1)}
\newcommand*{\schwartz}[1]{\mathcal{S}(#1)}
\newcommand*{\realschwartz}[1]{\mathcal{S}_{\RR}(#1)}
\newcommand*{\tempdistrib}[1]{\mathcal{S}'(#1)}

% Fock spaces
% -----------
\newcommand*{\FullFock}[1]{\mathcal{F}(#1)}
\newcommand*{\FullFockFinite}[1]{\mathcal{F}^{@0}(#1)}
\newcommand*{\BosonFock}[1]{\mathcal{F}_{\!\ts{s}}(#1)}
\newcommand*{\BosonFockFinite}[1]{\mathcal{F}^{@0}_{\!\ts{s}}(#1)}
\newcommand*{\FermionFock}[1]{\mathcal{F}_{\!\ts{s}}(#1)}
\newcommand*{\FermionFockFinite}[1]{\mathcal{F}^{@0}_{\!\ts{s}}(#1)}

% Operators
% ---------
\newcommand*{\Domain}[1]{\mathcal{D}(#1)}
\newcommand*{\Range}[1]{\mathcal{R}(#1)}
\newcommand*{\Graph}[1]{\mathcal{G}(#1)}

% Quadratic forms
% ---------
\newcommand*{\QF}[1]{QF(#1)}
\newcommand{\QFequal}{\overset{\text{\scriptsize QF}}{=}}

% Standard Subspaces
% ------------------
% real scalarproduct
\DeclarePairedDelimiterXPP\realscalarp[2]{\Re}{\langle}{\rangle}{}{#1,#2}
\DeclarePairedDelimiterXPP\symplecticp[2]{\Im}{\langle}{\rangle}{}{#1,#2}
% symplectic complement
\newcommand*{\sympcomp}{'}
% real orthogonal complement
\newcommand*{\realorthcomp}{^\bot}

% normal ordering (aka Wick ordering)
\newcommand*{\normord}[1]{{\vcentcolon\mathrel{#1}\vcentcolon}}

\newcommand\restr[2]{{% we make the whole thing an ordinary symbol
  \left.\kern-\nulldelimiterspace % automatically resize the bar with \right
  #1 % the function
  \vphantom{\big|} % pretend it's a little taller at normal size
  \right| {#2} % this is the delimiter
  }}

\newcommand{\defequal}{\overset{\text{\scriptsize def}}{=}}
