\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{PrimeTeX/packages/Boxout}[2025-08-20]

\RequirePackage{PrimeTeX/packages/Layout}
\RequirePackage{PrimeTeX/packages/Color}
\RequirePackage{PrimeTeX/packages/Tables}
\RequirePackage{calc}

\ProvideLength{\boxoutpadding}[1em]
\ProvideLength{\boxoutrule}[1pt]

\NewTblrEnviron{tblrBoxout}
\SetTblrInner[tblrBoxout]{
	cells		= {boxoutBG},
	hborder{1}	= {belowspace=\boxoutpadding},
	hborder{Z}	= {abovespace=\boxoutpadding},
	hlines		= {0pt,boxoutBG},
	hline{1,Z}	= {\boxoutrule,boxoutFG},
	%row{1}		= {font={\bfseries\sbfamily}},
	vborder{1}	= {rightspace=\boxoutpadding},
	vborder{Z}	= {leftspace=\boxoutpadding},
	vlines		= {0pt,boxoutBG},
	vline{1,Z}	= {\boxoutrule,boxoutFG},
}

\NewDocumentEnvironment{@boxout}{
	m m +b
}{
	\label{box:#1}%
	\begin{tblrBoxout}{#2}%
		#3%
	\end{tblrBoxout}%
}{}

\NewDocumentEnvironment{Boxout}{
	% #1: Label, passed to @boxout argument #1.
	>{\TrimSpaces}m
	% #2: Tabularray colspec, passed to @boxout argument #2.
	O{colspec={X[l,h]}}
	% #3: Caption.
	m
	% #4: [Ww] for warning box.
	o
	% #5: Body, passed to @boxout.
	+b
}{%
	\ifthenelse{\equal{#4}{w}\OR\equal{#4}{W}}{%
		\colorlet{boxoutBG}{warningBG}%
		\colorlet{boxoutFG}{warningFG}%
	}{}%
	\IfBlankTF{#3}{%
		\begin{@boxout}{#1}{#2}{}%
			\setlength{\parskip}{\medskipamount}%
			#5\\%
		\end{@boxout}%
	}{%
		\begin{@boxout}{#1}{#2}%
			{\Centering\sbfamily\bfseries #3}\\%
			\setlength{\parskip}{\medskipamount}%
			#5\\%
		\end{@boxout}%
	}%
}{}

\ExplSyntaxOn
\NewDocumentEnvironment{BigBoxout}{
	% #1: Overhang, passed to BigFloat argument #1.
	O{\c_BigFloat_overhang_dim}
	% #2: Float placement, passed to BigFloat argument #2.
	O{h,t,p,b}
	% #3: Offset ratio, passed to BigFloat argument #3.
	O{\c_BigFloat_offset_fp}
	% #4: Label, passed to Boxout argument #1.
	>{\TrimSpaces}m
	% #5: Tabularray colspec, passed to Boxout argument #2.
	O{X[l,h]}
	% #6: Caption, passed to Boxout argument #3.
	m
	% #7: [Ww] for warning box, if present passed to Boxout argument #4.
	o
	% #8: Body, passed to Boxout.
	+b
}{
	\begin{BigFloat}[
		type		= generic,
		overhang	= #1,
		placement	= {#2},
		offset		= #3,
	]%
		\IfNoValueTF{#7}{%
			\begin{Boxout}{#4}[#5]{#6}%
				#8%
			\end{Boxout}%
		}{%
			\begin{Boxout}{#4}[#5]{#6}[#7]%
				#8%
			\end{Boxout}%
		}%
	\end{BigFloat}%
}{}
\ExplSyntaxOff

\NewDocumentEnvironment{WrapBoxout}{
	% position [l,r,i,o]
	O{o}
	% offset
	O{\marparwidth}
	% width
	O{3in}
	O{X[l,h]}
	>{\TrimSpaces}m
	m
	o
	+b
}{%
	\begin{wrapfigure}{#1}[#2]%
		\begin{minipage}{#3}%
			\begin{Boxout}[#4]{#5}{#6}[#7]%
				#8%
			\end{Boxout}%
		\end{minipage}%
	\end{wrapfigure}%
}{}