<div id="fb3d-ctx" class="flip-book">
  <div class="view">
    <div class="fnav">
      <div class="prev">
        <a class="cmdBackward but-show" href="/#"><span class="icon previous-page-icon">
            <svg title="<$tr>Previous page</$tr>" width="28.947" height="49.999" viewBox="0 0 28.947 49.999" fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <path
                d="M1.372 22.096a4.12 4.12 0 0 0 0 5.821l20.559 20.559a4.118 4.118 0 0 0 5.821-5.821L10.097 25 27.739 7.345a4.118 4.118 0 0 0-5.821-5.821L1.359 22.083z"
                fill="#666" />
            </svg>
          </span></a>
      </div>
      <div class="next">
        <a class="cmdForward but-show" href="/#"><span class="icon next-page-icon">
            <svg title="<$tr>Next page</$tr>" width="29.605" height="50" viewBox="0 0 29.605 50" fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <path
                d="M27.904 22.096a4.12 4.12 0 0 1 0 5.821L7.345 48.476a4.118 4.118 0 0 1-5.821-5.821L19.179 25 1.537 7.345a4.118 4.118 0 0 1 5.821-5.821l20.559 20.559z"
                fill="#666" />
            </svg>

          </span></a>
      </div>
    </div>
    <div class="widLoadingProgress loading-progress hidden">
      <div class="progress">
      </div>
      <div class="txtLoadingProgress caption">
      </div>
    </div>
    <div class="widLoading page-loading hidden">
    </div>
  </div>

  <div class="widFloatWnd float-wnd hidden">
    <div class="header">
      <$tr>Table of contents</$tr>
      <a href="/#" title="<$tr>Close</$tr>" class="close cmdCloseToc">
        <span class="icon">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M18.249 4.385a1.709 1.709 0 0 0-2.413-2.412l-5.609 5.614-5.614-5.609A1.709 1.709 0 0 0 2.2 4.391L7.815 10l-5.61 5.615a1.709 1.709 0 0 0 2.413 2.412l5.609-5.615 5.615 5.609a1.709 1.709 0 0 0 2.413-2.413L12.64 10z"
              fill="#fff" />
          </svg>

        </span>
      </a>
    </div>
    <div class="body">
      <div class="ctrl">
        <div class="toc">
          <div class="toc-menu widTocMenu">
            <ul>
              <li class="cmdBookmarks"><a href="/#">
                  <$tr>Bookmarks</$tr>
                </a></li>
              <li class="cmdThumbnails"><a href="/#">
                  <$tr>Thumbnails</$tr>
                </a></li>
              <li class="cmdSearch"><a href="/#">
                  <$tr>Search</$tr>
                </a></li>
            </ul>
          </div>
          <div class="widBookmarks toc-view">

          </div>
          <div class="widThumbnails toc-view">

          </div>
          <div class="widSearch toc-view">

          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="controls">

    <div class="ctrl js-center">
      <nav class="fnavbar">
        <ul class="fnav">

          <li class="fnav-item cmdZoomIn"><a href="/#"><span class="icon">
                <svg title="<$tr>Zoom in</$tr>" width="30" height="30" viewBox="0 0 30 30" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M24.375 12.188c0 2.689-.873 5.174-2.344 7.189l7.418 7.424c.732.732.732 1.922 0 2.654s-1.922.732-2.654 0l-7.418-7.424a12.1 12.1 0 0 1-7.189 2.344C5.455 24.375 0 18.92 0 12.188S5.455 0 12.188 0s12.188 5.455 12.188 12.188m-13.594 5.156c0 .779.627 1.406 1.406 1.406s1.406-.627 1.406-1.406v-3.75h3.75c.779 0 1.406-.627 1.406-1.406s-.627-1.406-1.406-1.406h-3.75v-3.75c0-.779-.627-1.406-1.406-1.406s-1.406.627-1.406 1.406v3.75h-3.75c-.779 0-1.406.627-1.406 1.406s.627 1.406 1.406 1.406h3.75z"
                    fill="#fff" />
                </svg>
              </span></a></li>
          <li class="fnav-item cmdZoomOut"><a href="/#"><span class="icon">
                <svg title="<$tr>Zoom out</$tr>" width="30" height="30" viewBox="0 0 30 30" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <g clip-path="url(#a)">
                    <path
                      d="M24.375 12.188c0 2.689-.873 5.174-2.344 7.189l7.418 7.424c.732.732.732 1.922 0 2.654s-1.922.732-2.654 0l-7.418-7.424a12.1 12.1 0 0 1-7.189 2.344C5.455 24.375 0 18.92 0 12.188S5.455 0 12.188 0s12.188 5.455 12.188 12.188M7.97 10.782c-.779 0-1.406.627-1.406 1.406s.627 1.406 1.406 1.406h8.438c.779 0 1.406-.627 1.406-1.406s-.627-1.406-1.406-1.406z"
                      fill="#fff" />
                  </g>
                  <defs>
                    <clipPath id="a">
                      <path fill="#fff" d="M0 0h30v30H0z" />
                    </clipPath>
                  </defs>
                </svg>
              </span></a></li>
          <li class="fnav-item cmdDefaultZoom but-show"><a href="/#"><span class="icon">

                <svg title="<$tr>Fit view</$tr>" width="30" height="30" viewBox="0 0 30 30" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M.005.005v7.498h1.874V1.879h5.623V.005zm28.116 22.493v5.623h-5.623v1.874h7.498v-7.497zM29.995.005v7.498h-1.874V1.879h-5.623V.005zM1.879 22.498v5.623h5.623v1.874H.005v-7.497z"
                    fill="#fff" />
                  <path fill-rule="evenodd" clip-rule="evenodd"
                    d="M5.628 5.628v18.744h18.744V5.628zm1.874 1.874h14.995v14.995H7.502z" fill="#fff" />
                </svg>

              </span></a></li>
          <li class="fnav-item cmdToc"><a href="/#"><span class="icon">
                <svg title="<$tr>Table of contents</$tr>" width="30" height="40" viewBox="0 0 30 40" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M0 3.75v34.352a1.9 1.9 0 0 0 2.992 1.554L15 31.25l12.008 8.406A1.9 1.9 0 0 0 30 38.102V3.75C30 1.68 28.32 0 26.25 0H3.75C1.68 0 0 1.68 0 3.75"
                    fill="#fff" />
                </svg>
              </span></a></li>

          <!-- <li class="fnav-item cmdFastBackward"><a href="/#"><span class="icon icon-backward">
            <svg title="<$tr>10 pages backward</$tr>" width="30" height="17" viewBox="0 0 30 17" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M0 0L10.6105 8.11579L0 16.2316V0ZM13.7368 0L24.3789 8.11579L13.7368 16.2316V0ZM26.2421 0.631578H30V15.6316H26.2421V0.631578Z" fill="white"/>
              </svg>
          </span></a></li> -->


          <li class="fnav-item cmdBackward"><a href="/#"><span class="icon">
                <svg class="rotate-180" width="25" height="17" viewBox="0 0 25 17" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path d="M0 0L10.6105 8.11579L0 16.2316V0ZM13.7368 0L24.3789 8.11579L13.7368 16.2316V0Z"
                    fill="white" />
                </svg>
              </span></a></li>

          <li class="fnav-item">
            <div class="pages">
              <input type="text" class="number inpPage" maxlength="4" placeholder="1">
              <input type="text" class="amount inpPages" readOnly maxlength="4" placeholder="1">
            </div>
          </li>
          <li class="fnav-item cmdForward"><a href="/#"><span class="icon">
                <svg title="<$tr>Next page</$tr>" width="25" height="17" viewBox="0 0 25 17" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path d="M0 0L10.6105 8.11579L0 16.2316V0ZM13.7368 0L24.3789 8.11579L13.7368 16.2316V0Z"
                    fill="white" />
                </svg>
              </span></a></li>

          <!-- <li class="fnav-item cmdFastForward"><a href="/#"><span class="icon">
            <svg title="<$tr>10 pages forward</$tr>" width="30" height="17" viewBox="0 0 30 17" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M0 0L10.6105 8.11579L0 16.2316V0ZM13.7368 0L24.3789 8.11579L13.7368 16.2316V0ZM26.2421 0.631578H30V15.6316H26.2421V0.631578Z" fill="white"/>
              </svg>
              
          </span></a></li> -->

          <li class="fnav-item but-show cmdDownload"><a id="download-pdf" href="/#"><span class="icon">
                <svg title="<$tr>Download</$tr>" width="20" height="20" viewBox="0 0 20 20" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M11.25 1.25a1.25 1.25 0 1 0-2.5 0v9.48L5.883 7.863a1.252 1.252 0 0 0-1.77 1.77l5 5a1.253 1.253 0 0 0 1.77 0l5-5a1.252 1.252 0 0 0-1.77-1.77L11.25 10.73zM2.5 13.75a2.5 2.5 0 0 0-2.5 2.5v1.25C0 18.879 1.121 20 2.5 20h15c1.379 0 2.5-1.121 2.5-2.5v-1.25c0-1.379-1.121-2.5-2.5-2.5h-3.965l-1.77 1.77a2.5 2.5 0 0 1-3.535 0l-1.765-1.77zm14.375 2.188c.249 0 .487.099.663.275a.94.94 0 0 1 0 1.326.94.94 0 0 1-1.326 0 .94.94 0 0 1 0-1.326.94.94 0 0 1 .663-.275"
                    fill="#fff" />
                </svg>
              </span></a></li>
          <li class="fnav-item cmdPrint"><a href="/#"><span class="icon">
                <svg title="<$tr>Print</$tr>" width="30" height="30" viewBox="0 0 30 30" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <g clip-path="url(#a)">
                    <path
                      d="M7.5 0a3.754 3.754 0 0 0-3.75 3.75v5.625H7.5V3.75h13.283L22.5 5.467v3.908h3.75V5.467c0-.996-.393-1.951-1.096-2.654l-1.716-1.717A3.76 3.76 0 0 0 20.783 0zm15 20.625v5.625h-15v-5.625zm3.75 1.875h1.875A1.873 1.873 0 0 0 30 20.625V15a3.755 3.755 0 0 0-3.75-3.75H3.75A3.754 3.754 0 0 0 0 15v5.625C0 21.662.838 22.5 1.875 22.5H3.75v3.75A3.754 3.754 0 0 0 7.5 30h15a3.755 3.755 0 0 0 3.75-3.75zm-.938-7.969a1.406 1.406 0 1 1 0 2.812 1.406 1.406 0 0 1 0-2.812"
                      fill="#fff" />
                  </g>
                  <defs>
                    <clipPath id="a">
                      <path fill="#fff" d="M0 0h30v30H0z" />
                    </clipPath>
                  </defs>
                </svg>

              </span></a></li>
          <li class="fnav-item cmdFullScreen"><a href="/#"><span class="icon">
                <svg title="<$tr>Full screen</$tr>" width="20" height="20" viewBox="0 0 20 20" fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M1.429 0C.638 0 0 .638 0 1.429v4.286c0 .79.638 1.429 1.429 1.429s1.429-.638 1.429-1.429V2.857h2.857A1.427 1.427 0 1 0 5.714 0zm1.429 14.286c0-.79-.638-1.429-1.429-1.429S0 13.496 0 14.286v4.286c0 .79.638 1.429 1.429 1.429h4.286c.79 0 1.429-.638 1.429-1.429s-.638-1.429-1.429-1.429H2.857zM14.286 0c-.79 0-1.429.638-1.429 1.429s.638 1.429 1.429 1.429h2.857v2.857c0 .79.638 1.429 1.429 1.429s1.429-.638 1.429-1.429V1.429c0-.79-.638-1.429-1.429-1.429zM20 14.286c0-.79-.638-1.429-1.429-1.429s-1.429.638-1.429 1.429v2.857h-2.857c-.79 0-1.429.638-1.429 1.429s.638 1.429 1.429 1.429h4.286c.79 0 1.429-.638 1.429-1.429z"
                    fill="#fff" />
                </svg>

              </span></a></li>

          <li class="dropup fnav-item toggle widSettings">
            <a href="/#">
              <div class="icon-caret"><span class="icon">

                  <svg width="112" height="432" viewBox="0 0 112 432" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path
                      d="M56 320C41.1479 320 26.9041 325.9 16.402 336.402C5.89998 346.904 0 361.148 0 376C0 390.852 5.89998 405.096 16.402 415.598C26.9041 426.1 41.1479 432 56 432C70.8521 432 85.0959 426.1 95.598 415.598C106.1 405.096 112 390.852 112 376C112 361.148 106.1 346.904 95.598 336.402C85.0959 325.9 70.8521 320 56 320ZM56 160C41.1479 160 26.9041 165.9 16.402 176.402C5.89998 186.904 0 201.148 0 216C0 230.852 5.89998 245.096 16.402 255.598C26.9041 266.1 41.1479 272 56 272C70.8521 272 85.0959 266.1 95.598 255.598C106.1 245.096 112 230.852 112 216C112 201.148 106.1 186.904 95.598 176.402C85.0959 165.9 70.8521 160 56 160ZM112 56C112 41.1479 106.1 26.9041 95.598 16.402C85.0959 5.89998 70.8521 0 56 0C41.1479 0 26.9041 5.89998 16.402 16.402C5.89998 26.9041 0 41.1479 0 56C0 70.8521 5.89998 85.0959 16.402 95.598C26.9041 106.1 41.1479 112 56 112C70.8521 112 85.0959 106.1 95.598 95.598C106.1 85.0959 112 70.8521 112 56Z"
                      fill="white" />
                  </svg>

                </span></div>
            </a>

            <ul class="menu hidden">
              <li class="cmdSmartPan"><a href="/#"><span class="icon">
                    <svg width="25.714" height="20" viewBox="0 0 25.714 20" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M12.857 2.143c-2.911 0-5.304 1.321-7.138 3.022C4 6.763 2.812 8.661 2.205 10c.607 1.339 1.795 3.236 3.509 4.835 1.839 1.701 4.232 3.022 7.143 3.022s5.304-1.321 7.138-3.022c1.719-1.599 2.907-3.496 3.514-4.835-.607-1.339-1.795-3.237-3.509-4.835-1.839-1.701-4.232-3.022-7.143-3.022M4.259 3.598C6.362 1.643 9.25 0 12.857 0s6.495 1.643 8.598 3.598c2.089 1.942 3.487 4.259 4.152 5.853.147.353.147.746 0 1.098-.665 1.594-2.062 3.915-4.152 5.853C19.352 18.357 16.464 20 12.857 20s-6.495-1.643-8.598-3.598C2.17 14.464.772 12.143.112 10.549a1.42 1.42 0 0 1 0-1.098c.66-1.594 2.058-3.915 4.147-5.853m8.598 9.973c1.973 0 3.571-1.598 3.571-3.571s-1.598-3.571-3.571-3.571h-.089a2.86 2.86 0 0 1-3.482 3.482V10a3.57 3.57 0 0 0 3.571 3.571m0-9.286a5.7 5.7 0 0 1 4.041 1.674 5.714 5.714 0 0 1 0 8.081 5.714 5.714 0 0 1-8.081 0 5.714 5.714 0 0 1 0-8.081 5.7 5.7 0 0 1 4.04-1.673"
                        fill="#fff" />
                    </svg>
                  </span>
                  <$tr>Smart pan</$tr>
                </a></li>
              <li class="cmdSinglePage"><a href="/#"><span class="icon">
                    <svg width="15" height="20" viewBox="0 0 15 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <g clip-path="url(#a)">
                        <path
                          d="M2.5 18.125a.627.627 0 0 1-.625-.625v-15c0-.344.281-.625.625-.625h6.25V5c0 .692.558 1.25 1.25 1.25h3.125V17.5a.627.627 0 0 1-.625.625zM2.5 0A2.5 2.5 0 0 0 0 2.5v15C0 18.879 1.121 20 2.5 20h10c1.379 0 2.5-1.121 2.5-2.5V6.035a2.5 2.5 0 0 0-.731-1.77L10.73.73A2.5 2.5 0 0 0 8.965 0zm2.188 10c-.519 0-.938.418-.938.938s.418.938.938.938h5.625c.519 0 .938-.418.938-.938S10.832 10 10.313 10zm0 3.75c-.519 0-.938.418-.938.938s.418.938.938.938h5.625c.519 0 .938-.418.938-.938s-.418-.938-.938-.938z"
                          fill="#fff" />
                      </g>
                      <defs>
                        <clipPath id="a">
                          <path fill="#fff" d="M0 0h15v20H0z" />
                        </clipPath>
                      </defs>
                    </svg></span>
                  <$tr>Single page</$tr>
                </a></li>
              <li class="cmdSounds"><a href="/#"><span class="icon sound-icon">
                    <svg width="25" height="20" viewBox="0 0 25 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M20.844 1.27C23.379 3.328 25 6.477 25 10s-1.621 6.668-4.156 8.73c-.402.328-.992.266-1.32-.137s-.266-.992.137-1.32c2.117-1.719 3.465-4.336 3.465-7.273s-1.348-5.555-3.465-7.277c-.402-.328-.461-.918-.137-1.32s.918-.461 1.32-.137zM18.48 4.18c1.688 1.375 2.77 3.473 2.77 5.82s-1.082 4.445-2.77 5.82c-.402.328-.992.266-1.32-.137s-.266-.992.137-1.32c1.269-1.031 2.078-2.601 2.078-4.363s-.809-3.332-2.078-4.367c-.402-.328-.461-.918-.137-1.32s.918-.461 1.32-.137zm-2.363 2.91a3.755 3.755 0 0 1 0 5.82c-.402.328-.992.266-1.32-.137s-.266-.992.137-1.32c.421-.344.691-.867.691-1.453s-.27-1.109-.691-1.457c-.402-.328-.461-.918-.137-1.32s.918-.461 1.32-.137zm-4.355-5.731c.449.204.738.649.738 1.141v15c0 .492-.289.938-.738 1.141s-.977.121-1.344-.207l-5.27-4.684H2.5a2.5 2.5 0 0 1-2.5-2.5v-2.5c0-1.379 1.121-2.5 2.5-2.5h2.648l5.27-4.684a1.26 1.26 0 0 1 1.344-.207"
                        fill="#fff" />
                    </svg>
                  </span>
                  <$tr>Sounds</$tr>
                </a></li>
              <li class="cmdStats"><a href="/#"><span class="icon">
                    <svg width="22.857" height="20" viewBox="0 0 22.857 20" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M2.857 1.429C2.857 0.638 2.219 0 1.429 0S0 0.638 0 1.429v15c0 1.973 1.598 3.571 3.571 3.571h17.857c0.79 0 1.429 -0.638 1.429 -1.429s-0.638 -1.429 -1.429 -1.429H3.571c-0.393 0 -0.714 -0.321 -0.714 -0.714zm18.152 3.866c0.558 -0.558 0.558 -1.464 0 -2.022s-1.464 -0.558 -2.022 0L14.286 7.978l-2.562 -2.562c-0.558 -0.558 -1.464 -0.558 -2.022 0l-5 5c-0.558 0.558 -0.558 1.464 0 2.022s1.464 0.558 2.022 0l3.991 -3.987 2.562 2.562c0.558 0.558 1.464 0.558 2.022 0l5.714 -5.714z"
                        fill="#fff" />
                    </svg>
                  </span>
                  <$tr>Stats</$tr>
                </a></li>
              <!-- <li class="divider"></li> -->
              <!-- <li class="cmdLightingUp"><a href="/#"><span class="icon arrow-icon">
                    <svg width="35.019" height="20" viewBox="0 0 35.019 20" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M15.751.732a2.493 2.493 0 0 1 3.525 0l14.941 14.941a2.493 2.493 0 0 1-3.525 3.525L17.509 6.015 4.327 19.19a2.493 2.493 0 0 1-3.525-3.525L15.743.724z"
                        fill="#fff" />
                    </svg>
                  </span>
                  <$tr>Increase lighting</$tr>
                </a></li>
              <li class="cmdLightingDown"><a href="/#"><span class="icon arrow-icon">
                    <svg width="35.019" height="20" viewBox="0 0 35.019 20" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M15.751 19.268c0.973 0.973 2.552 0.973 3.525 0l14.941 -14.941c0.973 -0.973 0.973 -2.552 0 -3.525s-2.552 -0.973 -3.525 0L17.509 13.984 4.327 0.809c-0.973 -0.973 -2.552 -0.973 -3.525 0s-0.973 2.552 0 3.525l14.941 14.941z"
                        fill="#fff" />
                    </svg>
                  </span>
                  <$tr>Reduce lighting</$tr>
                </a></li> -->
            </ul>
          </li>
        </ul>
      </nav>
    </div>

  </div>
</div>


<script>

  const adjustHexColor = (hexColor, percentage) => {
    if (!hexColor || typeof hexColor !== 'string' || !hexColor.startsWith('#') || hexColor.length < 4) {
      return hexColor || '#38383d';
    }
    // Convert hex color to RGB values
    const r = parseInt(hexColor.slice(1, 3), 16);
    const g = parseInt(hexColor.slice(3, 5), 16);
    const b = parseInt(hexColor.slice(5, 7), 16);

    // Calculate adjusted RGB values
    const adjustment = Math.round((percentage / 100) * 255);
    const newR = Math.max(Math.min(r + adjustment, 255), 0);
    const newG = Math.max(Math.min(g + adjustment, 255), 0);
    const newB = Math.max(Math.min(b + adjustment, 255), 0);

    // Convert adjusted RGB values back to hex color
    const newHexColor = '#' + ((1 << 24) + (newR << 16) + (newG << 8) + newB).toString(16).slice(1);

    return newHexColor;
  }


  const getColorBrightness = (hexColor) => {
    if (!hexColor || typeof hexColor !== 'string' || !hexColor.startsWith('#') || hexColor.length < 4) {
      return 50;
    }
    const r = parseInt(hexColor.slice(1, 3), 16);
    const g = parseInt(hexColor.slice(3, 5), 16);
    const b = parseInt(hexColor.slice(5, 7), 16);

    // Convert the RGB color to HSL
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    const l = (max + min) / 2;

    // Calculate the brightness position in percentage
    const brightnessPercentage = Math.round(l / 255 * 100);

    return brightnessPercentage;
  }

  try {
    // Access the parent iframe from the nested iframe
    var parentIframe = window.parent.frameElement;

    // Check if the parentIframe exists
    if (parentIframe) {
      // Get the src attribute of the parent iframe
      var parentSrc = parentIframe.getAttribute("src");

      // Extract the data attribute from the src (assuming it's in the query string)
      var dataUrlParams = new URLSearchParams(new URL(parentSrc).search);
      var dataKey = dataUrlParams.get('key');
      var dataFile = dataUrlParams.get('file');

      var dataParams = atob(dataKey);

    } else {
      console.error('Parent iframe not found');
    }
  } catch (error) {
    console.error('An error occurred:', error);
  }

  // Step 2: Create URLSearchParams object
  const urlParams = new URLSearchParams(dataParams);

  // Step 3: Convert URLSearchParams to Object
  const params = {};
  for (const [key, value] of urlParams.entries()) {
    params[key] = (value === 'yes' || value === 'true') ? true : (value === 'no' || value === 'false' ? false : value);
  }


  // Ensure the DOM is fully loaded before manipulating it
  if (!(params?.toolbar)) {
    document.querySelector(".flip-book .controls")?.remove();
  }
  if (!(params?.download)) {
    document.querySelector("li.fnav-item.cmdDownload")?.remove();
    document.querySelector("li.fnav-item.cmdPrint")?.remove();
  }
  if (!(params?.presentation)) {
    document.querySelector("li.fnav-item.cmdFullScreen")?.remove();
  }
  if (!(params?.zoom_in)) {
    document.querySelector("li.fnav-item.cmdZoomIn")?.remove();
  }
  if (!(params?.zoom_out)) {
    document.querySelector("li.fnav-item.cmdZoomOut")?.remove();
  }
  if (!(params?.fit_view)) {
    document.querySelector("li.fnav-item.cmdDefaultZoom")?.remove();
  }
  if (!(params?.bookmark)) {
    document.querySelector("li.fnav-item.cmdToc")?.remove();
  }
  if (!(params?.sound)) {
    document.querySelector("li.cmdSounds")?.remove();
  }
  


  const flipBookElement = document.querySelector(".flip-book");
  const controlsElement = document.querySelector(".flip-book .controls");

  if (params?.flipbook_toolbar_position === 'top') {
    if (flipBookElement) {
      flipBookElement.classList.add('toolbar-position-top');
    }
    if (controlsElement) {
      controlsElement.classList.add('toolbar-position-top');
    }
  }
  else {
    if (controlsElement) {
      controlsElement.classList.add('toolbar-position-bottom');
    }
  }


  //Create theme mode function
  const setThemeMode = (themeMode) => {
    const htmlEL = document.getElementsByTagName("html")[0];
    if (htmlEL) {
      htmlEL.setAttribute('ep-data-theme', themeMode);
    }
  }


  setThemeMode(params.themeMode);


  const pdfIframeStyle = () => {
    const otherhead = document.getElementsByTagName("head")[0];

    const style = document.createElement("style");
    style.setAttribute('id', 'EBiframeStyleID');

    let pdfCustomColor = '';

    if (params.themeMode == 'custom') {

      if (!params.customColor) {
        params.customColor = '#38383d';
      }

      let colorBrightness = getColorBrightness(params.customColor);

      let iconsTextsColor = 'white';
      if (colorBrightness > 60) {
        iconsTextsColor = 'black';
      }

      pdfCustomColor = `[ep-data-theme=custom] {
          --body-bg-color: ${params.customColor};
          --toolbar-bg-color: ${adjustHexColor(params.customColor, 15)};
          --toolbar-icon-color: ${iconsTextsColor};
          --toolbar-active-icon-bg-color: ${adjustHexColor(params.customColor, 25)};
          --toolbar-item-hover-bg-color: ${adjustHexColor(params.customColor, 25)};
          --toolbar-current-page-number-bg-color: ${adjustHexColor(params.customColor, 10)};
          --toolbar-page-number-bg-color: ${adjustHexColor(params.customColor, 20)};
        }
        `;

      style.textContent = `
        ${pdfCustomColor}
    `;


      if (otherhead) {
        if (document.getElementById("EBiframeStyleID")) {
          document.getElementById("EBiframeStyleID").remove();
        }
        otherhead.appendChild(style);
      }
    }
  }

  pdfIframeStyle();

  // Set watermark config in this context from decoded params
  // (viewer.html sets it on its own window, but this template may run
  //  inside the 3D FlipBook's internal iframe — a separate window scope)
  if (params.watermark_text) {
    window._epWmConfig = {
      text: params.watermark_text,
      fontSize: parseInt(params.watermark_font_size, 10) || 48,
      color: (function() { var c = params.watermark_color; if (c && c.charAt(0) !== '#') c = '#' + c; return c || '#000000'; })(),
      opacity: (parseInt(params.watermark_opacity, 10) || 15) / 100,
      style: params.watermark_style || 'center'
    };
  }

  // Draw watermark on a canvas (standalone for download use)
  const _epDrawWmOnCanvas = (canvas, wm) => {
    if (!wm || !wm.text) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);

    const hexToRgba = (hex, alpha) => {
      if (!hex || hex === 'transparent') return 'rgba(0,0,0,' + alpha + ')';
      hex = hex.replace(/^#/, '');
      if (hex.length === 3) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
      if (!/^[0-9A-Fa-f]{6}$/.test(hex)) return 'rgba(0,0,0,' + alpha + ')';
      return 'rgba(' + parseInt(hex.slice(0,2),16) + ',' + parseInt(hex.slice(2,4),16) + ',' + parseInt(hex.slice(4,6),16) + ',' + alpha + ')';
    };

    ctx.fillStyle = hexToRgba(wm.color, wm.opacity);
    ctx.font = 'bold ' + wm.fontSize + 'px sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    if (wm.style === 'tiled') {
      const tw = ctx.measureText(wm.text).width;
      const stepX = tw + 80;
      const stepY = wm.fontSize * 3;
      const diag = Math.sqrt(canvas.width * canvas.width + canvas.height * canvas.height);
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate(-Math.PI / 6);
      for (let y = -diag; y < diag; y += stepY) {
        for (let x = -diag; x < diag; x += stepX) {
          ctx.fillText(wm.text, x, y);
        }
      }
    } else {
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate(-Math.atan2(canvas.height, canvas.width));
      const tw = ctx.measureText(wm.text).width;
      const maxW = Math.sqrt(canvas.width * canvas.width + canvas.height * canvas.height) * 0.8;
      if (tw > maxW) {
        ctx.font = 'bold ' + Math.floor(wm.fontSize * (maxW / tw)) + 'px sans-serif';
      }
      ctx.fillText(wm.text, 0, 0);
    }
    ctx.restore();
  };

  // Resolve pdfjsLib from current or parent window and load PDF with proper font config
  const _epGetPdfjsLib = () => {
    return (typeof pdfjsLib !== 'undefined' && pdfjsLib)
      || (window.parent && window.parent.pdfjsLib)
      || null;
  };

  const _epLoadPdf = (pdfUrl) => {
    const lib = _epGetPdfjsLib();
    if (!lib) throw new Error('pdfjsLib not available');
    const docPromise = lib.getDocument({
      url: pdfUrl,
      cMapPacked: true,
      disableFontFace: true,
      isEvalSupported: true
    }).promise;
    // Timeout: reject if document doesn't load within 30 seconds
    const timeout = new Promise((_, reject) =>
      setTimeout(() => reject(new Error('PDF load timed out')), 30000)
    );
    return Promise.race([docPromise, timeout]);
  };

  // Download PDF with watermark baked into pages as JPEG images
  const _epWatermarkDownload = async (pdfUrl, wm) => {
    const pdf = await _epLoadPdf(pdfUrl);
    const numPages = pdf.numPages;
    const scale = 2;
    const jpgQuality = 0.92;
    const pageImages = [];

    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i);
      const vp = page.getViewport({ scale: scale });
      const canvas = document.createElement('canvas');
      canvas.width = vp.width;
      canvas.height = vp.height;
      const ctx = canvas.getContext('2d');
      await page.render({ canvasContext: ctx, viewport: vp }).promise;
      _epDrawWmOnCanvas(canvas, wm);

      const dataUrl = canvas.toDataURL('image/jpeg', jpgQuality);
      const raw = atob(dataUrl.split(',')[1]);
      const arr = new Uint8Array(raw.length);
      for (let j = 0; j < raw.length; j++) arr[j] = raw.charCodeAt(j);
      pageImages.push({ jpeg: arr, w: vp.width / scale, h: vp.height / scale });
    }

    // Build minimal PDF with JPEG images
    const enc = new TextEncoder();
    const parts = [];
    const offsets = [];

    function writeStr(s) { parts.push(enc.encode(s)); }
    function writeBytes(b) { parts.push(b); }
    function currentSize() { return parts.reduce((a, p) => a + p.length, 0); }

    const nl = '\n';
    writeStr('%PDF-1.4' + nl);

    offsets[1] = currentSize();
    writeStr('1 0 obj' + nl + '<< /Type /Catalog /Pages 2 0 R >>' + nl + 'endobj' + nl);

    let nextObj = 3;
    const pageObjNumbers = [];
    const allPageData = [];

    for (let i = 0; i < pageImages.length; i++) {
      const pg = pageImages[i];
      const ptW = (pg.w * 72 / 96).toFixed(2);
      const ptH = (pg.h * 72 / 96).toFixed(2);
      const imgObj = nextObj++;
      const contObj = nextObj++;
      const pgObj = nextObj++;
      pageObjNumbers.push(pgObj);
      const contentStr = 'q ' + ptW + ' 0 0 ' + ptH + ' 0 0 cm /Im0 Do Q';
      const contentBytes = enc.encode(contentStr);
      allPageData.push({ imgObj, contObj, pgObj, ptW, ptH, jpeg: pg.jpeg, contentBytes, pgIndex: i });
    }

    offsets[2] = currentSize();
    writeStr('2 0 obj' + nl + '<< /Type /Pages /Kids [' + pageObjNumbers.map(n => n + ' 0 R').join(' ') + '] /Count ' + pageImages.length + ' >>' + nl + 'endobj' + nl);

    for (const pd of allPageData) {
      const pg = pageImages[pd.pgIndex];

      offsets[pd.imgObj] = currentSize();
      writeStr(pd.imgObj + ' 0 obj' + nl +
        '<< /Type /XObject /Subtype /Image /Width ' + (pg.w * 2) +
        ' /Height ' + (pg.h * 2) +
        ' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ' + pd.jpeg.length + ' >>' + nl +
        'stream' + nl);
      writeBytes(pd.jpeg);
      writeStr(nl + 'endstream' + nl + 'endobj' + nl);

      offsets[pd.contObj] = currentSize();
      writeStr(pd.contObj + ' 0 obj' + nl +
        '<< /Length ' + pd.contentBytes.length + ' >>' + nl +
        'stream' + nl);
      writeBytes(pd.contentBytes);
      writeStr(nl + 'endstream' + nl + 'endobj' + nl);

      offsets[pd.pgObj] = currentSize();
      writeStr(pd.pgObj + ' 0 obj' + nl +
        '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ' + pd.ptW + ' ' + pd.ptH + ']' +
        ' /Contents ' + pd.contObj + ' 0 R' +
        ' /Resources << /XObject << /Im0 ' + pd.imgObj + ' 0 R >> >> >>' + nl + 'endobj' + nl);
    }

    const xrefOffset = currentSize();
    writeStr('xref' + nl + '0 ' + nextObj + nl);
    writeStr('0000000000 65535 f ' + nl);
    for (let i = 1; i < nextObj; i++) {
      writeStr(String(offsets[i]).padStart(10, '0') + ' 00000 n ' + nl);
    }
    writeStr('trailer' + nl + '<< /Size ' + nextObj + ' /Root 1 0 R >>' + nl);
    writeStr('startxref' + nl + xrefOffset + nl + '%%EOF');

    const totalLen = parts.reduce((a, p) => a + p.length, 0);
    const result = new Uint8Array(totalLen);
    let pos = 0;
    for (const p of parts) { result.set(p, pos); pos += p.length; }

    const blob = new Blob([result], { type: 'application/pdf' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = pdfUrl.split('/').pop() || 'document.pdf';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setTimeout(() => URL.revokeObjectURL(url), 5000);
  };

  const DownloadPDF = (pdfUrl) => {
    // If watermark is configured, render watermarked version
    if (window._epWmConfig && window._epWmConfig.text) {
      _epWatermarkDownload(pdfUrl, window._epWmConfig)
        .catch(error => {
          console.error('EmbedPress: Watermarked download failed, falling back to original', error);
          _epOriginalDownload(pdfUrl);
        });
      return;
    }
    _epOriginalDownload(pdfUrl);
  };

  const _epOriginalDownload = (pdfUrl) => {
    const fileName = pdfUrl.split('/').pop();

    fetch(pdfUrl)
      .then(response => response.blob())
      .then(blob => {
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      })
      .catch(error => console.error('Error downloading the PDF:', error));
  };

  document.getElementById('download-pdf').addEventListener('click', function (e) {
    e.preventDefault();
    DownloadPDF(dataFile);
  });

  // Print with watermark support using a hidden iframe (no popup window)
  const _epWatermarkPrint = (pdfUrl, wm) => {
    return _epLoadPdf(pdfUrl).then(function (pdf) {
      var numPages = pdf.numPages;
      var scale = 2;
      var chain = Promise.resolve();
      var pageDataUrls = [];

      for (var i = 1; i <= numPages; i++) {
        (function (pageNum) {
          chain = chain.then(function () {
            return pdf.getPage(pageNum).then(function (page) {
              var vp = page.getViewport({ scale: scale });
              var canvas = document.createElement('canvas');
              canvas.width = vp.width;
              canvas.height = vp.height;
              var ctx = canvas.getContext('2d');
              return page.render({ canvasContext: ctx, viewport: vp }).promise.then(function () {
                _epDrawWmOnCanvas(canvas, wm);
                pageDataUrls.push(canvas.toDataURL('image/jpeg', 0.92));
              });
            });
          });
        })(i);
      }

      return chain.then(function () {
        var imgs = pageDataUrls.map(function (dataUrl) {
          return '<img src="' + dataUrl + '" style="width:100%;height:auto;page-break-after:always;display:block;" />';
        }).join('');

        // Use a hidden iframe to trigger the print dialog directly
        var iframe = document.createElement('iframe');
        iframe.style.cssText = 'position:fixed;left:-9999px;width:0;height:0;border:none;';
        document.body.appendChild(iframe);

        var doc = iframe.contentDocument || iframe.contentWindow.document;
        doc.open();
        doc.write(
          '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Print</title>' +
          '<style>*{margin:0;padding:0}img{width:100%;height:auto;display:block;page-break-after:always}img:last-child{page-break-after:auto}</style>' +
          '</head><body>' + imgs + '</body></html>'
        );
        doc.close();

        // Wait for images to load, then print
        var images = doc.querySelectorAll('img');
        var loaded = 0;
        var total = images.length;

        var triggerPrint = function () {
          iframe.contentWindow.focus();
          iframe.contentWindow.print();
          // Clean up after print dialog closes
          setTimeout(function () {
            document.body.removeChild(iframe);
          }, 1000);
        };

        if (total === 0) { triggerPrint(); return; }
        for (var j = 0; j < total; j++) {
          images[j].onload = images[j].onerror = function () {
            if (++loaded >= total) triggerPrint();
          };
        }
      });
    });
  };

  // Override cmdPrint button when watermark is configured
  const printBtn = document.querySelector('li.fnav-item.cmdPrint a');
  if (printBtn && window._epWmConfig && window._epWmConfig.text) {
    var _epPrintBusy = false;
    printBtn.addEventListener('click', function (e) {
      if (_epPrintBusy) return; // let default 3D FlipBook handler run on fallback re-click
      e.preventDefault();
      e.stopImmediatePropagation();
      _epPrintBusy = true;
      _epWatermarkPrint(dataFile, window._epWmConfig)
        .catch(function (err) {
          console.error('EmbedPress: Watermarked print failed, falling back to default', err);
          // Re-trigger click without our interception so 3D FlipBook handles it
          _epPrintBusy = true;
          printBtn.click();
        })
        .finally(function () {
          _epPrintBusy = false;
        });
    }, true);
  }

</script>