%% This is file `coloredtheorem.sty',
%%
%% Copyright (C) 2024 by João Lourenço <joao.lourenco@fct.unl.pt>
%%
%% This file 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 2006/05/20 or later.
%%
\NeedsTeXFormat{LaTeX2e}[2020/06/01]
\ProvidesPackage{coloredtheorem}
  [2024/09/15 v1.0.4 - A colorful boxed theorem environment]

\RequirePackage{tcolorbox}
\tcbuselibrary{breakable}

\gdef\tcbth{cth}

\expandafter\NewDocumentCommand\csname\tcbth newtheorem\endcsname { m m O{} }{%
  \expandafter\newcounter\expandafter{\tcbth#1}%
  \expandafter\gdef\csname\tcbth#1name\endcsname{#2}%
  \expandafter\gdef\csname\tcbth list#1name\endcsname{List of #2s}%
  \expandafter\gdef\csname#1autorefname\endcsname{#2}%
  \AtEndPreamble{%
      \ifdefined\crefname\expandafter\crefname\expandafter{\tcbth#1}{#2}{#2s}\fi}%
  \expandafter\gdef\csname\tcbth listof#1s\endcsname
  {%
    \ifdefined\chapter\chapter*{\csname\tcbth list#1name\endcsname}%
        \else\section*{\csname\tcbth list#1name\endcsname}\fi%
    \expandafter\@starttoc\expandafter{lo#1}%
  }
  \expandafter\NewDocumentEnvironment\expandafter{\tcbth#1} {O{} m O{}}%
  {% \begin{tcb<SOMETHING>}
    \begin{center}%
      \ifx\relax##2\relax
      \else
        \expandafter\refstepcounter\expandafter{\tcbth#1}%
        \ifx\relax##1\relax
          \expandafter\addcontentsline\expandafter{lo#1}{subsection}
                        {\protect\numberline{\csname the\tcbth#1\endcsname}##2}%
        \else
          \expandafter\addcontentsline\expandafter{lo#1}{subsection}
                        {\protect\numberline{\csname the\tcbth#1\endcsname}##1}%
        \fi
      \fi
      \begin{tcolorbox}[breakable,
                        title={\textbf{\csname\tcbth#1name\endcsname
                               \ifx\relax##2\relax\else
                                   ~\csname the\tcbth#1\endcsname\fi}~~##2},
                        #3, ##3,
                       ]%
      \let\origpar=\par%
      \def\par{\origpar\medskip}%
      \ignorespaces%
  }{% \end{tcb<SOMETHING>}
       \end{tcolorbox}%
     \end{center}%
  }%
}
