/* site-navigation.js — variable-driven layout, no body.toc-collapsed dependency
   Arndt edition (2026-02-06)
   - Drives layout via CSS variables: --sidebar-width, --content-offset
   - Never relies on <body class="toc-collapsed">
   - No inline width/grid writes; keeps DOM/vars/ARIA in sync
*/
(function(){
  // ---- 0) Reduced motion ---------------------------------------------------
  try {
    const m = window.matchMedia?.('(prefers-reduced-motion: reduce)');
    const apply = () => document.documentElement.classList.toggle('reduced-motion', !!m?.matches);
    if (m) { apply(); m.addEventListener('change', apply); }
  } catch(_) {}

  // ---- helpers --------------------------------------------------------------
  const $  = (sel, root=document) => root.querySelector(sel);
  const $$ = (sel, root=document) => Array.from(root.querySelectorAll(sel));
  const byId = (id) => document.getElementById(id);
  const prefersReducedMotion = () => !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
  const getSidebar = () => byId('toc-sidebar') || $('.toc-sidebar');

  function setLayoutVars(collapsed){
    // Source of truth for layout. No body class checks anywhere else.
    const root = document.documentElement;
    root.classList.toggle('toc-collapsed', !!collapsed);

    // IMPORTANT: stop writing inline vars, otherwise they can override :root rules.
    root.style.removeProperty('--sidebar-width');
    root.style.removeProperty('--content-offset'); // in case older builds set it
    root.style.removeProperty('--sidebar-border');
  }

  function normalizeLayoutState(){
    const sidebar = getSidebar();
    const main    = $('.main-content');
    const topbar  = $('.top-bar');
    const inner   = $('.top-bar__inner');
    const collapsed = !!sidebar?.classList.contains('collapsed');

    // Clear any stale inline sizing that could fight CSS
    if (main)  { 
      main.style.removeProperty('inline-size');
      main.style.removeProperty('width');
      main.style.removeProperty('margin');
      main.style.removeProperty('margin-left');
      main.style.removeProperty('margin-right');
      main.style.removeProperty('max-width');
    }
    if (inner) { inner.style.removeProperty('inline-size'); inner.style.removeProperty('width'); }
    if (topbar){ topbar.style.removeProperty('grid-template-columns'); }

    setLayoutVars(collapsed);

    if (sidebar){
      // Keep ARIA in sync
      sidebar.setAttribute('aria-hidden', String(collapsed));
      if (collapsed){ sidebar.setAttribute('inert',''); sidebar.style.display='none'; }
      else { sidebar.removeAttribute('inert'); sidebar.style.display=''; }
    }
    const btn = byId('toc-toggle');
    if (btn) btn.setAttribute('aria-expanded', String(!collapsed));
  }
function clearInlineLayoutProps(){
  const main = document.querySelector('.main-content');
  const header = document.querySelector('.content-header');
  const topbar = document.querySelector('.top-bar');

  if (main){
    main.style.removeProperty('margin');
    main.style.removeProperty('margin-left');
    main.style.removeProperty('margin-right');
    main.style.removeProperty('width');
    main.style.removeProperty('max-width');
    main.style.removeProperty('inline-size');
  }
  if (header){
    header.style.removeProperty('left');
    header.style.removeProperty('margin');
    header.style.removeProperty('width');
    header.style.removeProperty('max-width');
  }
  if (topbar){
    topbar.style.removeProperty('grid-template-columns');
  }
}

function enforceLayoutSoon(){
  // Re-apply after the browser paints, and again after Flare’s delayed writes.
  requestAnimationFrame(() => {
    normalizeLayoutState();
    clearInlineLayoutProps();

    // Force reflow
    const main = document.querySelector('.main-content');
    if (main) void main.offsetWidth;

    setTimeout(() => { normalizeLayoutState(); clearInlineLayoutProps(); }, 50);
    setTimeout(() => { normalizeLayoutState(); clearInlineLayoutProps(); }, 200);
  });
}

  // ---- 1) Focused TOC branch expansion + markers ---------------------------
  const getMenuFocused = () => {
    const s = getSidebar(); if (!s) return null;
    const menus = $('.menu', s) ? $$('.menu', s) : [];
    if (!menus.length) return null;
    const fullHost = s.querySelector('.menu-full');
    if (!fullHost) return menus[0];
    const m = menus.find(u => !fullHost.contains(u));
    return m || menus[0];
  };
  const getMenuFull = () => {
    const s = getSidebar(); if (!s) return null;
    const host = s.querySelector('.menu-full'); if (!host) return null;
    return host.querySelector('.menu') || host.querySelector('ul.menu') || null;
  };
  function openBranch(li){ if (!li) return; li.classList.add('expand'); const u=li.querySelector(':scope > ul'); if (u){ u.style.display='block'; u.classList.add('open'); } }
  function expandActiveBranchInFocused(){
    const menu = getMenuFocused(); if (!menu) return;
    const currentLink = menu.querySelector('a.selected') || menu.querySelector('a[aria-current="true"]') || menu.querySelector('a[aria-current="page"]');
    if (!currentLink) return;
    const currentItem = currentLink.closest('li');
    openBranch(currentItem);
    let node = currentItem?.parentElement;
    while (node && node !== menu){
      if (node.tagName === 'UL'){
        const parentLi = node.closest('li');
        openBranch(parentLi);
        node = parentLi?.parentElement;
      } else { node = node.parentElement; }
    }
  }
  function syncHasChildrenMarkers(){
    const sidebar = getSidebar() || document.querySelector('.toc-sidebar');
    if (!sidebar) return;
    const menuFocused = (typeof getMenuFocused === 'function') ? getMenuFocused() : sidebar.querySelector('.menu');
    const menuFull    = (typeof getMenuFull    === 'function') ? getMenuFull()    : sidebar.querySelector('.menu-full .menu');
    if (!menuFocused || !menuFull) return;
    const fullHasKidsHref = new Set();
    const fullHasKidsText = new Set();
    menuFull.querySelectorAll(':scope > li, li').forEach(li => {
      const hasChildUl = !!li.querySelector(':scope > ul');
      if (!hasChildUl) return;
      const a = li.querySelector(':scope > a');
      if (!a) return;
      const href = (a.getAttribute('href') || '').split('#')[0];
      const text = (a.textContent || '').trim();
      if (href) fullHasKidsHref.add(href);
      if (text) fullHasKidsText.add(text);
    });
    menuFocused.querySelectorAll('li').forEach(li => {
      const a = li.querySelector(':scope > a');
      if (!a) return;
      const href = (a.getAttribute('href') || '').split('#')[0];
      const text = (a.textContent || '').trim();
      const should = !!(href && fullHasKidsHref.has(href));
      li.classList.toggle('has-children', !!should);
    });
  }
  function whenFocusedMenuReady(run){
    const s = getSidebar(); if (!s) return;
    const ready = () => { const m=getMenuFocused(); const sel=m?.querySelector('a.selected, a[aria-current="true"], a[aria-current="page"]'); return m && sel; };
    if (ready()){ run(); return; }
    const mo = new MutationObserver(() => { if (ready()){ mo.disconnect(); run(); } });
    mo.observe(s, { childList:true, subtree:true });
    setTimeout(() => mo.disconnect(), 7000);
  }
  function observeFocusedMenu(){
    const menu = getMenuFocused(); if (!menu) return;
    let pending=false; const reexpand = () => { if (pending) return; pending=true; setTimeout(()=>{ pending=false; expandActiveBranchInFocused(); },150); };
    const mo = new MutationObserver(muts => { if (muts.some(m => m.type==='childList')) reexpand(); });
    mo.observe(menu, { childList:true, subtree:true });
  }
  window.addEventListener('load', () => { whenFocusedMenuReady(()=>{ expandActiveBranchInFocused(); observeFocusedMenu(); syncHasChildrenMarkers(); }); });

  // ---- 2) Quick Float Navigation -------------------------------------------
  const slugify = (text) => { const base = String(text || 'section').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/(^-+|-+$)/g,'').slice(0,64); return base || 'section'; };
  function ensureHeadingIds(){ const heads = $$('h2,h3,h4'); const used=new Set(); heads.forEach(h=>{ let id=(h.id||'').trim(); if(!id){ const base=slugify(h.textContent||h.innerText||'section'); let v=base,i=2; while(used.has(v) || byId(v)) v=`${base}-${i++}`; h.id=v; used.add(v);} else { used.add(id);} }); }
  function collectFromHeadings(){ return $$('h2[id],h3[id],h4[id]').map(h=>({ id:h.id, text:(h.textContent||'').trim(), level:h.tagName==='H2'?2:(h.tagName==='H3'?3:4) })); }
  function collectFromMiniToc(){ const sel=['div[class*="MiniTOC"] a[href^="#"]','nav[aria-label*="Mini"] a[href^="#"]','ul[class*="MiniTOC"] a[href^="#"]'].join(','); return $$(sel).map(a=>{ const href=a.getAttribute('href')||''; if(!href || href.indexOf('#')!==0) return null; const id=href.substring(1); const t=byId(id); if(!t) return null; const h=t.closest?.('h2,h3,h4'); const level=h?(h.tagName==='H2'?2:(h.tagName==='H3'?3:4)):2; return {id, text:(a.textContent||'').trim(), level}; }).filter(Boolean); }
  function buildList(items){ const root=document.createElement('ul'); root.className='qfn-list'; const stack=[{level:2,ul:root}]; items.forEach(it=>{ const L=it.level; if(L>stack[stack.length-1].level){ const parentLi=stack[stack.length-1].ul.lastElementChild; const ul=document.createElement('ul'); (parentLi?parentLi:stack[stack.length-1].ul).appendChild(ul); stack.push({level:L,ul}); } else if(L<stack[stack.length-1].level){ while(L<stack[stack.length-1].level) stack.pop(); } const li=document.createElement('li'); const a=document.createElement('a'); a.className='qfn-link'; a.href='#'+it.id; a.appendChild(document.createTextNode(it.text)); a.addEventListener('click', (e)=>{ e.preventDefault(); const t=byId(it.id); if(!t) return; const r=t.getBoundingClientRect(); const y=Math.max(window.scrollY + r.top - getStickyOffset(), 0); window.scrollTo({ top:y, behavior: prefersReducedMotion()? 'auto':'smooth' }); }); li.appendChild(a); stack[stack.length-1].ul.appendChild(li); }); return root; }
  function setupActiveTracking(items, panel){ if(!('IntersectionObserver' in window)) return; const links=$$('.qfn-link', panel); const obs=new IntersectionObserver((entries)=>{ entries.forEach(en=>{ if(!en.isIntersecting) return; const id=en.target.id; links.forEach(l=>l.classList.remove('is-active')); const a=links.find(l=>l.getAttribute('href')==='#'+id); if(a) a.classList.add('is-active'); }); }, { rootMargin:'-130px 0px -60% 0px', threshold:0.1 }); items.forEach(i=>{ const el=byId(i.id); if(el) obs.observe(el); }); }
  function addTopLink(panel){ const ul=document.createElement('ul'); ul.className='qfn-list'; const li=document.createElement('li'); const a=document.createElement('a'); a.className='qfn-link qfn-top-link'; a.href='#top'; a.appendChild(document.createTextNode('Back to top ⤴')); a.addEventListener('click', (e)=>{ e.preventDefault(); window.scrollTo({ top:0, behavior: prefersReducedMotion()? 'auto':'smooth' }); enforceLayoutSoon();}); li.appendChild(a); ul.appendChild(li); panel.appendChild(ul); }
  function initQuickFloatNav(){ const nav=byId('quick-float-nav'); const panel=byId('qfn-panel'); const toggle=nav?.querySelector('.qfn-toggle'); if(!nav || !panel || !toggle) return; ensureHeadingIds(); let items=collectFromHeadings(); if(!items.length) items=collectFromMiniToc(); if(!items.length) return; nav.removeAttribute('hidden'); addTopLink(panel); panel.appendChild(buildList(items)); toggle.addEventListener('click', ()=>{ const open=panel.style.display==='block'; panel.style.display=open?'none':'block'; toggle.setAttribute('aria-expanded', String(!open)); }); panel.style.display='none'; setupActiveTracking(items, panel); }
  window.addEventListener('load', initQuickFloatNav);

  // ---- 3) TOC sidebar toggle (FAB) -----------------------------------------
  function toggleToc(forceCollapse){
    const btn = byId('toc-toggle');
    const sidebar = getSidebar();
    if (!sidebar || !btn) return;

    const sidebarIsCollapsed = sidebar.classList.contains('collapsed');
    const willCollapse = (typeof forceCollapse === 'boolean') ? forceCollapse : !sidebarIsCollapsed;

    if (willCollapse){
      sidebar.classList.add('collapsed');
      btn.setAttribute('aria-expanded','false');
    } else {
      sidebar.classList.remove('collapsed');
      btn.setAttribute('aria-expanded','true');
    }

    // Drive layout via variables; keep ARIA/display in sync
    normalizeLayoutState();
    enforceLayoutSoon();
  }

  function ensureTocButton(){
    let btn = byId('toc-toggle');
    if (btn) return btn;
    btn = document.createElement('button');
    btn.id='toc-toggle'; btn.className='toc-fab'; btn.type='button';
    btn.setAttribute('aria-expanded','true');
    btn.setAttribute('aria-controls','toc-sidebar');
    btn.setAttribute('title','Show/Hide Table of Contents');
    btn.innerHTML='☰';
    document.body.appendChild(btn);
    return btn;
  }

  function bindTocToggle(){
    const btn = byId('toc-toggle') || ensureTocButton();
    const sidebar = getSidebar();
    if (!btn || !sidebar){ if(btn) btn.style.display='none'; return; }
    btn.style.display='';
    if (btn._bound) btn.removeEventListener('click', btn._bound);
    btn._bound = (ev)=>{ ev.preventDefault(); toggleToc(); };
    btn.addEventListener('click', btn._bound);

    // Auto-collapse below breakpoint on first bind
    const isSmall = window.matchMedia && window.matchMedia('(max-width: 900px)').matches;
    if (!sidebar.classList.contains('collapsed') && isSmall) toggleToc(true);
  }

  function observeTocLifecycle(){
    bindTocToggle();
    const sidebar = getSidebar();
    if (sidebar){
      const moSidebar = new MutationObserver((muts)=>{ if (muts.some(m=>m.type==='childList')) bindTocToggle(); });
      moSidebar.observe(sidebar, { childList:true, subtree:true });
    }
    const moBody = new MutationObserver(()=>{ const btn=byId('toc-toggle'); const s=getSidebar(); if (!btn || !s) bindTocToggle(); });
    moBody.observe(document.body, { childList:true, subtree:true });
    let t=0; window.addEventListener('resize', ()=>{ clearTimeout(t); t=setTimeout(()=>{ bindTocToggle(); normalizeLayoutState(); },150); });
  }
  window.addEventListener('load', observeTocLifecycle);
  setTimeout(observeTocLifecycle, 800);

  // ---- 4) Breadcrumb root link + dual-TOC modes ----------------------------
  (function(){
    const MODE_KEY='tocMode';
    const getMode=()=> (localStorage.getItem(MODE_KEY)==='full'?'full':'focused');
    const setMode=(mode)=>{ const val=(mode==='full'?'full':'focused'); localStorage.setItem(MODE_KEY,val); const B=document.body; if(!B) return; B.classList.toggle('toc-full', val==='full'); B.classList.toggle('toc-focused', val!=='full'); };

    function findBreadcrumbHost(){ return byId('doc-breadcrumbs') || document.querySelector('nav[aria-label*="Breadcrumb"], .breadcrumbs, [data-mc-breadcrumbs], [class*="breadcrumbs"]'); }
    function getCurrentLink(menu){ if(!menu) return null; return menu.querySelector('a.selected') || menu.querySelector('a[aria-current="page"]') || menu.querySelector('a[aria-current="true"]') || null; }
    function getTopLevelLiOfCurrent(menu, currentLink){ if(!menu || !currentLink) return null; let li=currentLink.closest('li'); if(!li) return null; while(li && li.parentElement && li.parentElement !== menu){ li=li.parentElement.closest('li'); } return li; }
    function isTopLevelPage(menu, currentLink){ if(!menu || !currentLink) return false; const li=currentLink.closest('li'); return !!(li && li.parentElement === menu); }
    function markTopLevelParentActive(menu, currentLink){ if(!menu || !currentLink) return; $$('.menu a.is-active', getSidebar() || document).forEach(a=>a.classList.remove('is-active')); const topLi=getTopLevelLiOfCurrent(menu,currentLink); const topA=topLi ? topLi.querySelector(':scope > a') : null; if(topA) topA.classList.add('is-active'); }

    function collapseAllChildren(menu){ if(!menu) return; menu.querySelectorAll(':scope > li > ul').forEach(ul=>{ ul.style.display='none'; }); menu.querySelectorAll('li.expand').forEach(li=>li.classList.remove('expand')); }
    function showTopLevelOnly(menu){ if(!menu) return; menu.querySelectorAll(':scope > li').forEach(li=>li.style.removeProperty('display')); collapseAllChildren(menu); }

    function showMenuVisibility({focused, full}){ const mF=getMenuFocused(); const mAll=getMenuFull(); if(mF){ const hostF = mF.closest('.menu-full') ? null : mF; (hostF||mF).style.display=(focused?'':'none'); } if(mAll){ const hostAll = mAll.closest('.menu-full') || mAll; hostAll.style.display=(full?'':'none'); } }
    function syncActiveToFullMenu(focusedMenu, fullMenu){ if(!focusedMenu || !fullMenu) return; const curr=getCurrentLink(focusedMenu); if(!curr) return; const topLi=getTopLevelLiOfCurrent(focusedMenu,curr); if(!topLi) return; const topA=topLi.querySelector(':scope > a'); if(!topA) return; const href=(topA.getAttribute('href')||'').split('#')[0]; const label=(topA.textContent||'').trim(); fullMenu.querySelectorAll('a.is-active').forEach(a=>a.classList.remove('is-active')); let match=null; if(href) match=fullMenu.querySelector(`:scope > li > a[href="${CSS.escape(href)}"]`); if(!match && label){ const cand=$$(':scope > li > a', fullMenu); match=cand.find(a=>(a.textContent||'').trim()===label) || null; } if(match) match.classList.add('is-active'); }

    function createAllTopicsLink(){ const a=document.createElement('a'); a.href='#'; a.className='breadcrumbs-rootlink'; a.setAttribute('role','button'); a.setAttribute('aria-label','Show all topics'); a.setAttribute('title','Show all topics'); a.textContent='All topics'; a.addEventListener('click',(ev)=>{ ev.preventDefault(); activateFullView(); },{capture:true}); return a; }
    function ensureCaretAfter(linkEl){ let caret=linkEl.nextElementSibling; if(!caret || !caret.classList.contains('breadcrumbs-caret')){ caret=document.createElement('span'); caret.className='breadcrumbs-caret'; caret.setAttribute('aria-hidden','true'); caret.textContent='\u203A'; linkEl.insertAdjacentElement('afterend', caret); } }
    function removeAffordance(host){ if(!host) return; host.querySelectorAll('.breadcrumbs-rootlink').forEach(n=>n.remove()); host.querySelectorAll('.breadcrumbs-caret').forEach(n=>n.remove()); host.querySelectorAll('.breadcrumbs-rootitem').forEach(n=>n.remove()); }

    function renderAllTopicsAffordance(){ const host=findBreadcrumbHost(); if(!host) return; function getCrumbCount(){ const cands = host.querySelectorAll('.MCBreadcrumbsBox_0 a, .MCBreadcrumbsBox_breadcrumps_0 a, .MCBreadcrumbsBox_0 li, .MCBreadcrumbsBox_breadcrumps_0 li, .breadcrumbs a, .breadcrumbs li, ol[aria-label*="crumb" i] li'); return cands.length; }
      const menu = getMenuFocused(); const curr = menu ? (menu.querySelector('a.selected') || menu.querySelector('a[aria-current="true"]') || menu.querySelector('a[aria-current="page"]')) : null; const mode=getMode(); let atTopLevel=false; if(menu && curr) atTopLevel = isTopLevelPage(menu, curr); else atTopLevel = (getCrumbCount() < 2); const shouldShow = (!atTopLevel && mode !== 'full'); if(!shouldShow){ removeAffordance(host); return; }
      const flareBox = host.querySelector('.MCBreadcrumbsBox_0, .MCBreadcrumbsBox_breadcrumps_0'); const container = flareBox || host; let link = container.querySelector('.breadcrumbs-rootlink'); if(!link){ link=createAllTopicsLink(); if(container.firstChild) container.insertBefore(link, container.firstChild); else container.appendChild(link); } ensureCaretAfter(link);
    }
    window.__renderAllTopicsAffordance = renderAllTopicsAffordance;

    function showMenuVisibilityApply(){ const mode=getMode(); if(mode==='full') activateFullView(); else activateFocusedView(); }
    function activateFullView(){ const menuF=getMenuFocused(); const menuAll=getMenuFull(); setMode('full'); if(menuAll){ showMenuVisibility({focused:false, full:true}); collapseAllChildren(menuAll); syncActiveToFullMenu(menuF, menuAll); } else { showMenuVisibility({focused:true, full:false}); showTopLevelOnly(menuF); const curr=getCurrentLink(menuF); markTopLevelParentActive(menuF,curr); } renderAllTopicsAffordance(); syncHasChildrenMarkers(); }
    function activateFocusedView(){ setMode('focused'); showMenuVisibility({focused:true, full:false}); expandActiveBranchInFocused(); renderAllTopicsAffordance(); syncHasChildrenMarkers(); }

    function init(){ if(document.body) setMode(getMode()); else document.addEventListener('DOMContentLoaded', ()=>setMode(getMode()), { once:true }); const applyMode = ()=>{ showMenuVisibilityApply(); };
      let tries=0, max=60; const watch=setInterval(()=>{ const host=findBreadcrumbHost(); const menuF=getMenuFocused(); const menuAll=getMenuFull(); if ((host && (menuF || menuAll)) || (++tries >= max)){ clearInterval(watch); applyMode(); const s=getSidebar(); if (s){ const mo=new MutationObserver(()=>{ clearTimeout(init._t); init._t=setTimeout(()=>{ applyMode(); syncHasChildrenMarkers(); },80); }); mo.observe(s,{ childList:true, subtree:true }); } } },120);
      const s=getSidebar(); if (s){ s.addEventListener('click', (ev)=>{ const a=ev.target.closest('a'); if(!a) return; const menuFull=getMenuFull(); const mode=getMode(); if (mode==='full' && menuFull && menuFull.contains(a)){ const li=a.closest('li'); if (li && li.parentElement===menuFull){ localStorage.setItem('tocMode','focused'); document.body.classList.remove('toc-full'); document.body.classList.add('toc-focused'); } } }, { capture:true }); }
      window.addEventListener('storage', (e)=>{ if (e.key==='tocMode'){ (getMode()==='full'?activateFullView:activateFocusedView)(); } });
      window.addEventListener('load', ()=>{ if (getMode()==='full') activateFullView(); });
    }
    if (document.readyState==='loading') document.addEventListener('DOMContentLoaded', init, { once:true }); else init();
  })();

  // ---- 5) Hash-based anchor adjustment -------------------------------------
  function getStickyOffset(){ const v=getComputedStyle(document.documentElement).getPropertyValue('--header-total').trim(); const n=parseFloat(v) || 0; return n + 30; }
  function adjustForHashTarget(){ if(!location.hash) return; const id=decodeURIComponent(location.hash.slice(1)); const t=byId(id); if(!t) return; const r=t.getBoundingClientRect(); const y=Math.max(window.scrollY + r.top - getStickyOffset(), 0); window.scrollTo({ top:y, behavior:'auto' }); }
  window.addEventListener('load', ()=> setTimeout(adjustForHashTarget, 60));
  window.addEventListener('hashchange', ()=>{
  setTimeout(adjustForHashTarget, 0);
  enforceLayoutSoon();
});

  // ---- 6) Breadcrumbs MIRROR ------------------------------------------------
  (function(){
    var HOST_ID='doc-breadcrumbs';
    var SOURCE_WRAP_ID='crumb-source';
    var SELECTOR_CRUMBS=['.MCBreadcrumbsBox_0','.MCBreadcrumbsBox_breadcrumps_0','[data-mc-breadcrumbs]','nav[aria-label*="Breadcrumb" i]','nav[aria-label*="bread" i]','ol[aria-label*="crumb" i]'].join(',');
    function findSource(){ var wrap=byId(SOURCE_WRAP_ID); if (wrap){ var inside=wrap.querySelector(SELECTOR_CRUMBS); if (inside) return inside; } var host=byId(HOST_ID); var all=Array.from(document.querySelectorAll(SELECTOR_CRUMBS)); return all.find(function(n){ return n !== host && !host.contains(n); }) || null; }
    function cloneIntoHost(src, host){ var node=src.cloneNode(true); var existing=host.querySelector(SELECTOR_CRUMBS); if (existing) host.replaceChild(node, existing); else host.appendChild(node); try{ window.__renderAllTopicsAffordance && window.__renderAllTopicsAffordance(); }catch(_){} }
    function readyEnough(el){ return !!(el && el.querySelector && el.querySelector('a, li, span')); }
    function setup(source, host){ cloneIntoHost(source, host); var mo=new MutationObserver(function(){ cloneIntoHost(source, host); }); mo.observe(source, { childList:true, subtree:true, attributes:true, characterData:true }); var tries=0, tick=setInterval(function(){ cloneIntoHost(source, host); if (readyEnough(source) || ++tries > 120) clearInterval(tick); }, 125); setTimeout(function(){ try{ mo.disconnect(); }catch(_){ } }, 30000); }
    function start(){ var host=byId(HOST_ID); if(!host) return; var source=findSource(); if(!source){ var moFind=new MutationObserver(function(){ source=findSource(); if(source){ moFind.disconnect(); setup(source, host); } }); moFind.observe(document.documentElement, { childList:true, subtree:true }); setTimeout(function(){ try{ moFind.disconnect(); }catch(_){ } }, 12000); return; } setup(source, host); }
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once:true }); else start();
  })();

  // ---- Initial layout sync on DOMContentLoaded ------------------------------
  window.addEventListener('DOMContentLoaded', ()=>{
    const sidebar = getSidebar();
    if (!sidebar) return;
    const small = window.matchMedia('(max-width: 900px)').matches;

    // Force a deterministic initial state based on viewport
    if (small){ sidebar.classList.add('collapsed'); }
    else      { sidebar.classList.remove('collapsed'); }

    normalizeLayoutState();
  });

  // ---- Drop Down menu execution ------------------------------
  document.addEventListener("DOMContentLoaded", function () {
    const sel = document.getElementById("quick-nav-select");

    sel.addEventListener("change", function () {
        if (this.value) {
            window.location.href = this.value;
        }
    });
});

})();
