<script src="{{baseUrl}}/css/highlight/highlight.min.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('pre code').forEach(el => { el.textContent = el.textContent.trimEnd(); });
    hljs.highlightAll();
    var kbd = document.querySelector('.search-button__shortcut');
    if (kbd) kbd.textContent = navigator.platform.indexOf('Mac') > -1 ? '⌘K' : 'Ctrl K';

    // Copy code buttons
    const copyIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
    const checkIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
    document.querySelectorAll('pre').forEach(function(pre) {
      const btn = document.createElement('button');
      btn.className = 'copy-code-btn';
      btn.innerHTML = copyIcon;
      btn.setAttribute('aria-label', 'Copy code');
      btn.addEventListener('click', function() {
        const code = pre.querySelector('code');
        const text = code ? code.textContent : pre.textContent;
        navigator.clipboard.writeText(text || '').then(function() {
          btn.innerHTML = checkIcon;
          setTimeout(function() { btn.innerHTML = copyIcon; }, 2000);
        });
      });
      pre.appendChild(btn);
    });
  });
</script>
<script>
  (function() {
    var themeKey = window.__doculaThemeKey;
    function getMode() {
      return localStorage.getItem(themeKey) || {{#if themeMode}}'{{themeMode}}'{{else}}'system'{{/if}};
    }

    function resolveTheme(mode) {
      if (mode === 'system') {
        return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
      }
      return mode;
    }

    var cachedEls = null;
    function getThemeEls() {
      if (!cachedEls) {
        cachedEls = {
          systemIcon: document.querySelector('.theme-button__icon--system'),
          sunIcon: document.querySelector('.theme-button__icon--sun'),
          moonIcon: document.querySelector('.theme-button__icon--moon'),
          toggle: document.getElementById('theme-toggle')
        };
      }
      return cachedEls;
    }

    function applyTheme(mode) {
      var resolved = resolveTheme(mode);
      if (resolved === 'light') {
        document.documentElement.setAttribute('data-theme', 'light');
      } else {
        document.documentElement.removeAttribute('data-theme');
      }

      var els = getThemeEls();
      if (els.systemIcon && els.sunIcon && els.moonIcon) {
        els.systemIcon.classList.add('theme-button__icon--hidden');
        els.sunIcon.classList.add('theme-button__icon--hidden');
        els.moonIcon.classList.add('theme-button__icon--hidden');
        if (mode === 'system') {
          els.systemIcon.classList.remove('theme-button__icon--hidden');
        } else if (mode === 'light') {
          els.sunIcon.classList.remove('theme-button__icon--hidden');
        } else {
          els.moonIcon.classList.remove('theme-button__icon--hidden');
        }
      }

      if (els.toggle) {
        var labels = { system: 'Theme: system (following system)', light: 'Theme: light', dark: 'Theme: dark' };
        els.toggle.setAttribute('aria-label', labels[mode] || 'Toggle theme');
      }
    }

    function nextMode(current) {
      var cycle = { system: 'light', light: 'dark', dark: 'system' };
      return cycle[current] || 'system';
    }

    var currentMode = getMode();

    document.addEventListener('DOMContentLoaded', function() {
      applyTheme(currentMode);

      var els = getThemeEls();
      if (els.toggle) {
        els.toggle.addEventListener('click', function() {
          currentMode = nextMode(currentMode);
          localStorage.setItem(themeKey, currentMode);
          applyTheme(currentMode);
        });
      }
    });

    window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', function() {
      if (getMode() === 'system') {
        applyTheme('system');
      }
    });
  })();
</script>
{{#if cookieAuth}}
<div id="cookie-auth-config" hidden{{#if cookieAuth.logoutUrl}} data-logout-url="{{cookieAuth.logoutUrl}}"{{/if}}{{#if cookieAuth.authCheckUrl}} data-auth-check-url="{{cookieAuth.authCheckUrl}}"{{/if}}{{#if cookieAuth.authCheckMethod}} data-auth-check-method="{{cookieAuth.authCheckMethod}}"{{/if}}{{#if cookieAuth.authCheckUserPath}} data-auth-check-user-path="{{cookieAuth.authCheckUserPath}}"{{/if}}></div>
<script>
  (function() {
    var configEl = document.getElementById('cookie-auth-config');
    if (!configEl) return;
    var logoutUrl = configEl.getAttribute('data-logout-url');
    var authCheckUrl = configEl.getAttribute('data-auth-check-url');
    var authCheckMethod = configEl.getAttribute('data-auth-check-method') || 'GET';
    var authCheckUserPath = configEl.getAttribute('data-auth-check-user-path');
    function getNestedValue(obj, path) {
      if (!path) return null;
      var parts = path.split('.');
      var current = obj;
      for (var i = 0; i < parts.length; i++) {
        if (current == null || typeof current !== 'object') return null;
        current = current[parts[i]];
      }
      return current || null;
    }
    var cachedAuth = null;
    try { cachedAuth = JSON.parse(localStorage.getItem('docula-auth-state')); } catch(e) {}
    window.__doculaAuth = cachedAuth || { loggedIn: false, displayName: null };
    function setAuthUI(loggedIn, displayName) {
      window.__doculaAuth = { loggedIn: loggedIn, displayName: displayName };
      try { localStorage.setItem('docula-auth-state', JSON.stringify(window.__doculaAuth)); } catch(e) {}
      document.documentElement.classList.toggle('docula-auth-logged-in', loggedIn);
      document.dispatchEvent(new CustomEvent('docula-auth-change'));
      var els = [
        { login: document.getElementById('cookie-auth-login'), logout: document.getElementById('cookie-auth-logout'), user: document.getElementById('cookie-auth-user') },
        { login: document.getElementById('cookie-auth-login-mobile'), logout: document.getElementById('cookie-auth-logout-mobile'), user: document.getElementById('cookie-auth-user-mobile') }
      ];
      els.forEach(function(pair) {
        if (pair.login) pair.login.style.display = loggedIn ? 'none' : '';
        if (pair.logout) pair.logout.style.display = loggedIn ? '' : 'none';
        if (pair.user) {
          pair.user.textContent = displayName || '';
          pair.user.style.display = (loggedIn && displayName) ? '' : 'none';
        }
      });
    }
    function checkAuth() {
      if (!authCheckUrl) return;
      fetch(authCheckUrl, { method: authCheckMethod, credentials: 'include' }).then(function(res) {
        if (!res.ok) {
          setAuthUI(false, null);
          return;
        }
        if (authCheckUserPath) {
          res.json().then(function(data) {
            setAuthUI(true, getNestedValue(data, authCheckUserPath));
          }).catch(function() {
            setAuthUI(true, null);
          });
        } else {
          setAuthUI(true, null);
        }
      }).catch(function() {
        setAuthUI(false, null);
      });
    }
    document.addEventListener('DOMContentLoaded', function() {
      if (cachedAuth) setAuthUI(cachedAuth.loggedIn, cachedAuth.displayName);
      checkAuth();
      var logoutEls = [
        document.getElementById('cookie-auth-logout'),
        document.getElementById('cookie-auth-logout-mobile')
      ];
      logoutEls.forEach(function(el) {
        if (el) {
          el.addEventListener('click', function() {
            if (logoutUrl) {
              window.location.href = logoutUrl;
            } else {
              window.location.reload();
            }
          });
        }
      });
    });
  })();
</script>
{{/if}}
<script defer>
  document.addEventListener('DOMContentLoaded', () => {
    const menuToggle = document.getElementById('mobile-menu-toggle');
    const mobileSidebar = document.getElementById('mobile-sidebar');
    const backdrop = document.getElementById('sidebar-backdrop');
    if (menuToggle && mobileSidebar) {
      menuToggle.addEventListener('click', () => {
        mobileSidebar.classList.toggle('mobile-sidebar--open');
        if (backdrop) backdrop.classList.toggle('sidebar-backdrop--visible');
      });
      if (backdrop) {
        backdrop.addEventListener('click', () => {
          mobileSidebar.classList.remove('mobile-sidebar--open');
          backdrop.classList.remove('sidebar-backdrop--visible');
        });
      }
    }

    // Page dropdown toggle (docs pages)
    const dropdownToggle = document.getElementById('page-dropdown-toggle');
    const dropdownList = document.getElementById('page-dropdown-list');
    if (dropdownToggle && dropdownList) {
      dropdownToggle.addEventListener('click', () => {
        dropdownList.classList.toggle('page-dropdown__list--open');
      });
    }

    // Active sidebar link highlighting
    const sidebarLinks = document.querySelectorAll('.nav-sidebar__item');
    const currentPath = window.location.pathname;
    sidebarLinks.forEach((link) => {
      if (link.getAttribute('href') === currentPath || link.getAttribute('href') === currentPath.replace(/\/$/, '')) {
        link.classList.add('nav-sidebar__item--active');
      }
    });

    // Active header nav link highlighting
    const navLinks = document.querySelectorAll('.header-bottom__item');
    navLinks.forEach((link) => {
      const href = link.getAttribute('href');
      if (currentPath.startsWith(href)) {
        link.classList.add('header-bottom__item--active');
      }
    });

    // Active mobile nav link highlighting
    const mobileNavLinks = document.querySelectorAll('.mobile-nav__item');
    mobileNavLinks.forEach((link) => {
      const href = link.getAttribute('href');
      if (currentPath.startsWith(href)) {
        link.classList.add('mobile-nav__item--active');
      }
    });

    // TOC extraction: move the inline TOC into the right sidebar and hide the original
    const tocHeading = document.getElementById('table-of-contents');
    if (tocHeading) {
      const tocList = tocHeading.nextElementSibling;
      const tocTarget = document.getElementById('toc-list');
      if (tocList && tocList.tagName === 'UL' && tocTarget) {
        tocTarget.innerHTML = tocList.innerHTML;
        tocHeading.style.display = 'none';
        tocList.style.display = 'none';
      }
    }

    // Hide the TOC aside if it has no entries
    const tocSidebar = document.getElementById('toc-list');
    if (tocSidebar && tocSidebar.children.length === 0) {
      const aside = tocSidebar.closest('.content-aside');
      if (aside) { aside.style.display = 'none'; }
    }

    // Image lightbox
    const lightboxOverlay = document.createElement('div');
    lightboxOverlay.className = 'lightbox-overlay';
    lightboxOverlay.addEventListener('click', function(e) {
      if (e.target !== lightboxImg) lightboxOverlay.classList.remove('lightbox-overlay--visible');
    });
    const lightboxClose = document.createElement('button');
    lightboxClose.className = 'lightbox-close';
    lightboxClose.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
    lightboxClose.addEventListener('click', function() {
      lightboxOverlay.classList.remove('lightbox-overlay--visible');
    });
    const lightboxImg = document.createElement('img');
    lightboxOverlay.appendChild(lightboxClose);
    lightboxOverlay.appendChild(lightboxImg);
    document.body.appendChild(lightboxOverlay);

    document.querySelectorAll('.article__main img, .changelog-entry-body img').forEach(function(img) {
      img.addEventListener('click', function() {
        lightboxImg.src = img.src;
        lightboxOverlay.classList.add('lightbox-overlay--visible');
      });
    });
  });
</script>
