(() => {
  'use strict';
  if (window.__APU_V631_OVERVIEW_VISIBLE__) return;
  window.__APU_V631_OVERVIEW_VISIBLE__ = true;

  const root = document.documentElement;
  const mobile = matchMedia('(max-width:54rem)');
  const labels = {
    id:'Gambaran Ikhtisar', en:'Overview', ms:'Gambaran Keseluruhan',
    de:'Übersicht', vi:'Tổng quan', zh:'概览', ja:'概要'
  };

  function language(){
    const supported = new Set(Object.keys(labels));
    let value = '';
    try { value = window.__APU_GET_LANGUAGE__?.() || ''; } catch (_) {}
    value ||= root.dataset.apuLanguage || '';
    if (!supported.has(value)) {
      try { value = localStorage.getItem('apu-ui-language') || ''; } catch (_) {}
    }
    if (!supported.has(value)) value = (root.lang || 'en').split('-')[0];
    return supported.has(value) ? value : 'en';
  }

  function closeMenus(){
    root.dataset.apuV69MenuOpen = 'false';
    document.querySelectorAll('.apu-v69-malaysia-menu,.apu-final-mobile-drawer,.apu-v5-mobile-nav-drawer,.apu-mobile-drawer-v65,.ai-architect-drawer').forEach(node => {
      node.classList.remove('is-open','open','flex');
      if (node.hasAttribute('aria-hidden')) node.setAttribute('aria-hidden','true');
    });
    document.querySelectorAll('button[aria-expanded="true"]').forEach(button => button.setAttribute('aria-expanded','false'));
  }

  function navFrom(container){
    if (!container) return null;
    return container.matches('nav') ? container : (container.querySelector('nav') || container.querySelector('.apu-final-mobile-links'));
  }

  function candidateNavs(){
    const result = [];
    document.querySelectorAll('.apu-v69-malaysia-menu,.apu-final-mobile-drawer,.apu-v5-mobile-nav-drawer,.apu-mobile-drawer-v65,.ai-architect-drawer').forEach(container => {
      const nav = navFrom(container);
      if (nav && !result.includes(nav)) result.push(nav);
    });
    return result;
  }

  function isOverview(anchor){
    if (!anchor?.matches?.('a[href]')) return false;
    if (anchor.dataset.apuOverview === 'true' || anchor.dataset.apuRouteKey === 'overview') return true;
    let path = '';
    try { path = new URL(anchor.getAttribute('href'), location.href).pathname.replace(/\/index\.html$/,'/'); } catch (_) {}
    if (path === '/') {
      const text = (anchor.textContent || '').replace(/\s+/g,' ').trim().toLowerCase();
      return /overview|gambaran ikhtisar|gambaran keseluruhan|übersicht|tổng quan|概览|概要/.test(text);
    }
    return false;
  }

  function createOverview(){
    const anchor = document.createElement('a');
    anchor.href = '/';
    const icon = document.createElement('span');
    icon.setAttribute('aria-hidden','true');
    icon.textContent = '⌂';
    const text = document.createElement('span');
    text.textContent = labels[language()] || labels.en;
    anchor.append(icon,text);
    return anchor;
  }

  function normalizeOverview(nav){
    if (!nav) return null;
    const all = [...nav.querySelectorAll('a[href]')];
    let overview = all.find(isOverview) || null;
    if (!overview) overview = createOverview();

    // Remove accidental duplicate Overview entries while retaining the first real one.
    all.filter(anchor => anchor !== overview && isOverview(anchor)).forEach(anchor => anchor.remove());

    overview.href = '/';
    overview.dataset.apuOverview = 'true';
    overview.dataset.apuRouteKey = 'overview';
    overview.classList.add('apu-v631-overview-visible');
    overview.hidden = false;
    overview.removeAttribute('aria-hidden');
    overview.style.removeProperty('display');
    overview.style.removeProperty('visibility');
    overview.style.removeProperty('opacity');

    const spans = overview.querySelectorAll('span');
    if (spans.length < 2) {
      overview.replaceChildren();
      const icon = document.createElement('span');
      icon.setAttribute('aria-hidden','true');
      icon.textContent = '⌂';
      const text = document.createElement('span');
      text.textContent = labels[language()] || labels.en;
      overview.append(icon,text);
    } else {
      spans[0].textContent = '⌂';
      spans[spans.length - 1].textContent = labels[language()] || labels.en;
    }

    const atRoot = location.pathname.replace(/\/index\.html$/,'/') === '/';
    if (atRoot) overview.setAttribute('aria-current','page');
    else overview.removeAttribute('aria-current');

    if (overview !== nav.firstElementChild) nav.prepend(overview);
    return overview;
  }

  function resetScroller(nav){
    const container = nav.closest('.apu-v69-malaysia-menu,.apu-final-mobile-drawer,.apu-v5-mobile-nav-drawer,.apu-mobile-drawer-v65,.ai-architect-drawer');
    [nav, container].filter(Boolean).forEach(node => {
      node.style.setProperty('scroll-behavior','auto','important');
      node.scrollTop = 0;
      node.scrollLeft = 0;
    });
  }

  function makeVisible(){
    if (!mobile.matches) return;
    candidateNavs().forEach(nav => {
      const overview = normalizeOverview(nav);
      resetScroller(nav);
      if (overview) {
        const rect = overview.getBoundingClientRect();
        if (rect.height === 0 || rect.bottom <= 0) {
          overview.style.setProperty('display','grid','important');
          overview.style.setProperty('visibility','visible','important');
          overview.style.setProperty('opacity','1','important');
        }
      }
    });
    root.dataset.apuV631OverviewVisible = 'true';
  }

  function resetAfterOpen(){
    [0, 32, 96, 220].forEach(delay => setTimeout(() => {
      makeVisible();
      candidateNavs().forEach(resetScroller);
    }, delay));
  }

  document.addEventListener('click', event => {
    const toggle = event.target.closest?.('.apu-v69-native-toggle,.apu-final-mobile-menu,[aria-controls="apuV69NativeMenu"],[aria-controls*="Drawer" i]');
    if (toggle) resetAfterOpen();

    const overview = event.target.closest?.('.apu-v631-overview-visible');
    if (!overview) return;
    const atRoot = location.pathname.replace(/\/index\.html$/,'/') === '/';
    closeMenus();
    if (atRoot) {
      event.preventDefault();
      scrollTo({top:0,left:0,behavior:matchMedia('(prefers-reduced-motion:reduce)').matches?'auto':'smooth'});
    }
  }, true);

  let queued = false;
  const schedule = () => {
    if (queued) return;
    queued = true;
    requestAnimationFrame(() => { queued = false; makeVisible(); });
  };

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', resetAfterOpen, {once:true});
  else resetAfterOpen();
  addEventListener('load', resetAfterOpen, {once:true});
  addEventListener('apu:languagechange', resetAfterOpen);
  addEventListener('storage', event => { if (event.key === 'apu-ui-language') resetAfterOpen(); });
  mobile.addEventListener?.('change', resetAfterOpen);

  const observer = new MutationObserver(records => {
    if (!mobile.matches) return;
    for (const record of records) {
      if (record.type === 'childList' || record.attributeName === 'class' || record.attributeName === 'aria-expanded' || record.attributeName === 'aria-hidden') {
        schedule();
        break;
      }
    }
  });
  observer.observe(document.documentElement, {subtree:true, childList:true, attributes:true, attributeFilter:['class','aria-expanded','aria-hidden']});
  setTimeout(() => observer.disconnect(), 12000);
})();
