%% =============================================================
%% bookaspro.cls
%% Book layout and image composition for print-ready "books as [a] pro"
%% books (trim size + bleed, running heads, styled headings,
%% unified image macros, bleed proofing overlays).
%%
%% Copyright (C) 2026 Stefano Dalpez
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either
%% version 1.3c of this license or (at your option) any later
%% version. The latest version of this license is in
%%   http://www.latex-project.org/lppl.txt
%% and version 1.3c or later is part of all distributions of
%% LaTeX version 2005/12/01 or later.
%%
%% This work has the LPPL maintenance status `maintained'.
%%
%% The Current Maintainer of this work is Stefano Dalpez.
%%
%% This work consists of the files bookaspro.cls,
%% bookaspro-doc.tex, example_bookaspro.tex and README.md.
%% =============================================================
\NeedsTeXFormat{LaTeX2e}[2020-10-01]
\ProvidesClass{bookaspro}[2026/11/29 v2.0.1 Trim-and-bleed book class and image composition]

% -------------------------------------------------------------
% ENGINE CHECK
% The class relies on fontspec (OpenType fonts) and therefore
% requires LuaLaTeX or XeLaTeX.
% -------------------------------------------------------------
\RequirePackage{iftex}
\ifLuaTeX\else
  \ifXeTeX\else
    \ClassError{bookaspro}{LuaLaTeX or XeLaTeX is required}%
      {The bookaspro class uses fontspec and OpenType fonts.\MessageBreak
       Compile your document with lualatex or xelatex.}%
  \fi
\fi

% -------------------------------------------------------------
% CLASS OPTIONS
%   nofont      do not load fontspec / do not set the main font
%   notitles    do not apply the titlesec heading styles
%   nohyperref  do not load hyperref+bookmark (load them yourself
%               AFTER bookaspro if you need custom options)
%   showframe   pass showframe to geometry (layout proofing)
%   bleedmarks  enable \showBleedMargin with default values
% Any other option (11pt, 12pt, oneside, draft, a4paper, ...) is
% passed through to the underlying book class.
% -------------------------------------------------------------
\newif\ifbap@font     \bap@fonttrue
\newif\ifbap@titles   \bap@titlestrue
\newif\ifbap@hyperref \bap@hyperreftrue
\newif\ifbap@frame    \bap@framefalse
\newif\ifbap@marks    \bap@marksfalse
% Sensible book layout defaults, passed FIRST so that explicit
% user options (appended later through \DeclareOption*) override
% them cleanly.
\PassOptionsToClass{10pt,twoside,openright}{book}
\DeclareOption{nofont}{\bap@fontfalse}
\DeclareOption{notitles}{\bap@titlesfalse}
\DeclareOption{nohyperref}{\bap@hyperreffalse}
\DeclareOption{showframe}{\bap@frametrue}
\DeclareOption{bleedmarks}{\bap@markstrue}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{book}}
\ProcessOptions\relax
\LoadClass{book}

% -------------------------------------------------------------
% REQUIRED PACKAGES
% -------------------------------------------------------------
% Scalable Computer Modern math fonts: avoids size-substitution
% warnings when non-standard sizes (e.g. 16pt) are used.
\RequirePackage{fix-cm}
\RequirePackage{keyval}
\RequirePackage{geometry}
\ifbap@font
  \RequirePackage{fontspec}
  % File names (.otf) are used on purpose: immune to system font
  % cache issues on any machine.
  \setmainfont{texgyrepagella-regular.otf}[
    BoldFont       = texgyrepagella-bold.otf ,
    ItalicFont     = texgyrepagella-italic.otf ,
    BoldItalicFont = texgyrepagella-bolditalic.otf
  ]
\fi
\RequirePackage{microtype}
\RequirePackage{graphicx}
\RequirePackage{xcolor}
\RequirePackage{textcomp}
\RequirePackage{csquotes}
\RequirePackage{float}
\RequirePackage{wrapfig}
\RequirePackage{rotating}
\RequirePackage{caption}
\RequirePackage{lscape}
\RequirePackage{longtable}
\RequirePackage{placeins}
\RequirePackage{fancyhdr}
\RequirePackage{emptypage}
\RequirePackage{setspace}
\ifbap@titles
  \RequirePackage{titlesec}
\fi
\RequirePackage{tikz}
% NOTE: pdflscape is deliberately NOT loaded: it conflicts with
% LuaLaTeX. Use the lscape environment instead.

% -------------------------------------------------------------
% PAGE LAYOUT CONFIGURATION (\bookasprosetup)
% -------------------------------------------------------------
% Print model (thread-sewn perfect binding, single pages, 1:1 PDF,
% NO crop marks in the final file):
%   * trim size ............ final book size after trimming
%   * bleed ................ extra image area on every side
%   * PDF page = trim size + 2 x bleed
% Typographic margins are measured FROM THE TRIM LINE; the bleed
% amount is added automatically to every geometry value.
% Defaults reproduce a 170 x 240 mm book with 3 mm bleed:
%   PDF page 176 x 246 mm, text block 138 x 200 mm,
%   >= 5 mm safety distance on the three outer sides and
%   >= 15 mm on the binding side (measured from the trim line).
% Setup keys: values are stored as dimension/number text and
% applied by \bap@applygeometry / \bap@applytypography.
\define@key{bap}{trimwidth}{\def\bap@trimwidth{#1}}
\define@key{bap}{trimheight}{\def\bap@trimheight{#1}}
\define@key{bap}{bleed}{\def\bap@bleed{#1}}
\define@key{bap}{top}{\def\bap@top{#1}}
\define@key{bap}{bottom}{\def\bap@bottom{#1}}
\define@key{bap}{inner}{\def\bap@inner{#1}}
\define@key{bap}{outer}{\def\bap@outer{#1}}
\define@key{bap}{bindingoffset}{\def\bap@bindingoffset{#1}}
\define@key{bap}{headheight}{\def\bap@headheight{#1}}
\define@key{bap}{headsep}{\def\bap@headsep{#1}}
\define@key{bap}{footskip}{\def\bap@footskip{#1}}
\define@key{bap}{stretch}{\def\bap@stretch{#1}}
\define@key{bap}{parindent}{\def\bap@parindent{#1}}
\define@key{bap}{parskip}{\def\bap@parskip{#1}}
\define@key{bap}{emergencystretch}{\def\bap@emergencystretch{#1}}
\define@key{bap}{imagepath}{\graphicspath{{#1}}}
% Caption controls (global, dependencies-free: they do not touch
% the page geometry, so \bookasprosetup re-applying the geometry
% is harmless). Values are stored as text and passed to the
% caption package / to the tikz overlay nodes.
\define@key{bap}{captionfont}{\def\bap@gcaptionfont{#1}}
\define@key{bap}{captionskip}{\def\bap@gcaptionskip{#1}}
\define@key{bap}{captionmargin}{\def\bap@gcaptionmargin{#1}}
\define@key{bap}{bleedcaptionskip}{\def\bap@gbleedcaptionskip{#1}}
% Computed geometry values (registers, safe for \geometry).
\newlength{\bap@gpw}
\newlength{\bap@gph}
\newlength{\bap@gt}
\newlength{\bap@gb}
\newlength{\bap@gi}
\newlength{\bap@go}
\newcommand{\bap@applygeometry}{%
  % PDF page = trim size + bleed on both sides
  \setlength{\bap@gpw}{\dimexpr\bap@trimwidth+\bap@bleed+\bap@bleed\relax}%
  \setlength{\bap@gph}{\dimexpr\bap@trimheight+\bap@bleed+\bap@bleed\relax}%
  % margins from the trim line + bleed
  \setlength{\bap@gt}{\dimexpr\bap@top+\bap@bleed\relax}%
  \setlength{\bap@gb}{\dimexpr\bap@bottom+\bap@bleed\relax}%
  \setlength{\bap@gi}{\dimexpr\bap@inner+\bap@bleed\relax}%
  \setlength{\bap@go}{\dimexpr\bap@outer+\bap@bleed\relax}%
  \def\bap@geomopts{
    paperwidth=\bap@gpw,
    paperheight=\bap@gph,
    top=\bap@gt,
    bottom=\bap@gb,
    inner=\bap@gi,
    outer=\bap@go,
    bindingoffset=\bap@bindingoffset,
    headheight=\bap@headheight,
    headsep=\bap@headsep,
    footskip=\bap@footskip
  }%
  \ifbap@frame
    \g@addto@macro\bap@geomopts{,showframe}%
  \fi
  \expandafter\geometry\expandafter{\bap@geomopts}%
}
\newcommand{\bap@applytypography}{%
  \setstretch{\bap@stretch}%
  \setlength{\parindent}{\bap@parindent}%
  \setlength{\parskip}{\bap@parskip}%
  \emergencystretch=\bap@emergencystretch\relax
}
% \bookasprosetup{key=value,...}: change any layout/typography
% parameter and re-apply the geometry immediately. Because it
% re-applies the geometry through the geometry package, it may
% only be used in the preamble.
\newcommand{\bookasprosetup}[1]{%
  \setkeys{bap}{#1}%
  \bap@applygeometry
  \bap@applytypography
}

% -------------------------------------------------------------
% PAGE STRUCTURE AND FLOAT FLOW
% -------------------------------------------------------------
% Ragged bottom: with many figures this is the modern editorial
% choice; it removes pages with exaggerated vertical gaps
% ("Underfull \vbox" warnings).
\raggedbottom
% Large float queues: image-heavy books need them.
\maxdeadcycles=500
\extrafloats{500}
% Float flow tuning: fewer deferred floats, fewer float-only pages.
\renewcommand{\topfraction}{0.9}
\renewcommand{\bottomfraction}{0.85}
\renewcommand{\textfraction}{0.08}
\renewcommand{\floatpagefraction}{0.8}
\setcounter{topnumber}{2}
\setcounter{bottomnumber}{1}
\setcounter{totalnumber}{3}
% In-text separation: wrapped figures (and any [h] float) must sit
% flush with the surrounding text (no \intextsep gap above). This
% keeps the caption of a wrapped figure inside the text block and
% removes the white strip above the figure. Top/bottom floats are
% spaced with \textfloatsep, which is left unchanged.
\setlength{\intextsep}{0pt}
% Widows and orphans: never leave isolated lines at page breaks,
% never split a hyphenated word across two pages.
\clubpenalty=10000
\widowpenalty=10000
\brokenpenalty=10000

% -------------------------------------------------------------
% HEADING STYLES (titlesec)
% -------------------------------------------------------------
\ifbap@titles
  % Centered rule below the chapter title, in a dedicated macro:
  % the after-code argument of \titleformat accepts neither a
  % direct \par nor \shortstack reliably at non-standard sizes.
  \newcommand{\bap@chapterrule}{%
    \par\nobreak\vskip 16pt\null\hfill\rule{50pt}{0.8pt}\hfill\null\par\nobreak
  }
  \titleformat{\chapter}[display]
    {\normalfont\centering}
    {\fontsize{16}{19}\selectfont\bfseries\textls[200]{\MakeUppercase{\chaptertitlename}\ \thechapter}}
    {20pt}
    {\fontsize{22}{28}\selectfont\bfseries}
    [\bap@chapterrule]
  \titlespacing*{\chapter}{0pt}{56pt}{30pt}
  \titleformat{\section}
    {\normalfont\fontsize{16}{22}\bfseries\selectfont}
    {\fontsize{15}{19}\selectfont\bfseries\thesection}
    {1em}
    {}
  \titlespacing*{\section}{0pt}{18pt}{8pt}
  \titleformat{\subsection}
    {\normalfont\normalsize\bfseries\itshape\selectfont}
    {\fontsize{10.5}{12}\selectfont\bfseries\itshape\thesubsection}
    {1em}
    {}
  \titlespacing*{\subsection}{0pt}{14pt}{6pt}
  \titleformat{\subsubsection}
    {\normalfont\normalsize\itshape}
    {}
    {0em}
    {}
  \titlespacing*{\subsubsection}{0pt}{10pt}{4pt}
\fi

% -------------------------------------------------------------
% RUNNING HEADS AND FOLIOS (fancyhdr)
% No running heads, no head rule: centered folio at the bottom,
% on both regular and chapter-opening (plain) pages.
% -------------------------------------------------------------
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[C]{\small\thepage}
\renewcommand{\headrulewidth}{0pt}
\fancypagestyle{plain}{%
  \fancyhf{}
  \fancyfoot[C]{\small\thepage}
  \renewcommand{\headrulewidth}{0pt}%
}

% -------------------------------------------------------------
% CAPTIONS
% Label separator: a period followed by a wide space (\quad).
% Multi-line captions are justified; single-line captions stay
% centered (singlelinecheck, the caption package default).
% Figure numbers run continuously through the whole book
% (no chapter prefix).
% -------------------------------------------------------------
\DeclareCaptionLabelSeparator{broadsep}{.\quad}
\captionsetup{font=normalsize,labelfont=bf,labelsep=broadsep,
  margin=0pt,skip=6pt,justification=justified,singlelinecheck=true}
\counterwithout{figure}{chapter}

% -------------------------------------------------------------
% STRUCTURAL COMMANDS
% -------------------------------------------------------------
% \unnumberedchapter{title}: unnumbered chapter, correctly wired
% for hyperref/bookmark: fresh page, phantom anchor, ToC entry
% and running-head marks.
\newcommand{\unnumberedchapter}[1]{%
  \cleardoublepage
  \phantomsection
  \chapter*{#1}%
  \addcontentsline{toc}{chapter}{#1}%
  \markboth{#1}{#1}%
}
% \chapterornament: closing ornament (three centered asterisks).
% Use it as the last line of a chapter.
% \WFclear ends any still-open wrapfig wrapping (a short paragraph
% following a wrapped figure leaves its \parshape active), so the
% asterisks are centered in the full text block, not the wrapped
% column.
\newcommand{\chapterornament}{%
  \par\vspace{2.5\baselineskip}%
  \WFclear
  {\centering\large\itshape *\quad *\quad *\par}%
}

% =============================================================
% UNIFIED IMAGE MACROS
% -------------------------------------------------------------
% Three public functions cover every image case:
%
% 1) \imageGrid[options]{file1,file2,...}{caption}{label}
%    - ONE file   -> single centered photo
%    - TWO+ files -> grid: columns=N (rows automatic)
%    - columns=1 with 2+ files -> vertical stack
%    - rotate=<angle> -> rotated photo(s)
%    - wrap=left|right -> wrapfigure, text flows beside the photo
%    - mode=bleed -> dedicated full-page cover composition
%    - letters=true -> a,b,c... overlaid on each photo
%
% 2) \imageColumns[options]{ {col1}, {col2a,col2b}, ... }{caption}{label}
%    Each braced group is one column; files inside a group are
%    stacked vertically. widths={40,60} = column widths in %
%    (sum 100; omitted = equal; sum != 100 -> warning +
%    proportional redistribution). Columns are top-aligned.
%
% 3) \imageBleed[options]{file}{caption}{label}
%    - mode=full (default): dedicated page, image covers the
%      WHOLE physical sheet (paper + bleed), uniform scale,
%      caption/folio overlaid at the bottom.
%    - mode=partial: horizontal bleed only (width=\paperwidth),
%      natural height, floating figure, text above/below.
%      place=c -> dedicated plate page, image centered on the
%      physical sheet. extend=top|bottom (with place=t|b) pulls
%      the image to the physical page edge.
%    - mode=vertical: VERTICAL bleed only, dedicated page: the
%      image fills the WHOLE physical sheet height (uniform
%      scale, top and bottom bleed past the trim); its width
%      stays natural. The image (and caption/folio) is centered
%      on the TEXT BLOCK (parity-aware), not on the sheet.
%
% All overlays use TikZ "remember picture": TWO compilations are
% needed for correct positioning.
% =============================================================
\makeatletter
% -------------------------------------------------------------
% Registers, counters, key families
% -------------------------------------------------------------
\newsavebox{\bap@box}
\newif\ifbap@letters
\newif\ifbap@folio
\newif\ifbap@background
\newif\ifbap@overlay
\newif\ifbap@fillh
\newif\ifbap@firstcol
\newif\ifbap@firstphoto
\newif\ifbap@wgiven
\newlength{\bap@hgap}
\newlength{\bap@vgap}
\newlength{\bap@cellw}
\newlength{\bap@colw}
\newlength{\bap@totalw}
\newlength{\bap@w}
\newlength{\bap@h}
\newlength{\bap@folio@y}
\newlength{\bap@cap@y}
\newlength{\bap@tmpd}
\newlength{\bap@topdist}
\newlength{\bap@botdist}
\newlength{\bap@captionw}
\newcounter{bap@letter}
\newcounter{bap@cols}
\newcounter{bap@pct}
\newcounter{bap@n}
\newcounter{bap@id}

% Comparison sentinels (English values only).
\def\bap@zero{0}
\def\bap@modebleed{bleed}
\def\bap@modefull{full}
\def\bap@modepartial{partial}
\def\bap@modevertical{vertical}
\def\bap@even{even}
\def\bap@odd{odd}
\def\bap@landscape{landscape}
\def\bap@portrait{portrait}
\def\bap@wrapnone{none}
\def\bap@left{left}
\def\bap@right{right}
\def\bap@posC{c}
\def\bap@extendtop{top}
\def\bap@extendbottom{bottom}
\def\bap@extendnone{none}

% Common keys, defined once for each key family.
\newcommand{\bap@commonkeys}[1]{%
  \define@key{#1}{place}{\def\bap@pos{##1}}%
  \define@key{#1}{width}{\def\bap@width{##1}}%
  \define@key{#1}{maxheight}{%
    \def\bap@tmp{none}\def\bap@tmpb{##1}%
    \ifx\bap@tmpb\bap@tmp\let\bap@maxh\@empty\else\def\bap@maxh{##1}\fi}%
  \define@key{#1}{gap}{\setlength{\bap@hgap}{##1}\setlength{\bap@vgap}{##1}}%
  \define@key{#1}{hgap}{\setlength{\bap@hgap}{##1}}%
  \define@key{#1}{vgap}{\setlength{\bap@vgap}{##1}}%
  \define@key{#1}{rotate}{\def\bap@rot{##1}}%
  \define@key{#1}{letters}[true]{\csname bap@letters##1\endcsname}%
  \define@key{#1}{lettercolor}{\def\bap@lcolor{##1}}%
  \define@key{#1}{mode}{\def\bap@mode{##1}}%
  \define@key{#1}{folio}[true]{\csname bap@folio##1\endcsname}%
  \define@key{#1}{background}[true]{\csname bap@background##1\endcsname}%
  \define@key{#1}{color}{\def\bap@color{##1}}%
  \define@key{#1}{page}{\def\bap@pageside{##1}}%
  \define@key{#1}{orientation}{\def\bap@orient{##1}}%
  % Local caption overrides (fall back to the global
  % \bookasprosetup values, re-established by the defaults).
  \define@key{#1}{captionfont}{\def\bap@captionfont{##1}}%
  \define@key{#1}{captionskip}{\def\bap@captionskip{##1}}%
}
\bap@commonkeys{bapgrid}
\bap@commonkeys{bapcolumns}
\bap@commonkeys{bapbleed}
\define@key{bapgrid}{columns}{\def\bap@ncols{#1}}
\define@key{bapgrid}{wrap}{\def\bap@wrap{#1}}
\define@key{bapcolumns}{widths}{\def\bap@widths{#1}}
\define@key{bapbleed}{extend}{\def\bap@extend{#1}}
\define@key{bapbleed}{overlay}[true]{\csname bap@overlay#1\endcsname}

% -------------------------------------------------------------
% Defaults
% -------------------------------------------------------------
\newcommand{\bap@griddefaults}{%
  \def\bap@pos{htbp}%
  \def\bap@ncols{2}%
  \def\bap@width{\textwidth}%
  \def\bap@maxh{0.70\textheight}%
  \setlength{\bap@hgap}{2mm}\setlength{\bap@vgap}{2mm}%
  \def\bap@rot{0}%
  \bap@lettersfalse
  \def\bap@lcolor{black}%
  \def\bap@mode{normal}%
  \def\bap@wrap{none}%
  \bap@foliotrue\bap@backgroundtrue
  \def\bap@pageside{auto}\def\bap@color{white}\def\bap@orient{auto}%
  \let\bap@captionfont\bap@gcaptionfont
  \let\bap@captionskip\bap@gcaptionskip
  \setcounter{bap@letter}{0}%
}
\newcommand{\bap@colsdefaults}{%
  \def\bap@pos{htbp}%
  \def\bap@width{\textwidth}%
  \let\bap@maxh\@empty
  \setlength{\bap@hgap}{2mm}\setlength{\bap@vgap}{2mm}%
  \def\bap@rot{0}%
  \bap@lettersfalse
  \def\bap@lcolor{black}%
  \def\bap@mode{normal}%
  \def\bap@widths{}%
  \bap@foliotrue\bap@backgroundtrue
  \def\bap@pageside{auto}\def\bap@color{white}\def\bap@orient{auto}%
  \let\bap@captionfont\bap@gcaptionfont
  \let\bap@captionskip\bap@gcaptionskip
  \setcounter{bap@letter}{0}%
}
\newcommand{\bap@bleeddefaults}{%
  \def\bap@mode{full}%
  \def\bap@pos{htbp}%
  \def\bap@pageside{auto}%
  \bap@foliotrue\bap@backgroundtrue
  \def\bap@color{white}%
  \def\bap@orient{auto}%
  \def\bap@rot{0}%
  \def\bap@extend{none}%
  \bap@overlayfalse
  \let\bap@captionfont\bap@gcaptionfont
  \let\bap@captionskip\bap@gcaptionskip
}

% -------------------------------------------------------------
% Value normalization: wrap side left/right -> wrapfig l/r.
% -------------------------------------------------------------
\newcommand{\bap@normwrap}{%
  \ifx\bap@wrap\bap@left\def\bap@wrap{l}\fi
  \ifx\bap@wrap\bap@right\def\bap@wrap{r}\fi
}

% -------------------------------------------------------------
% Single photo with optional overlaid letter.
% #1 = width, #2 = file, #3 = letter (empty = none).
% Photo and letter live in the SAME tikzpicture (no remember
% picture needed for letters). \protected: file/width/letter are
% frozen at accumulation time; the body must NOT expand during
% \edef.
% -------------------------------------------------------------
\protected\def\bap@photo#1#2#3{%
  \tikz{%
    \node[inner sep=0,outer sep=0] (bap@img) {\bap@graphic{#1}{#2}};
    \IfBlankTF{#3}{}{%
      \node[anchor=north west,inner sep=0,font=\small\bfseries,text opacity=1]
        at ([xshift=1.5mm,yshift=-1.5mm]bap@img.north west)
        {\color{\bap@lcolor}#3};
    }%
  }%
}
\newcommand{\bap@graphic}[2]{%
  \ifx\bap@rot\bap@zero
    \bap@inc{#1}{#2}%
  \else
    \expandafter\rotatebox\expandafter{\bap@rot}{\bap@inc{#1}{#2}}%
  \fi
}
\newcommand{\bap@inc}[2]{%
  \ifx\bap@maxh\@empty
    \includegraphics[width=#1,keepaspectratio]{#2}%
  \else
    \includegraphics[width=#1,height=\bap@maxh,keepaspectratio]{#2}%
  \fi
}

% -------------------------------------------------------------
% GRID builder -> \bap@box.  #1 = comma-separated file list.
% One file = single photo at full composition width.
% -------------------------------------------------------------
\newcommand{\bap@grid}[1]{%
  \setcounter{bap@n}{0}%
  \foreach \f in {#1}{\stepcounter{bap@n}}%
  \ifnum\arabic{bap@n}=1
    \def\bap@ncols{1}%
  \fi
  \setlength{\bap@cellw}{\dimexpr(\bap@width-\bap@hgap*\numexpr\bap@ncols-1\relax)/\bap@ncols\relax}%
  % tabular preamble: c columns separated by hgap
  \def\bap@preamble{@{}}%
  \foreach \i in {1,...,\bap@ncols}{%
    \ifnum\i>1
      \g@addto@macro\bap@preamble{@{\hspace{\bap@hgap}}}%
    \fi
    \g@addto@macro\bap@preamble{c}%
  }%
  \g@addto@macro\bap@preamble{@{}}%
  % body: & between cells, \\[vgap] between rows. File names and
  % letters are FROZEN now (\edef): \f and the counter only exist
  % inside the loop.
  \def\bap@body{}%
  \foreach \f [count=\i] in {#1}{%
    \ifnum\i>1
      \ifnum\i=\numexpr(\i-1)/\bap@ncols*\bap@ncols+1\relax
        \g@addto@macro\bap@body{\\[\bap@vgap]}%
      \else
        \g@addto@macro\bap@body{&}%
      \fi
    \fi
    \stepcounter{bap@letter}%
    \ifbap@letters
      \edef\bap@let{\alph{bap@letter}}%
    \else
      \def\bap@let{}%
    \fi
    \edef\bap@tmp{%
      \noexpand\g@addto@macro\noexpand\bap@body{%
        \noexpand\bap@photo{\the\bap@cellw}{\f}{\bap@let}%
      }%
    }%
    \bap@tmp
  }%
  \sbox{\bap@box}{%
    \setlength{\tabcolsep}{0pt}%
    % arraystretch 0: no row strut, box height/depth exactly like
    % plain \includegraphics lines (layout fidelity)
    \renewcommand{\arraystretch}{0}%
    \expandafter\tabular\expandafter{\bap@preamble}%
      \bap@body
    \endtabular
  }%
}

% -------------------------------------------------------------
% COLUMNS builder -> \bap@box.  #1 = comma-separated braced
% groups, one per column; files inside each group are stacked
% vertically. \foreach strips a group's braces only when a comma
% follows immediately; the dispatcher below normalizes spacing.
% -------------------------------------------------------------
\def\bap@dispatch{%
  \@ifnextchar\bgroup{\bap@dispatch@braced}{\bap@dispatch@plain}%
}
\def\bap@dispatch@braced#1#2\bap@dispatch@end{\bap@photos{#1}}%
\def\bap@dispatch@plain#1\bap@dispatch@end{\bap@photos{#1}}%
\newcommand{\bap@photos}[1]{%
  \foreach \f in {#1}{%
    \ifbap@firstphoto
      \global\bap@firstphotofalse
    \else
      \g@addto@macro\bap@colbody{\vskip\bap@vgap}%
    \fi
    \stepcounter{bap@letter}%
    \ifbap@letters
      \edef\bap@let{\alph{bap@letter}}%
    \else
      \def\bap@let{}%
    \fi
    \edef\bap@tmp{%
      \noexpand\g@addto@macro\noexpand\bap@colbody{%
        \noexpand\hbox{\noexpand\bap@photo{\the\bap@colw}{\f}{\bap@let}}%
      }%
    }%
    \bap@tmp
  }%
}
\newcommand{\bap@cols}[1]{%
  \setcounter{bap@cols}{0}%
  \foreach \g in {#1}{\stepcounter{bap@cols}}%
  \setlength{\bap@totalw}{\dimexpr\bap@width-\bap@hgap*\numexpr\arabic{bap@cols}-1\relax\relax}%
  \bap@wgivenfalse
  \ifx\bap@widths\@empty\else\bap@wgiventrue\fi
  \ifbap@wgiven
    \setcounter{bap@pct}{0}%
    \foreach \p in \bap@widths{\addtocounter{bap@pct}{\p}}%
    \ifnum\arabic{bap@pct}=100\else
      \ClassWarningNoLine{bookaspro}{widths: percentage sum is
        \arabic{bap@pct}, not 100: automatic proportional redistribution}%
    \fi
  \fi
  \def\bap@body{}%
  \bap@firstcoltrue
  \foreach \g [count=\ci] in {#1}{%
    \ifbap@wgiven
      \foreach \p [count=\pi] in \bap@widths{%
        \ifnum\pi=\ci
          % \global: assignments inside \foreach are local to the
          % iteration group and would be lost at loop end
          \global\setlength{\bap@colw}{\dimexpr\bap@totalw*\p/\arabic{bap@pct}\relax}%
        \fi
      }%
    \else
      \global\setlength{\bap@colw}{\dimexpr\bap@totalw/\arabic{bap@cols}\relax}%
    \fi
    \def\bap@colbody{}%
    \bap@firstphototrue
    \expandafter\bap@dispatch\g\bap@dispatch@end
    \ifbap@firstcol
      \global\bap@firstcolfalse
    \else
      \g@addto@macro\bap@body{\hskip\bap@hgap}%
    \fi
    \edef\bap@tmp{%
      \noexpand\g@addto@macro\noexpand\bap@body{%
        \noexpand\vtop{\noexpand\vskip0pt\bap@colbody}%
      }%
    }%
    \bap@tmp
  }%
  \sbox{\bap@box}{\hbox to\bap@width{\bap@body\hfil}}%
  % \vtop reference is at the top: normalize the final box
  % baseline to the bottom, like a normal image
  \setlength{\bap@tmpd}{\dp\bap@box}%
  \sbox{\bap@box}{\raisebox{\bap@tmpd}{\usebox{\bap@box}}}%
}

% -------------------------------------------------------------
% NORMAL mode: floating figure in the text flow
% -------------------------------------------------------------
\newcommand{\bap@normal}[3]{%
  \bap@build{#1}%
  % float spec must be expanded BEFORE figure reads it
  \edef\bap@next{\noexpand\begin{figure}[\bap@pos]}%
  \bap@next
    \centering
    \usebox{\bap@box}%
    % smaller captions, closer to the image (configurable)
    \captionsetup{font=\bap@captionfont,skip=\bap@captionskip,
      margin=\bap@gcaptionmargin}%
    % always \caption: an empty caption {} still produces a
    % numbered figure and an (empty) List-of-Figures entry
    \caption{#2}%
    \label{#3}%
  \end{figure}%
}

% -------------------------------------------------------------
% WRAP mode (grid only): text flows beside the photo
% -------------------------------------------------------------
\newcommand{\bap@wrapfig}[3]{%
  \edef\bap@next{\noexpand\begin{wrapfigure}{\bap@wrap}{\bap@width}}%
  \bap@next
    \centering
    \captionsetup{font=\bap@captionfont,skip=\bap@captionskip,
      margin=\bap@gcaptionmargin}%
    \bap@graphic{\linewidth}{#1}%
    \caption{#2}%
    \label{#3}%
  \end{wrapfigure}%
}

% -------------------------------------------------------------
% BLEED machinery (shared by \imageBleed and mode=bleed)
% -------------------------------------------------------------
% Dedicated page setup + parity compensation (page=even|odd
% inserts a blank page when needed).
\newcommand{\bap@page}{%
  \clearpage
  \ifx\bap@pageside\bap@even
    \ifodd\c@page
      \null\thispagestyle{empty}\clearpage
    \fi
  \else
    \ifx\bap@pageside\bap@odd
      \ifodd\c@page\else
        \null\thispagestyle{empty}\clearpage
      \fi
    \fi
  \fi
  \thispagestyle{empty}%
}
% Panels: with background=false NO fill is emitted at all.
% Node text always has text opacity=1 (solid color): without it,
% TikZ node text would inherit the fill opacity (invisible text).
\newcommand{\bap@bg}{%
  \ifbap@background
    \tikzset{bap@capbg/.style={fill=black,fill opacity=0.55,rounded corners=2pt}}%
    \tikzset{bap@folbg/.style={fill=black,fill opacity=0.35,rounded corners=1.5pt}}%
  \else
    \tikzset{bap@capbg/.style={}}%
    \tikzset{bap@folbg/.style={}}%
  \fi
}
% Choose the cover fill side (orientation + safety net: a full
% cover is always guaranteed). Requires \bap@w/\bap@h = current
% content dimensions.
\newcommand{\bap@choosefill}{%
  \ifx\bap@orient\bap@landscape
    \bap@fillhtrue
  \else
    \ifx\bap@orient\bap@portrait
      \bap@fillhfalse
    \else
      \ifdim\dimexpr\bap@w*\p@/\bap@h\relax
            >\dimexpr\paperwidth*\p@/\paperheight\relax
        \bap@fillhtrue
      \else
        \bap@fillhfalse
      \fi
    \fi
  \fi
  \ifbap@fillh
    \ifdim\dimexpr\bap@w*\p@/\bap@h\relax
          <\dimexpr\paperwidth*\p@/\paperheight\relax
      \bap@fillhfalse
    \fi
  \else
    \ifdim\dimexpr\bap@w*\p@/\bap@h\relax
          >\dimexpr\paperwidth*\p@/\paperheight\relax
      \bap@fillhtrue
    \fi
  \fi
}
% Uniform cover scaling of \bap@box (no distortion); excess on
% the long side bleeds past the PDF edge and is trimmed.
\newcommand{\bap@cover}{%
  \bap@choosefill
  \ifbap@fillh
    \sbox{\bap@box}{\resizebox{\dimexpr\bap@w*\paperheight/\bap@h\relax}{!}{\usebox{\bap@box}}}%
  \else
    \sbox{\bap@box}{\resizebox{\paperwidth}{!}{\usebox{\bap@box}}}%
  \fi
}
% Parity-aware horizontal center of the TEXT BLOCK, defined as a
% TikZ coordinate named (bap@tbcenter). Dedicated-page overlays
% center captions/folios on the live area (respecting bindingoffset
% and the asymmetric inner/outer margins), never on the physical
% sheet center.
\newcommand{\bap@tbcenter}{%
  \coordinate (bap@tbcenter) at ([%
    xshift=\dimexpr 1in+\hoffset
      +\ifodd\c@page\oddsidemargin\else\evensidemargin\fi
      +\textwidth/2\relax]current page.west);
}
% Vertical positions + width of an overlaid bleed caption/folio.
% The folio baseline (\bap@folio@y) sits at the bottom margin minus
% the footskip; the caption (\bap@cap@y) floats above it by the
% configurable \bap@gbleedcaptionskip. The caption text width keeps
% the panel (6pt inner sep on both sides) inside the text block.
\newcommand{\bap@capfolcalc}{%
  \setlength{\bap@folio@y}{\dimexpr\paperheight-1in-\voffset-\topmargin
    -\headheight-\headsep-\textheight-\footskip\relax}%
  \setlength{\bap@cap@y}{\dimexpr\bap@folio@y+\bap@gbleedcaptionskip\relax}%
  \setlength{\bap@captionw}{\dimexpr\textwidth-12pt\relax}%
}
% Overlaid caption node (no folio). #1 = caption text.
\newcommand{\bap@captionnode}[1]{%
  \IfBlankTF{#1}{}{%
    \node[anchor=south,text width=\bap@captionw,align=center,
          font=\csname\bap@captionfont\endcsname,text opacity=1,bap@capbg,inner sep=6pt]
      at ([yshift=\bap@cap@y]bap@tbcenter |- current page.south)
      {\color{\bap@color}#1};
  }%
}
% Overlaid folio node (only when \bap@folio is set).
\newcommand{\bap@folionode}{%
  \ifbap@folio
    \node[anchor=base,font=\footnotesize,text opacity=1,bap@folbg,inner sep=2pt]
      at ([yshift=\bap@folio@y]bap@tbcenter |- current page.south)
      {\color{\bap@color}\thepage};
  \fi
}
% Overlaid caption + folio inside the current remember-picture
% tikzpicture. The image \bap@box must already be placed.
% #1 = caption.
\newcommand{\bap@capfolnodes}[1]{%
  \bap@tbcenter
  \bap@captionnode{#1}%
  \bap@folionode
}
% Overlays + numbering of the dedicated page.
% #1 = caption, #2 = label. \label BEFORE the final \clearpage.
\newcommand{\bap@overlay}[2]{%
  \bap@capfolcalc
  \begin{tikzpicture}[remember picture,overlay]
    \node[inner sep=0,outer sep=0] at (current page.center) {\usebox{\bap@box}};
    \bap@capfolnodes{#1}
  \end{tikzpicture}%
  \refstepcounter{figure}%
  \phantomsection
  \label{#2}%
  \addcontentsline{lof}{figure}{\protect\numberline{\thefigure}{#1}}%
  \null
  \clearpage
}

% \imageBleed mode=full: measure at 100 pt, choose the fill side,
% re-include at the cover width (rotation applied throughout).
\newcommand{\bap@bleedfull}[3]{%
  \bap@page
  \bap@bg
  \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
    {\includegraphics[width=100pt]{#1}}}%
  \setlength{\bap@w}{\wd\bap@box}%
  \setlength{\bap@h}{\dimexpr\ht\bap@box+\dp\bap@box\relax}%
  \bap@choosefill
  \ifbap@fillh
    \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
      {\includegraphics[width=\dimexpr\dimexpr\paperheight*\p@/\bap@h\relax*100\relax]{#1}}}%
  \else
    \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
      {\includegraphics[width=\dimexpr\dimexpr\paperwidth*\p@/\bap@w\relax*100\relax]{#1}}}%
  \fi
  \bap@overlay{#2}{#3}%
}

% Shared box builder for partial/center: a (possibly rotated) box
% whose POST-rotation width is exactly \paperwidth, natural
% height. Too-tall images are uniformly reduced (warning in the
% .log; the horizontal bleed may become partial). Works with any
% rotation angle.
\newcommand{\bap@partialbox}[1]{%
  % measure the rotated photo at 100 pt width (proportions intact)
  \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
    {\includegraphics[width=100pt]{#1}}}%
  \setlength{\bap@w}{\wd\bap@box}%
  % final pre-rotation width = paperwidth * 100 / measured width
  \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
    {\includegraphics[width=\dimexpr\dimexpr\paperwidth*\p@/\bap@w\relax*100\relax]{#1}}}%
  \setlength{\bap@h}{\dimexpr\ht\bap@box+\dp\bap@box\relax}%
  \ifdim\bap@h>\dimexpr\textheight-4\baselineskip\relax
    \ClassWarningNoLine{bookaspro}{Image too tall for mode=partial:
      reduced to fit the page; horizontal bleed may not reach the sheet
      edge on both sides}%
    \sbox{\bap@box}{\resizebox{!}{\dimexpr\textheight-4\baselineskip\relax}{\usebox{\bap@box}}}%
    \setlength{\bap@h}{\dimexpr\ht\bap@box+\dp\bap@box\relax}%
  \fi
}

% \imageBleed mode=partial: horizontal bleed, natural height,
% floating figure, text above/below, standard caption.
% extend=top|bottom pulls the image to the PHYSICAL page edge
% (covering the bleed) for a full top banner / full footer.
\newcommand{\bap@bleedpartial}[3]{%
  \stepcounter{bap@id}%
  \edef\bap@ancname{bap@anc\arabic{bap@id}}%
  \bap@partialbox{#1}%
  % extend validation against place: accept t/b (or p) but NOT h:
  % a "here" float could land mid-text and the negative space
  % would overlap the surrounding text.
  \ifx\bap@extend\bap@extendtop
    % \pgfutil@in@ does not expand its argument: freeze place first.
    \edef\bap@tmp{\noexpand\pgfutil@in@{t}{\bap@pos}}\bap@tmp
    \ifpgfutil@in@
      \edef\bap@tmp{\noexpand\pgfutil@in@{h}{\bap@pos}}\bap@tmp
      \ifpgfutil@in@
        \ClassWarningNoLine{bookaspro}{extend=top requires a
          top-only place (t or p, without h): extend ignored}%
        \def\bap@extend{none}%
      \fi
    \else
      \edef\bap@tmp{\noexpand\pgfutil@in@{p}{\bap@pos}}\bap@tmp
      \ifpgfutil@in@\else
        \ClassWarningNoLine{bookaspro}{extend=top requires
          place=t (or p): extend ignored}%
        \def\bap@extend{none}%
      \fi
    \fi
  \fi
  \ifx\bap@extend\bap@extendbottom
    \edef\bap@tmp{\noexpand\pgfutil@in@{b}{\bap@pos}}\bap@tmp
    \ifpgfutil@in@
      \edef\bap@tmp{\noexpand\pgfutil@in@{h}{\bap@pos}}\bap@tmp
      \ifpgfutil@in@
        \ClassWarningNoLine{bookaspro}{extend=bottom requires a
          bottom-only place (b or p, without h): extend ignored}%
        \def\bap@extend{none}%
      \fi
    \else
      \edef\bap@tmp{\noexpand\pgfutil@in@{p}{\bap@pos}}\bap@tmp
      \ifpgfutil@in@\else
        \ClassWarningNoLine{bookaspro}{extend=bottom requires
          place=b (or p): extend ignored}%
        \def\bap@extend{none}%
      \fi
    \fi
  \fi
  % distances from the physical page edges to the text block,
  % straight from the geometry registers
  \setlength{\bap@topdist}{\dimexpr 1in+\voffset+\topmargin
    +\headheight+\headsep\relax}%
  \setlength{\bap@botdist}{\dimexpr\paperheight-1in-\voffset-\topmargin
    -\headheight-\headsep-\textheight\relax}%
  \edef\bap@next{\noexpand\begin{figure}[\bap@pos]}%
  \bap@next
    \centering
    % smaller captions, closer to the image (configurable)
    \captionsetup{font=\bap@captionfont,skip=\bap@captionskip,
      margin=\bap@gcaptionmargin}%
    \ifx\bap@extend\bap@extendtop
      % pull the reserved space up to the physical page top:
      % the image (anchored to the coordinate below) starts there
      \vspace*{-\bap@topdist}%
    \fi
    \ifx\bap@extend\bap@extendbottom
      \ifbap@overlay
        % full footer OVERLAY: caption drawn over the image (color +
        % panel, mirroring the full-page / vertical bleed). The page is
        % a normal text page, so the running folio stays in place.
        \bap@bg
        \bap@capfolcalc
      \else
        % full footer: caption ABOVE the image
        \caption{#2}%
        \label{#3}%
      \fi
    \fi
    \ifx\bap@extend\bap@extendbottom
      % full footer: the image is anchored DIRECTLY to the physical
      % page bottom (south), so the bottom bleed is fully covered.
      % Only the in-text portion (image height minus the bottom
      % margin) is reserved in the flow, so the caption sits just
      % above the image top and no trailing negative space is needed.
      \vbox to \dimexpr\bap@h-\bap@botdist\relax{%
        \vfil
        \hbox{%
          \begin{tikzpicture}[remember picture,overlay]
            \node[anchor=south,inner sep=0,outer sep=0]
              at (current page.south) {\usebox{\bap@box}};
            \ifbap@overlay
              % Caption centered on the PHYSICAL sheet: the full-width
              % footer image is centered on the sheet, and this float
              % has no reliable parity (unlike a dedicated page).
              \node[anchor=south,text width=\bap@captionw,align=center,
                    font=\csname\bap@captionfont\endcsname,text opacity=1,bap@capbg,inner sep=6pt]
                at ([yshift=\bap@cap@y]current page.south)
                {\color{\bap@color}#2};
            \fi
          \end{tikzpicture}%
        }%
      }%
    \else
      % exact vertical space of the image. The remember-picture
      % coordinate marks its top; the overlay picture that draws the
      % image lives INSIDE the vbox (zero-size hbox): no extra line,
      % so the negative space above (extend=top) is exact and
      % independent of \baselineskip (setspace-safe).
      \vbox to\bap@h{%
        \hbox{\tikz[remember picture,overlay]\coordinate (\bap@ancname) at (0,0);}%
        \vfil
        \hbox{%
          \begin{tikzpicture}[remember picture,overlay]
            \node[anchor=north,inner sep=0,outer sep=0]
              at (current page.center |- \bap@ancname) {\usebox{\bap@box}};
          \end{tikzpicture}%
        }%
      }%
    \fi
    \ifx\bap@extend\bap@extendbottom
      \ifbap@overlay
        % no \caption: number + label + LoF entry set manually
        \refstepcounter{figure}%
        \phantomsection
        \label{#3}%
        \addcontentsline{lof}{figure}{\protect\numberline{\thefigure}{#2}}%
      \else
        % caption already emitted above
      \fi
    \else
      \caption{#2}%
      \label{#3}%
    \fi
  \end{figure}%
}

% \imageBleed mode=partial, place=c: dedicated plate page, image
% centered on the physical sheet (horizontal bleed, natural
% height), caption below, normal folio. No remember picture
% needed: the page is dedicated, so the parity (and the margin
% shift) is known here.
\newcommand{\bap@bleedcenter}[3]{%
  \clearpage
  \bap@partialbox{#1}%
  \null\vfill
  \begingroup
    \centering
    % \captionof lives outside a float: hypcap has nothing to
    % anchor to
    \captionsetup{hypcap=false,font=\bap@captionfont,skip=\bap@captionskip,
      margin=\bap@gcaptionmargin}%
    \par\noindent
    % shift left by the physical left margin of THIS page (recto
    % or verso): the paperwidth-wide box then spans edge to edge
    \makebox[\textwidth][l]{%
      \hspace*{-\dimexpr 1in+\hoffset
        +\ifodd\c@page\oddsidemargin\else\evensidemargin\fi\relax}%
      \usebox{\bap@box}%
    }%
    \par
    \captionof{figure}{#2}%
    \label{#3}%
  \endgroup
  \vfill\null
  \clearpage
}

% \imageBleed mode=vertical: VERTICAL bleed only. Dedicated page:
% the image fills the WHOLE physical sheet height (uniform scale,
% top and bottom bleed past the trim); its width stays natural, so
% a portrait image leaves white bands on the left and right. The
% image (and the overlaid caption/folio) is horizontally centered
% on the TEXT BLOCK (parity-aware asymmetric margins), not on the
% physical sheet. rotate works as in the other modes.
\newcommand{\bap@bleedvertical}[3]{%
  \bap@page
  \bap@bg
  % measure the natural post-rotation proportions at 100 pt width
  \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
    {\includegraphics[width=100pt]{#1}}}%
  \setlength{\bap@h}{\dimexpr\ht\bap@box+\dp\bap@box\relax}%
  % stretch uniformly so the POST-rotation height equals the full
  % physical sheet height (vertical bleed); width stays natural.
  \sbox{\bap@box}{\expandafter\rotatebox\expandafter{\bap@rot}%
    {\includegraphics[width=\dimexpr\dimexpr\paperheight*\p@/\bap@h\relax*100\relax]{#1}}}%
  \bap@capfolcalc
  \begin{tikzpicture}[remember picture,overlay]
    % horizontal center of the TEXT BLOCK (parity-aware): the image
    % (and caption/folio) align to the live area, not the sheet center
    \bap@tbcenter
    \node[anchor=north,inner sep=0,outer sep=0]
      at (bap@tbcenter |- current page.north) {\usebox{\bap@box}};
    \bap@capfolnodes{#2}
  \end{tikzpicture}%
  \refstepcounter{figure}%
  \phantomsection
  \label{#3}%
  \addcontentsline{lof}{figure}{\protect\numberline{\thefigure}{#2}}%
  \null
  \clearpage
}

% grid/columns mode=bleed: dedicated page, uniform cover of the
% composition (edge photos get trimmed -- documented bleed
% behavior).
\newcommand{\bap@compbleed}[3]{%
  \bap@page
  \bap@bg
  \bap@build{#1}%
  \setlength{\bap@w}{\wd\bap@box}%
  \setlength{\bap@h}{\dimexpr\ht\bap@box+\dp\bap@box\relax}%
  \bap@cover
  \bap@overlay{#2}{#3}%
}

% -------------------------------------------------------------
% PUBLIC IMAGE MACROS
% -------------------------------------------------------------
\NewDocumentCommand{\imageGrid}{ O{} m m m }{%
  \bap@griddefaults
  \setkeys{bapgrid}{#1}%
  \bap@normwrap
  \ifx\bap@wrap\bap@wrapnone
    \let\bap@build\bap@grid
    \ifx\bap@mode\bap@modebleed
      \bap@compbleed{#2}{#3}{#4}%
    \else
      \bap@normal{#2}{#3}{#4}%
    \fi
  \else
    \bap@wrapfig{#2}{#3}{#4}%
  \fi
}

\NewDocumentCommand{\imageColumns}{ O{} m m m }{%
  \bap@colsdefaults
  \setkeys{bapcolumns}{#1}%
  \let\bap@build\bap@cols
  \ifx\bap@mode\bap@modebleed
    \bap@compbleed{#2}{#3}{#4}%
  \else
    \bap@normal{#2}{#3}{#4}%
  \fi
}

\NewDocumentCommand{\imageBleed}{ O{} m m m }{%
  \bap@bleeddefaults
  \setkeys{bapbleed}{#1}%
  \ifx\bap@mode\bap@modepartial
    \ifx\bap@pos\bap@posC
      \bap@bleedcenter{#2}{#3}{#4}%
    \else
      \bap@bleedpartial{#2}{#3}{#4}%
    \fi
  \else
    \ifx\bap@mode\bap@modevertical
      \bap@bleedvertical{#2}{#3}{#4}%
    \else
      \bap@bleedfull{#2}{#3}{#4}%
    \fi
  \fi
}
\makeatother

% =============================================================
% BLEED PROOFING OVERLAY
% \showBleedMargin[options] draws, on EVERY page (shipout
% foreground, visible even over full-bleed images):
%   - the trim line in RED (+ cam crop marks), inset from the PDF
%     edge by the bleed amount;
%   - the inner safety margin in DASHED BLUE, further inside the
%     trim line by the margin amount;
%   - the text block border in DASHED GREEN (parity-aware).
% Pure drawing: no margin/layout/paper-size changes.
% \hideBleedMargin disables everything (the default state).
% Legacy aliases: \showBleed{<mm>} = \showBleedMargin[bleed=<mm>mm],
% \hideBleed = \hideBleedMargin.
% =============================================================
\makeatletter
\newif\ifbap@debug
\bap@debugfalse
\newif\ifbap@showbleed
\newif\ifbap@showmargin
\newif\ifbap@showtext
\newif\ifbap@label
% Per-side bleed (from the PDF edge inward) and inner margin
% (from the trim line further inward).
\newlength{\bap@bleedL}
\newlength{\bap@bleedR}
\newlength{\bap@bleedT}
\newlength{\bap@bleedB}
\newlength{\bap@marginL}
\newlength{\bap@marginR}
\newlength{\bap@marginT}
\newlength{\bap@marginB}
\define@key{bapdebug}{bleed}{%
  \setlength{\bap@bleedL}{#1}\setlength{\bap@bleedR}{#1}%
  \setlength{\bap@bleedT}{#1}\setlength{\bap@bleedB}{#1}}
\define@key{bapdebug}{bleedleft}{\setlength{\bap@bleedL}{#1}}
\define@key{bapdebug}{bleedright}{\setlength{\bap@bleedR}{#1}}
\define@key{bapdebug}{bleedtop}{\setlength{\bap@bleedT}{#1}}
\define@key{bapdebug}{bleedbottom}{\setlength{\bap@bleedB}{#1}}
\define@key{bapdebug}{margin}{%
  \setlength{\bap@marginL}{#1}\setlength{\bap@marginR}{#1}%
  \setlength{\bap@marginT}{#1}\setlength{\bap@marginB}{#1}}
\define@key{bapdebug}{marginleft}{\setlength{\bap@marginL}{#1}}
\define@key{bapdebug}{marginright}{\setlength{\bap@marginR}{#1}}
\define@key{bapdebug}{margintop}{\setlength{\bap@marginT}{#1}}
\define@key{bapdebug}{marginbottom}{\setlength{\bap@marginB}{#1}}
\define@key{bapdebug}{showbleed}[true]{\csname bap@showbleed#1\endcsname}
\define@key{bapdebug}{showmargin}[true]{\csname bap@showmargin#1\endcsname}
\define@key{bapdebug}{showtext}[true]{\csname bap@showtext#1\endcsname}
\define@key{bapdebug}{label}[true]{\csname bap@label#1\endcsname}

% Convert a dimension to a mm number (2 decimals) for the data
% label: pgfmath divides by 1mm, so the result is millimetres.
\newcommand{\bap@tomm}[2]{%
  \pgfmathsetmacro{#2}{round(#1/1mm*100)/100}%
}

\newcommand{\showBleedMargin}[1][]{%
  % defaults: 3 mm bleed, 5 mm inner margin, everything visible
  \setlength{\bap@bleedL}{3mm}\setlength{\bap@bleedR}{3mm}%
  \setlength{\bap@bleedT}{3mm}\setlength{\bap@bleedB}{3mm}%
  \setlength{\bap@marginL}{5mm}\setlength{\bap@marginR}{5mm}%
  \setlength{\bap@marginT}{5mm}\setlength{\bap@marginB}{5mm}%
  \bap@showbleedtrue\bap@showmargintrue\bap@showtexttrue\bap@labeltrue
  \setkeys{bapdebug}{#1}%
  \bap@debugtrue
}
\newcommand{\hideBleedMargin}{\bap@debugfalse}
% Legacy aliases (kept for compatibility with older preambles).
\newcommand{\showBleed}[1]{\showBleedMargin[bleed=#1mm]}
\newcommand{\hideBleed}{\hideBleedMargin}

\AddToHook{shipout/foreground}{%
  \ifbap@debug
    \begin{tikzpicture}[remember picture,overlay]
      % trim corners: PDF edge inset by the per-side bleed
      \coordinate (bap@trim@sw) at ([xshift=\bap@bleedL,yshift=\bap@bleedB]current page.south west);
      \coordinate (bap@trim@ne) at ([xshift=-\bap@bleedR,yshift=-\bap@bleedT]current page.north east);
      \coordinate (bap@trim@nw) at (bap@trim@sw |- bap@trim@ne);
      \coordinate (bap@trim@se) at (bap@trim@ne |- bap@trim@sw);
      % --- bleed layer: red trim line + cam crop marks ---
      \ifbap@showbleed
        \draw[red,line width=0.4pt] (bap@trim@sw) rectangle (bap@trim@ne);
        % marks run from the PDF edge toward the trim corner,
        % stopping 1 mm short; drawn only where bleed > 1 mm
        \ifdim\bap@bleedL>1mm
          \draw[black,line width=0.4pt]
            ([xshift=-\bap@bleedL]bap@trim@nw) -- ([xshift=-1mm]bap@trim@nw)
            ([xshift=-\bap@bleedL]bap@trim@sw) -- ([xshift=-1mm]bap@trim@sw);
        \fi
        \ifdim\bap@bleedR>1mm
          \draw[black,line width=0.4pt]
            ([xshift=\bap@bleedR]bap@trim@ne) -- ([xshift=1mm]bap@trim@ne)
            ([xshift=\bap@bleedR]bap@trim@se) -- ([xshift=1mm]bap@trim@se);
        \fi
        \ifdim\bap@bleedT>1mm
          \draw[black,line width=0.4pt]
            ([yshift=\bap@bleedT]bap@trim@nw) -- ([yshift=1mm]bap@trim@nw)
            ([yshift=\bap@bleedT]bap@trim@ne) -- ([yshift=1mm]bap@trim@ne);
        \fi
        \ifdim\bap@bleedB>1mm
          \draw[black,line width=0.4pt]
            ([yshift=-\bap@bleedB]bap@trim@sw) -- ([yshift=-1mm]bap@trim@sw)
            ([yshift=-\bap@bleedB]bap@trim@se) -- ([yshift=-1mm]bap@trim@se);
        \fi
      \fi
      % --- inner margin layer: dashed blue, inside the trim line ---
      \ifbap@showmargin
        \coordinate (bap@mar@sw) at ([xshift=\bap@marginL,yshift=\bap@marginB]bap@trim@sw);
        \coordinate (bap@mar@ne) at ([xshift=-\bap@marginR,yshift=-\bap@marginT]bap@trim@ne);
        \draw[blue,dashed,line width=0.4pt] (bap@mar@sw) rectangle (bap@mar@ne);
      \fi
      % --- text block border: dashed green, parity-aware ---
      \ifbap@showtext
        \coordinate (bap@text@sw) at ([%
          xshift=\dimexpr 1in+\hoffset
            +\ifodd\c@page\oddsidemargin\else\evensidemargin\fi\relax,
          yshift=\dimexpr\paperheight-1in-\voffset-\topmargin
            -\headheight-\headsep-\textheight\relax]current page.south west);
        \coordinate (bap@text@ne) at ([%
          xshift=\dimexpr 1in+\hoffset
            +\ifodd\c@page\oddsidemargin\else\evensidemargin\fi
            +\textwidth\relax,
          yshift=\dimexpr\paperheight-1in-\voffset-\topmargin
            -\headheight-\headsep\relax]current page.south west);
        \draw[green!60!black,dashed,line width=0.4pt]
          (bap@text@sw) rectangle (bap@text@ne);
      \fi
      % --- bottom data label, values in millimetres ---
      \ifbap@label
        \bap@tomm{\bap@bleedL}{\bap@mm@bl}%
        \bap@tomm{\bap@bleedR}{\bap@mm@br}%
        \bap@tomm{\bap@bleedT}{\bap@mm@bt}%
        \bap@tomm{\bap@bleedB}{\bap@mm@bb}%
        \bap@tomm{\bap@marginL}{\bap@mm@ml}%
        \bap@tomm{\bap@marginR}{\bap@mm@mr}%
        \bap@tomm{\bap@marginT}{\bap@mm@mt}%
        \bap@tomm{\bap@marginB}{\bap@mm@mb}%
        \node[font=\tiny,anchor=south,inner sep=0]
          at ([yshift=0.5mm]current page.south)
          {DEBUG --- {\color{red}bleed: left \pgfmathprintnumber[fixed,precision=2]{\bap@mm@bl},
            right \pgfmathprintnumber[fixed,precision=2]{\bap@mm@br},
            top \pgfmathprintnumber[fixed,precision=2]{\bap@mm@bt},
            bottom \pgfmathprintnumber[fixed,precision=2]{\bap@mm@bb} mm}%
           \quad{\color{blue}inner margin: left \pgfmathprintnumber[fixed,precision=2]{\bap@mm@ml},
            right \pgfmathprintnumber[fixed,precision=2]{\bap@mm@mr},
            top \pgfmathprintnumber[fixed,precision=2]{\bap@mm@mt},
            bottom \pgfmathprintnumber[fixed,precision=2]{\bap@mm@mb} mm}%
           \quad{\color{green!60!black}text border: green dashed}};
      \fi
    \end{tikzpicture}%
  \fi
}
\makeatother
\makeatletter

% -------------------------------------------------------------
% HYPERREF AND BOOKMARKS (must come last)
% -------------------------------------------------------------
\ifbap@hyperref
  \RequirePackage[hidelinks]{hyperref}
  \RequirePackage{bookmark}
\else
  % \phantomsection is used by the structural and bleed macros;
  % provide a no-op fallback when hyperref is not loaded here.
  \providecommand{\phantomsection}{}
\fi

% -------------------------------------------------------------
% APPLY DEFAULT CONFIGURATION
% -------------------------------------------------------------
\setkeys{bap}{
  trimwidth=170mm,
  trimheight=240mm,
  bleed=3mm,
  top=20mm,
  bottom=20mm,
  inner=15mm,
  outer=12mm,
  bindingoffset=5mm,
  headheight=14pt,
  headsep=13mm,
  footskip=13mm,
  stretch=1.15,
  parindent=1.5em,
  parskip=0pt,
  emergencystretch=1.5em,
  captionfont=footnotesize,
  captionskip=3pt,
  captionmargin=0pt,
  bleedcaptionskip=6mm
}
\bap@applygeometry
\bap@applytypography
% Default image search path (additive: other paths still work).
\graphicspath{{./img/}}
\ifbap@marks
  \showBleedMargin
\fi
\endinput