% Copyright 2026 Open-Guji (https://github.com/open-guji)
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
% banxin.sty
% 古籍版心与鱼尾功能支持
% 这是 luatex_cn 的子包
%
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{luatex-cn-banxin}[2026/01/19 v0.1.1 Ancient Book Banxin Support]

\RequirePackage{expl3}
\RequirePackage{xparse}

\ExplSyntaxOn

% --- Compatibility Mode Logic ---
% 1. Book Name / Title Synchronization
\cs_if_exist:NTF \title
  {
    \NewCommandCopy \__banxin_orig_title \title
    \RenewDocumentCommand \title { m }
      {
        \__banxin_orig_title { #1 }
        \keys_set:nn { vertical } { book-name = { #1 } }
      }
  }
  {
    \NewDocumentCommand \title { m }
      {
        \gdef\@title{#1}
        \keys_set:nn { vertical } { book-name = { #1 } }
      }
  }

% Fallback: Sync from \@title at the start of the document if set by other means
\AddToHook{begindocument/before}{
  \cs_if_exist:NT \@title {
    \tl_if_empty:NF \@title {
      \keys_set:nn { vertical } { book-name = { \@title } }
    }
  }
}

% 2. Chapter Title Synchronization
\cs_if_exist:NTF \chapter
  {
    \NewCommandCopy \__banxin_orig_chapter \chapter
    \RenewDocumentCommand \chapter { s o m }
      {
        \IfBooleanTF {#1}
          { \__banxin_orig_chapter* {#3} }
          {
            \IfNoValueTF {#2}
              { \__banxin_orig_chapter {#3} }
              { \__banxin_orig_chapter [#2] {#3} }
          }
        \keys_set:nn { vertical } { chapter-title = { #3 } }
      }
  }
  {
    \NewDocumentCommand \chapter { m }
      {
        \keys_set:nn { vertical } { chapter-title = { #1 } }
      }
  }

% Setup command for banxin specific parameters
\NewDocumentCommand{\banxinSetup}{ m }
  {
    \keys_set:nn { vertical } { #1 }
  }

\ExplSyntaxOff

\endinput
