%%% Preamble %%%

\usepackage{fontspec} % Font selection (LuaLaTeX)
\usepackage{lastpage} % Reference total page count (\pageref{LastPage})

\usepackage{listings} % Source code listings
\lstset{
    basicstyle=\small\ttfamily, % Font size and type
    breaklines=true,            % Line wrapping
    tabsize=2,                  % Tab size
    frame=single,               % Frame around listing
    literate={---}{{-{}-{}-}}3 {--}{{-{}-}}2 % Correct display of double and triple dashes
}

% Fonts
\defaultfontfeatures{Ligatures=TeX}
\setmainfont{Times New Roman} % Main font
\setmonofont{FreeMono}        % Monospace font for code listings

% Math formulas
\usepackage{mathtools,unicode-math} % mathtools supersedes amsmath
\setmathfont{XITS Math}             % Math font: https://github.com/aliftype/xits
\numberwithin{equation}{section}    % Equation numbering: section.number

% English language support
\usepackage{polyglossia}
\setdefaultlanguage{english}

% Paragraphs and lists
\usepackage{float}       % Extended float control
\usepackage{multirow}    % Complex tables

% Image paths
\usepackage{graphicx} % Insert graphics
\graphicspath{{images/}}
\usepackage{tikz} % Programmatic diagrams
\usetikzlibrary{arrows.meta, positioning, shapes.geometric, fit, calc}

% Microtypography: character protrusion and font expansion (full support in LuaLaTeX)
\usepackage{microtype}

% Reset figure and table counters per section (chngcntr no longer needed in LaTeX 2018+)
\counterwithin{figure}{section}
\counterwithin{table}{section}

% Hyperlinks (loaded late per best practice)
\usepackage{hyperref}
\hypersetup{
    colorlinks, urlcolor={black}, % All links black and clickable
    linkcolor={black}, citecolor={black}, filecolor={black},
    pdfauthor={Your Name},
    pdftitle={Your Thesis Title}
}
\usepackage{bookmark} % Faster PDF bookmarks (replaces hyperref's bookmark module)

% Bibliography and caption label formatting with dot separator
\makeatletter
\renewcommand*{\@biblabel}[1]{\hfill#1.}
\renewcommand*\l@section{\@dottedtocline{1}{1em}{1em}}
\renewcommand{\thefigure}{\thesection.\arabic{figure}} % Figure format: section.number
\renewcommand{\thetable}{\thesection.\arabic{table}}   % Table format: section.number
\def\redeflsection{\def\l@section{\@dottedtocline{1}{0em}{10em}}}
\makeatother

\usepackage{setspace}
\onehalfspacing % 1.5 line spacing (replaces manual \baselinestretch)
\parindent 1.27cm % Paragraph indent

\emergencystretch=1em  % Allow slight stretch to avoid overfull boxes
\hyphenpenalty=1000 % Hyphenation frequency
\clubpenalty=10000  % Prevent page break after first line of paragraph (orphan)
\widowpenalty=10000 % Prevent page break after last line of paragraph (widow)

% Page margins
\usepackage{geometry}
\geometry{left=2.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm}

% Lists
\usepackage{enumitem}
\setlist[enumerate,itemize]{leftmargin=12.7mm} % List indentation
\setlist{nolistsep}                            % No spacing between list items
\renewcommand{\labelitemi}{\textbullet}         % List marker: bullet
\renewcommand{\labelenumi}{\arabic{enumi})}     % First-level enumerate: 1) 2) 3)
\renewcommand{\labelenumii}{\arabic{enumii})}  % Second-level enumerate: 1) 2) 3)

% Table of contents
\usepackage{tocloft}
\renewcommand{\cfttoctitlefont}{\hspace{0.38\textwidth}\MakeTextUppercase} % CONTENTS title
\renewcommand{\cftsecfont}{\hspace{0pt}}            % Section names not bold in TOC
\renewcommand\cftsecleader{\cftdotfill{\cftdotsep}} % Dots for sections in TOC
\renewcommand\cftsecpagefont{\mdseries}             % Page numbers not bold
\setcounter{tocdepth}{3}                            % TOC depth: up to subsubsection

% List of figures
\renewcommand{\cftloftitlefont}{\hspace{0.17\textwidth}\MakeTextUppercase}
\renewcommand{\cftfigfont}{Figure }

% List of tables
\renewcommand{\cftlottitlefont}{\hspace{0.2\textwidth}\MakeTextUppercase}
\renewcommand{\cfttabfont}{Table }

% Page numbering: centered at bottom
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\cfoot{\textrm{\thepage}}
\fancyheadoffset{0mm}
\fancyfootoffset{0mm}
\setlength{\headheight}{17pt}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancypagestyle{plain}{
    \fancyhf{}
    \cfoot{\textrm{\thepage}}
}

% Figure and table caption formatting
\usepackage{caption}
\DeclareCaptionLabelSeparator{defffis}{. } % Separator (period)
\captionsetup[figure]{justification=centering, labelsep=defffis, format=plain} % Figure caption centered
\captionsetup[table]{justification=raggedright, labelsep=defffis, format=plain, singlelinecheck=false} % Table caption left-aligned

% Custom commands for inserting figures
\newcommand{\addimg}[4]{ % Add a single figure (floating)
    \begin{figure}
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \caption{#3} \label{#4}
    \end{figure}
}
\newcommand{\addimghere}[4]{ % Add a figure at exact position
    \begin{figure}[H]
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \caption{#3} \label{#4}
    \end{figure}
}
\newcommand{\addtwoimghere}[6]{ % Insert two figures side by side
    \begin{figure}[H]
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \hfill
        \includegraphics[width=#4\linewidth]{#3}
        \caption{#5} \label{#6}
    \end{figure}
}

% Uppercase section titles in TOC
\usepackage{textcase}
\makeatletter
\let\oldcontentsline\contentsline
\def\contentsline#1#2{
    \expandafter\ifx\csname l@#1\endcsname\l@section
        \expandafter\@firstoftwo
    \else
        \expandafter\@secondoftwo
    \fi
    {\oldcontentsline{#1}{\MakeTextUppercase{#2}}}
    {\oldcontentsline{#1}{#2}}
}
\makeatother

% Heading formatting
\usepackage[compact,explicit]{titlesec}
\titleformat{\section}{}{}{12.5mm}{\centering{\thesection\quad\MakeTextUppercase{#1}}\vspace{1.5em}}
\titleformat{\subsection}[block]{\vspace{1em}}{}{12.5mm}{\thesubsection\quad#1\vspace{1em}}
\titleformat{\subsubsection}[block]{\vspace{1em}\normalsize}{}{12.5mm}{\thesubsubsection\quad#1\vspace{1em}}
\titleformat{\paragraph}[block]{\normalsize}{}{12.5mm}{\MakeTextUppercase{#1}}

% Unnumbered sections (introduction, conclusion, etc.)
\newcommand{\anonsection}[1]{
    \phantomsection % Correct hyperlink target in TOC
    \paragraph{\centerline{{#1}}\vspace{1em}}
    \addcontentsline{toc}{section}{#1}
}

% Abstract section (not included in TOC)
\newcommand{\annotation}[1]{
    \paragraph{\centerline{{#1}}\vspace{1em}}
}

% List of figures section
\newcommand{\lof}{
    \phantomsection
    \listoffigures
    \addcontentsline{toc}{section}{\listfigurename}
}

% List of tables section
\newcommand{\lot}{
    \phantomsection
    \listoftables
    \addcontentsline{toc}{section}{\listtablename}
}

% Appendix sections
\newcommand{\appsection}[1]{
    \phantomsection
    \paragraph{\centerline{{#1}}}
    \addcontentsline{toc}{section}{#1}
}
