<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xi="http://www.w3.org/2001/XInclude"
    xmlns:tei="http://www.tei-c.org/ns/1.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xi xs">

    <xsl:param name="debug-xinclude" as="xs:boolean" select="true()"/>
    <xsl:output encoding="UTF-8" method="xhtml" />

    <!-- ============================================================ -->
    <!-- ENTRY POINT                                                  -->
    <!-- ============================================================ -->

    <xsl:template match="/" mode="#default">
        <!-- NOTE: no "as" attribute here – this forces classic RTF
             (temporary tree) construction, guaranteeing a single
             document node regardless of how many top-level items
             the sequence constructor produces internally. -->
        <xsl:variable name="expanded">
            <xsl:apply-templates select="." mode="xinclude"/>
        </xsl:variable>

        <xsl:if test="$debug-xinclude">
            <xsl:message>=== XInclude expansion complete ===</xsl:message>
        </xsl:if>

		<xsl:apply-templates select="$expanded" mode="processing"/>
        
        <!--   
        for debugging you can output the expanded but not transformed version with this:
        
        <xsl:copy-of select="$expanded" />
        
         -->
        

    </xsl:template>

    <!-- ============================================================ -->
    <!-- MODE "xinclude": IDENTITY TEMPLATE                            -->
    <!-- ============================================================ -->

    <xsl:template match="node() | @*" mode="xinclude">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" mode="xinclude"/>
        </xsl:copy>
    </xsl:template>

    <!-- ============================================================ -->
    <!-- PERMISSIVE MATCH: xi:include in correct namespace, OR         -->
    <!-- bare/unqualified <include href="textgrid:..">                 -->
    <!-- ============================================================ -->

    <xsl:template match="xi:include[starts-with(@href, 'textgrid:')]"
                  mode="xinclude">

        <xsl:if test="$debug-xinclude">
            <xsl:message>
                Found include candidate: name=<xsl:value-of select="name(.)"/>
                href=<xsl:value-of select="@href"/>
                in-namespace=<xsl:value-of select="namespace-uri(.) = 'http://www.w3.org/2001/XInclude'"/>
            </xsl:message>
        </xsl:if>

        <xsl:variable name="parse" select="(@parse, 'xml')[1]" as="xs:string"/>
        <xsl:variable name="raw-href" select="@href" as="xs:string?"/>

        <xsl:choose>
            <xsl:when test="not($raw-href)">
                <xsl:message terminate="yes">
                    include element without @href is not supported.
                </xsl:message>
            </xsl:when>
            <xsl:otherwise>
                <xsl:variable name="href"
                    select="resolve-uri($raw-href, base-uri(.))"
                    as="xs:anyURI"/>

                <xsl:if test="$debug-xinclude">
                    <xsl:message>
                        Resolved href=<xsl:value-of select="$href"/>
                        (base-uri was <xsl:value-of select="base-uri(.)"/>)
                    </xsl:message>
                </xsl:if>

                <xsl:choose>
                    <xsl:when test="$parse = 'text'">
                        <xsl:call-template name="xi-include-text">
                            <xsl:with-param name="href" select="$href"/>
                        </xsl:call-template>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:call-template name="xi-include-xml">
                            <xsl:with-param name="href" select="$href"/>
                        </xsl:call-template>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template name="xi-include-xml">
        <xsl:param name="href" as="xs:string"/>
        <xsl:choose>
            <xsl:when test="doc-available($href)">
                <xsl:variable name="doc" select="doc($href)" as="document-node()"/>

                <xsl:if test="$debug-xinclude">
                    <xsl:message>
                        Successfully fetched <xsl:value-of select="$href"/>,
                        root element = <xsl:value-of select="name($doc/*)"/>,
                        root namespace = <xsl:value-of select="namespace-uri($doc/*)"/>,
                        nested includes found = <xsl:value-of select="
                            count($doc//xi:include) +
                            count($doc//*[local-name()='include'][starts-with(@href,'textgrid:')])"/>
                    </xsl:message>
                    <xsl:if test="string(name($doc)) eq 'xsl:stylesheet '">
                    <xsl:message terminate="yes">
                    	ERROR: included element is xsl:stylesheet.
                	</xsl:message>
                    </xsl:if>
                </xsl:if>

                <xsl:apply-templates select="$doc/*" mode="xinclude"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:if test="$debug-xinclude">
                    <xsl:message>
                        ERROR: doc-available() returned false for href=<xsl:value-of select="$href"/>
                    </xsl:message>
                </xsl:if>
                <xsl:call-template name="xi-fallback">
                    <xsl:with-param name="href" select="$href"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>


    </xsl:template>

    <xsl:template name="xi-include-text">
        <xsl:param name="href" as="xs:string"/>
        <xsl:variable name="encoding" select="(@encoding, 'UTF-8')[1]" as="xs:string"/>

        <xsl:choose>
            <xsl:when test="unparsed-text-available($href, $encoding)">
                <xsl:value-of select="unparsed-text($href, $encoding)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="xi-fallback">
                    <xsl:with-param name="href" select="$href"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <xsl:template name="xi-fallback">
        <xsl:param name="href" as="xs:string"/>

        <xsl:choose>
            <xsl:when test="xi:fallback | *[local-name()='fallback']">
                <xsl:apply-templates select="(xi:fallback | *[local-name()='fallback'])/node()" mode="xinclude"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:message terminate="no">
                    XInclude resolution failed for href="<xsl:value-of select="$href"/>"
                    and no fallback was provided.
                </xsl:message>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    
    <!-- ============================================================ -->
    <!-- MODE "processing": IDENTITY TEMPLATE                         -->
    <!-- ============================================================ --> 

    <xsl:template match="node() | @*" mode="processing">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" mode="processing"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="@type" mode="processing">
      <xsl:attribute name="class" select="string(.)" />
    </xsl:template>
    <!-- Convert @type on TEI divs into @class -->
	<xsl:template match="tei:div/@type" mode="processing" priority="10">
	  <xsl:attribute name="class" select="."/>
	</xsl:template>
    <xsl:template match="*/@xml:id" mode="processing">
      <xsl:attribute name="id" select="string(.)" />
    </xsl:template>
    
    <!-- ============           Ignored Nodes            ============ -->
    <xsl:template match="processing-instruction()"  mode="processing" />
    <xsl:template match="tei:teiHeader" mode="processing" />
	<xsl:template match="tei:pb" mode="processing" />
	
	<!-- ============           Passed Nodes            ============ -->
    <xsl:template match="tei:TEI|tei:text"  mode="processing">
    	<xsl:apply-templates mode="processing"/>
    </xsl:template>

    <!-- ============================================================ -->
    <!-- PROCESSING LOGIC GOES HERE                                   -->
    <!-- ============================================================ -->
    <!-- ============       HTML base     ============ -->
      <xsl:template match="/" mode="processing">
      <html>
      <head>
        <meta charset="utf-8"/>
        <title><xsl:value-of select="/tei:TEI/tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title/text()"/></title>
        <style type="text/css"><![CDATA[
@font-face {
  font-family: "SourceSerif4";
  src: url("https://textgridlab.org/1.0/tgcrud/rest/textgrid:4n14q/data?sessionId=SzYVMzGaCegAVFEe4fN3I0C7Da3nX1gFQ6qfZh5UCIuua1PsDSs3SXx6cL7TLAnXxFzmgJt1785317261973899") format("woff2");
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  /* optional but recommended */
}

.tei .docTitle {
  font-size: xxx-large;
  text-align: center;
}

.tei .titlePage #figure_0 p {
  text-align: right;
}

.tei .ornament {
  text-align: center;
}

.tei .head {
  font-weight: 700;
  font-size: 1.2rem;
  margin: 0 0 0.5rem 0;
  text-align: center;
}

.tei #figure_1 p, .tei #figure_2 p, .tei #figure_3 p {
  font-size: 128px;
  text-align: center;
}

.tei p {
  margin: 0.5rem 0;
  text-align: justify;
}

.tei .book {
  margin-top: 60px;
}

.tei .section {
  margin-top: 30px;
}

.tei {
  font-family: "SourceSerif4", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  line-height: 1.35;
  margin: 2rem;
  max-width: 70rem;
}

.tei .div {
  margin: 1rem 0;
  padding: 0.75rem 1rem;
  border-left: 4px solid #444;
  background: #fafafa;
}

.tei .head {
  font-weight: 700;
  font-size: 1.2rem;
  margin: 0 0 0.5rem 0;
}

.tei p {
  margin: 0.5rem 0;
}

.tei .include {
  margin: 0.75rem 0;
  padding: 0.5rem 0.75rem;
  background: #fff3cd;
  border: 1px solid #ffeeba;
  border-radius: 0.25rem;
}

.tei .include code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
}

.tei .meta {
  color: #555;
  font-size: 0.95rem;
}

.tei h1 {
  font-size: large;
}

#ds1\.3\.3 {
  font-size: smaller;
  text-align: right;
}


/* TOC container */
.tei .toc{
  margin: 1.5rem 0;
  padding: 0.75rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background: #fff;
}

/* Collapsible header */
.tei .toc details > summary{
  cursor: pointer;
  list-style: none;            /* Firefox */
  display: flex;
  align-items: center;
  gap: .5rem;
  user-select: none;
  padding: .25rem 0;
}

/* Remove default marker */
.tei .toc details > summary::-webkit-details-marker{ display:none; }

/* Custom chevron */
.tei .toc details > summary::before{
  content: "▸";
  display: inline-block;
  width: 1em;
  color: #374151;
  transition: transform .15s ease;
}
.tei .toc details[open] > summary::before{
  transform: rotate(90deg);
}

/* Style the H1 inside summary */
.tei .toc summary h1{
  margin: 0;
  font-size: 1rem;
  letter-spacing: .02em;
}

/* The list */
.tei .toc ul{
  margin: .75rem 0 0 0;
  padding-left: 1.25rem;
}
.tei .toc li{
  margin: .15rem 0;
  line-height: 1.25;
}
.tei .toc li > a{
  color: #1f2937;
  text-decoration: none;
  border-radius: 6px;
  padding: .15rem .25rem;
  display: inline-block;
}
.tei .toc li > a:hover{
  background: #f3f4f6;
  text-decoration: underline;
}

/* Sublevels: slightly lighter + tighter */
.tei .toc ul ul{
  margin-top: .15rem;
  padding-left: 1.1rem;
  border-left: 1px solid #eef2f7;
}
.tei .toc ul ul > li > a{
  color: #374151;
}

/* Accessibility: visible focus */
.tei .toc a:focus-visible,
.tei .toc summary:focus-visible{
  outline: 2px solid #2563eb;
  outline-offset: 2px;
}

]]></style>
      </head>
      <body>
        <div class="tei">
          <xsl:apply-templates select="tei:TEI/tei:text/tei:front" mode="front"/>
          <div class="toc">
            <details>
			    <summary><span>Inhaltsverzeichnis</span></summary>
			    <ul>
          			<xsl:apply-templates select="tei:TEI/tei:text/tei:body | tei:div" mode="toc" />
			    </ul>
			  </details>
          </div>
          <xsl:apply-templates select="node() except tei:TEI/tei:text/tei:front" mode="processing"/>
        </div>
      </body>
    </html>
      </xsl:template>
	<!-- ============ Structural elements ============ -->
	  <xsl:template match="tei:front" mode="processing" />
	  <xsl:template match="tei:front" mode="front">
	      <div class="front">
	          <xsl:apply-templates mode="processing"/>
	      </div>
	  </xsl:template>
	
	  <xsl:template match="tei:titlePage" mode="processing">
	      <div class="titlePage">
	          <xsl:apply-templates mode="processing"/>
	          <div class="ornament">✳ ✳ ✳</div>
	      </div>
	  </xsl:template>
	
	  <xsl:template match="tei:docTitle" mode="processing">
	      <div class="docTitle">
	          <xsl:apply-templates/>
	      </div>
	  </xsl:template>
	
	  <xsl:template match="tei:titlePart[@type='main']" mode="processing">
	      <div class="main-title">
	          <xsl:apply-templates mode="processing"/>
	      </div>
	  </xsl:template>
	  
	  <xsl:template match="tei:head" mode="processing">
		  <div class="head">
		  	<xsl:apply-templates select="./@* | ./node()" mode="processing"/>
		  </div>
	  </xsl:template>
	  
	  <xsl:template match="tei:div" mode="processing">
		  <div class="div">
		    <xsl:attribute name="id">
		      <xsl:call-template name="div-id">
		        <xsl:with-param name="d" select="."/>
		      </xsl:call-template>
		    </xsl:attribute>
		
		    <xsl:apply-templates select="@* except @xml:id" mode="processing"/>
		    <xsl:apply-templates select="node()" mode="processing"/>
		  </div>
		</xsl:template>
	
	  <!-- ============ Figure with Hebrew motto ============ -->
	  <xsl:template match="tei:figure" mode="processing">
	      <div class="figure">
	          <xsl:if test="@xml:id">
	              <xsl:attribute name="id" select="@xml:id"/>
	          </xsl:if>
	          <xsl:apply-templates mode="processing"/>
	      </div>
	  </xsl:template>
	
	  <xsl:template match="tei:figure/tei:p" mode="processing">
	      <p>
	          <xsl:if test="@xml:lang">
	              <xsl:attribute name="lang" select="@xml:lang"/>
	          </xsl:if>
	          <xsl:apply-templates mode="processing"/>
	      </p>
	  </xsl:template>

    <!-- ============================================================ -->
    <!-- MODE "toc": TABLE OF CONTENT                                 -->
    <!-- ============================================================ --> 

	<xsl:template name="div-id">
	  <xsl:param name="d" as="element(tei:div)"/>
	
	  <xsl:choose>
	    <xsl:when test="$d/@xml:id">
	      <xsl:value-of select="string($d/@xml:id)"/>
	    </xsl:when>
	    <xsl:otherwise>
	      <xsl:value-of select="concat('div-', generate-id($d))"/>
	    </xsl:otherwise>
	  </xsl:choose>
	</xsl:template>
	
	<xsl:template match="tei:div" mode="toc">
	  <li>
	    <a>
	      <xsl:attribute name="href">
	        <xsl:text>#</xsl:text>
	        <xsl:call-template name="div-id">
	          <xsl:with-param name="d" select="."/>
	        </xsl:call-template>
	      </xsl:attribute>
	
	      <xsl:value-of select="
	        if (tei:head) then normalize-space(string((tei:head)[1]))
	        else '[untitled]'
	      "/>
	    </a>
	
	    <xsl:if test="tei:div">
	      <ul>
	        <xsl:apply-templates select="./tei:div" mode="toc"/>
	      </ul>
	    </xsl:if>
	  </li>
	</xsl:template>

</xsl:stylesheet>