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

  const root = document.documentElement;
  const project = root.dataset.scrollTheme || '';
  const isMobile = matchMedia('(max-width: 54rem)');

  const TEXT = {
    id: {
      overview:'Gambaran Ikhtisar', dataset:'Kumpulan Data', model:'Model', models:'Model', results:'Hasil', failure:'Analisis Kegagalan', limitations:'Keterbatasan', source:'Kode Sumber', technical:'Laporan Teknis',
      dashboard:'Dasbor', incidents:'Insiden', timeline:'Linimasa', reports:'Laporan', tickets:'Tiket', assets:'Inventaris Aset',
      costs:'Biaya', housing:'Perumahan', simulator:'Simulator', methodology:'Metodologi', calculator:'Kalkulator', troubleshoot:'Pemecahan Masalah', tutorial:'Tutorial', segmentation:'Segmentasi', history:'Riwayat',
      feedback:'Umpan Balik', topics:'Topik', keywords:'Kata Kunci', categories:'Kategori', recommendations:'Rekomendasi', evaluation:'Evaluasi Model', create:'Buat Tautan', analytics:'Analitik', campaigns:'Kampanye',
      projects:'Proyek', cv:'CV', certificates:'Sertifikat', research:'Riset', github:'GitHub', admission:'Penerimaan', rag:'RAG', support:'Dukungan', predict:'Prediksi', mlops:'MLOps', security:'Keamanan', agents:'Agen', governance:'Tata Kelola', roi:'ROI', cloud:'Perbandingan Cloud', blueprints:'Cetak Biru', documents:'Dokumen', resume:'Resume', contact:'Kontak', students:'Siswa', fairness:'Keadilan', report:'Laporan',
      open:'Buka menu navigasi', close:'Tutup menu navigasi'
    },
    en: {
      overview:'Overview', dataset:'Dataset', model:'Model', models:'Models', results:'Results', failure:'Failure Analysis', limitations:'Limitations', source:'Source Code', technical:'Technical Report',
      dashboard:'Dashboard', incidents:'Incidents', timeline:'Timeline', reports:'Reports', tickets:'Tickets', assets:'Asset Inventory',
      costs:'Costs', housing:'Housing', simulator:'Simulator', methodology:'Methodology', calculator:'Calculator', troubleshoot:'Troubleshooting', tutorial:'Tutorial', segmentation:'Segmentation', history:'History',
      feedback:'Feedback', topics:'Topics', keywords:'Keywords', categories:'Categories', recommendations:'Recommendations', evaluation:'Model Evaluation', create:'Create Link', analytics:'Analytics', campaigns:'Campaigns',
      projects:'Projects', cv:'CV', certificates:'Certificates', research:'Research', github:'GitHub', admission:'Admission', rag:'RAG', support:'Support', predict:'Prediction', mlops:'MLOps', security:'Security', agents:'Agents', governance:'Governance', roi:'ROI', cloud:'Cloud Comparison', blueprints:'Blueprints', documents:'Documents', resume:'Resume', contact:'Contact', students:'Students', fairness:'Fairness', report:'Report',
      open:'Open navigation menu', close:'Close navigation menu'
    },
    ms: {
      overview:'Gambaran Keseluruhan', dataset:'Set Data', model:'Model', models:'Model', results:'Keputusan', failure:'Analisis Kegagalan', limitations:'Batasan', source:'Kod Sumber', technical:'Laporan Teknikal',
      dashboard:'Papan Pemuka', incidents:'Insiden', timeline:'Garis Masa', reports:'Laporan', tickets:'Tiket', assets:'Inventori Aset',
      costs:'Kos', housing:'Perumahan', simulator:'Simulator', methodology:'Metodologi', calculator:'Kalkulator', troubleshoot:'Penyelesaian Masalah', tutorial:'Tutorial', segmentation:'Segmentasi', history:'Sejarah',
      feedback:'Maklum Balas', topics:'Topik', keywords:'Kata Kunci', categories:'Kategori', recommendations:'Cadangan', evaluation:'Penilaian Model', create:'Cipta Pautan', analytics:'Analitik', campaigns:'Kempen',
      projects:'Projek', cv:'CV', certificates:'Sijil', research:'Penyelidikan', github:'GitHub', admission:'Kemasukan', rag:'RAG', support:'Sokongan', predict:'Ramalan', mlops:'MLOps', security:'Keselamatan', agents:'Ejen', governance:'Tadbir Urus', roi:'ROI', cloud:'Perbandingan Awan', blueprints:'Pelan Tindakan', documents:'Dokumen', resume:'Resume', contact:'Hubungi', students:'Pelajar', fairness:'Keadilan', report:'Laporan',
      open:'Buka menu navigasi', close:'Tutup menu navigasi'
    },
    de: {
      overview:'Übersicht', dataset:'Datensatz', model:'Modell', models:'Modelle', results:'Ergebnisse', failure:'Fehleranalyse', limitations:'Einschränkungen', source:'Quellcode', technical:'Technischer Bericht',
      dashboard:'Dashboard', incidents:'Vorfälle', timeline:'Zeitleiste', reports:'Berichte', tickets:'Tickets', assets:'Anlagenbestand',
      costs:'Kosten', housing:'Wohnen', simulator:'Simulator', methodology:'Methodik', calculator:'Rechner', troubleshoot:'Fehlerbehebung', tutorial:'Tutorial', segmentation:'Segmentierung', history:'Verlauf',
      feedback:'Feedback', topics:'Themen', keywords:'Schlüsselwörter', categories:'Kategorien', recommendations:'Empfehlungen', evaluation:'Modellbewertung', create:'Link erstellen', analytics:'Analytik', campaigns:'Kampagnen',
      projects:'Projekte', cv:'Lebenslauf', certificates:'Zertifikate', research:'Forschung', github:'GitHub', admission:'Zulassung', rag:'RAG', support:'Support', predict:'Vorhersage', mlops:'MLOps', security:'Sicherheit', agents:'Agenten', governance:'Governance', roi:'ROI', cloud:'Cloud-Vergleich', blueprints:'Blaupausen', documents:'Dokumente', resume:'Lebenslauf', contact:'Kontakt', students:'Studierende', fairness:'Fairness', report:'Bericht',
      open:'Navigationsmenü öffnen', close:'Navigationsmenü schließen'
    },
    vi: {
      overview:'Tổng quan', dataset:'Tập dữ liệu', model:'Mô hình', models:'Các mô hình', results:'Kết quả', failure:'Phân tích lỗi', limitations:'Hạn chế', source:'Mã nguồn', technical:'Báo cáo kỹ thuật',
      dashboard:'Bảng điều khiển', incidents:'Sự cố', timeline:'Dòng thời gian', reports:'Báo cáo', tickets:'Phiếu hỗ trợ', assets:'Kho tài sản',
      costs:'Chi phí', housing:'Nhà ở', simulator:'Mô phỏng', methodology:'Phương pháp', calculator:'Máy tính', troubleshoot:'Khắc phục sự cố', tutorial:'Hướng dẫn', segmentation:'Phân đoạn', history:'Lịch sử',
      feedback:'Phản hồi', topics:'Chủ đề', keywords:'Từ khóa', categories:'Danh mục', recommendations:'Đề xuất', evaluation:'Đánh giá mô hình', create:'Tạo liên kết', analytics:'Phân tích', campaigns:'Chiến dịch',
      projects:'Dự án', cv:'CV', certificates:'Chứng chỉ', research:'Nghiên cứu', github:'GitHub', admission:'Tuyển sinh', rag:'RAG', support:'Hỗ trợ', predict:'Dự đoán', mlops:'MLOps', security:'Bảo mật', agents:'Tác nhân', governance:'Quản trị', roi:'ROI', cloud:'So sánh đám mây', blueprints:'Bản thiết kế', documents:'Tài liệu', resume:'Hồ sơ', contact:'Liên hệ', students:'Sinh viên', fairness:'Công bằng', report:'Báo cáo',
      open:'Mở menu điều hướng', close:'Đóng menu điều hướng'
    },
    zh: {
      overview:'概览', dataset:'数据集', model:'模型', models:'模型', results:'结果', failure:'失败分析', limitations:'局限性', source:'源代码', technical:'技术报告',
      dashboard:'仪表板', incidents:'事件', timeline:'时间线', reports:'报告', tickets:'工单', assets:'资产清单',
      costs:'费用', housing:'住房', simulator:'模拟器', methodology:'方法论', calculator:'计算器', troubleshoot:'故障排除', tutorial:'教程', segmentation:'分段', history:'历史',
      feedback:'反馈', topics:'主题', keywords:'关键词', categories:'类别', recommendations:'建议', evaluation:'模型评估', create:'创建链接', analytics:'分析', campaigns:'活动',
      projects:'项目', cv:'简历', certificates:'证书', research:'研究', github:'GitHub', admission:'招生', rag:'RAG', support:'支持', predict:'预测', mlops:'MLOps', security:'安全', agents:'智能体', governance:'治理', roi:'ROI', cloud:'云对比', blueprints:'蓝图', documents:'文档', resume:'简历', contact:'联系', students:'学生', fairness:'公平性', report:'报告',
      open:'打开导航菜单', close:'关闭导航菜单'
    },
    ja: {
      overview:'概要', dataset:'データセット', model:'モデル', models:'モデル', results:'結果', failure:'失敗分析', limitations:'制限事項', source:'ソースコード', technical:'技術レポート',
      dashboard:'ダッシュボード', incidents:'インシデント', timeline:'タイムライン', reports:'レポート', tickets:'チケット', assets:'資産インベントリ',
      costs:'費用', housing:'住宅', simulator:'シミュレーター', methodology:'方法論', calculator:'計算機', troubleshoot:'トラブルシューティング', tutorial:'チュートリアル', segmentation:'セグメンテーション', history:'履歴',
      feedback:'フィードバック', topics:'トピック', keywords:'キーワード', categories:'カテゴリー', recommendations:'推奨事項', evaluation:'モデル評価', create:'リンク作成', analytics:'分析', campaigns:'キャンペーン',
      projects:'プロジェクト', cv:'CV', certificates:'証明書', research:'研究', github:'GitHub', admission:'入学', rag:'RAG', support:'サポート', predict:'予測', mlops:'MLOps', security:'セキュリティ', agents:'エージェント', governance:'ガバナンス', roi:'ROI', cloud:'クラウド比較', blueprints:'ブループリント', documents:'ドキュメント', resume:'履歴書', contact:'お問い合わせ', students:'学生', fairness:'公平性', report:'レポート',
      open:'ナビゲーションメニューを開く', close:'ナビゲーションメニューを閉じる'
    }
  };

  const PROJECTS = {
    'computer-vision': {
      full:{id:'Klasifikasi Gambar Visi Komputer',en:'Computer Vision Image Classification',ms:'Pengelasan Imej Penglihatan Komputer',de:'Bildklassifizierung mit Computer Vision',vi:'Phân loại hình ảnh thị giác máy tính',zh:'计算机视觉图像分类',ja:'コンピュータビジョン画像分類'},
      title:{id:'Pusat Penelitian CV',en:'CV Research Hub',ms:'Pusat Penyelidikan CV',de:'CV-Forschungszentrum',vi:'Trung tâm Nghiên cứu CV',zh:'计算机视觉研究中心',ja:'コンピュータビジョン研究拠点'},
      routes:[['⌂','overview','/'],['◫','dataset','/dataset/'],['△','model','/model/'],['⌁','results','/results/'],['⚠','failure','/analysis/'],['✓','limitations','/limitations/'],['</>','source','/code/'],['▤','technical','/report/']]
    },
    'incident-monitoring': {title:{id:'Pemantauan Insiden',en:'Incident Monitoring',ms:'Pemantauan Insiden',de:'Incident Monitoring',vi:'Giám sát sự cố',zh:'事件监控',ja:'インシデント監視'},routes:[['⌂','overview','/'],['▦','dashboard','/dashboard/'],['⚠','incidents','/incidents/'],['⌁','timeline','/timeline/'],['▤','reports','/reports/']]},
    'it-helpdesk': {title:{id:'Meja Bantuan TI',en:'IT Helpdesk',ms:'Meja Bantuan IT',de:'IT-Helpdesk',vi:'Bộ phận hỗ trợ CNTT',zh:'IT 服务台',ja:'ITヘルプデスク'},routes:[['⌂','overview','/'],['☷','tickets','/tickets/'],['▣','assets','/assets/'],['▤','reports','/reports/']]},
    'kotlin-policy': {title:{id:'Kebijakan Perangkat Android',en:'Android Device Policy',ms:'Dasar Peranti Android',de:'Android-Geräterichtlinie',vi:'Chính sách thiết bị Android',zh:'Android 设备策略',ja:'Androidデバイスポリシー'},routes:[['⌂','overview','/']]},
    'malaysia-cost': {title:{id:'Perencana Biaya Malaysia',en:'Malaysia Cost Planner',ms:'Perancang Kos Malaysia',de:'Malaysia-Kostenplaner',vi:'Lập kế hoạch chi phí Malaysia',zh:'马来西亚生活成本规划',ja:'マレーシア生活費プランナー'},routes:[['⌂','overview','/'],['₿','costs','/costs/'],['⌂','housing','/housing/'],['◉','simulator','/simulator/'],['▤','methodology','/methodology/']]},
    'network-subnet': {title:{id:'Pemecah Masalah Subnet',en:'Network Subnet Troubleshooter',ms:'Penyelesai Masalah Subnet',de:'Subnet-Fehlerbehebung',vi:'Khắc phục sự cố mạng con',zh:'网络子网故障排除',ja:'ネットワークサブネット診断'},routes:[['⌂','overview','/'],['#','calculator','/calculator/'],['⚙','troubleshoot','/troubleshoot/'],['?','tutorial','/tutorial/'],['▥','segmentation','/segmentation/'],['⌁','history','/history/']]},
    'sentiment-analysis': {title:{id:'Analisis Sentimen Teks',en:'Text Sentiment Analysis',ms:'Analisis Sentimen Teks',de:'Text-Sentimentanalyse',vi:'Phân tích cảm xúc văn bản',zh:'文本情感分析',ja:'テキスト感情分析'},routes:[['⌂','overview','/'],['☷','feedback','/feedback/'],['◫','topics','/topics/'],['⌕','keywords','/keywords/'],['▥','categories','/categories/'],['✦','recommendations','/recommendations/'],['△','evaluation','/model/']]},
    'url-shortener': {title:{id:'Pemendek URL',en:'URL Shortener',ms:'Pemendek URL',de:'URL-Kürzer',vi:'Trình rút gọn URL',zh:'网址缩短器',ja:'URL短縮'},routes:[['⌂','overview','/'],['＋','create','/create/'],['◉','analytics','/analytics/'],['✦','campaigns','/campaigns/']]},
    'academic-evidence': {title:{id:'Bukti Akademik',en:'Academic Evidence',ms:'Bukti Akademik',de:'Akademische Nachweise',vi:'Minh chứng học thuật',zh:'学术证明',ja:'学術エビデンス'},routes:[['⌂','overview','/'],['▦','projects','/projects/'],['CV','cv','/cv/'],['★','certificates','/certificates/'],['⌕','research','/research/'],['GH','github','/github/'],['▤','reports','/reports/'],['</>','source','/source/'],['✓','admission','/admission/']]},
    'ai-architect': {title:{id:'Laboratorium Arsitek AI',en:'AI Architect Lab',ms:'Makmal Arkitek AI',de:'KI-Architekturlabor',vi:'Phòng thí nghiệm kiến trúc AI',zh:'AI 架构实验室',ja:'AIアーキテクトラボ'},routes:[['⌂','overview','/'],['R','rag','/rag/'],['S','support','/support/'],['P','predict','/predict/'],['M','mlops','/mlops/'],['🔒','security','/security/'],['A','agents','/agents/'],['G','governance','/governance/'],['%','roi','/roi/'],['☁','cloud','/cloud-compare/'],['▧','blueprints','/blueprints/'],['▤','documents','/documents/'],['CV','resume','/resume/'],['✉','contact','/contact/']]},
    'student-performance': {title:{id:'Kinerja Siswa AI',en:'Student Performance AI',ms:'Prestasi Pelajar AI',de:'KI-Schülerleistung',vi:'Hiệu suất học sinh AI',zh:'AI 学生表现',ja:'AI学生パフォーマンス'},routes:[['⌂','overview','/'],['♟','students','/students/'],['△','models','/models/'],['⚖','fairness','/fairness/'],['✦','recommendations','/recommendations/'],['▤','report','/report/']]}
  };

  const config = PROJECTS[project];
  if (!config) return;

  const normalizedPath = () => {
    let path = location.pathname.replace(/\/index\.html$/i, '/');
    if (!path.endsWith('/')) path += '/';
    return path;
  };

  const language = () => {
    const supported = new Set(['id','en','ms','de','vi','zh','ja']);
    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';
  };

  const titleFor = lang => config.title?.[lang] || config.title?.en || '';
  const fullTitleFor = lang => config.full?.[lang] || titleFor(lang);
  const labelFor = (key, lang) => TEXT[lang]?.[key] || TEXT.en[key] || key;

  function removeExitControls(scope = document) {
    scope.querySelectorAll?.('.apu-v69-exit-link,.apu-final-mobile-exit,.apu-mobile-exit,.project-exit-link,[data-apu-action="exit-project"]').forEach(node => node.remove());
    scope.querySelectorAll?.('a,button').forEach(node => {
      const text = (node.textContent || '').replace(/\s+/g,' ').trim().toLowerCase();
      if (/keluar ke project universe|keluar ke proyek universe|exit to project universe|return to project universe|projek universe|project universe/.test(text)) node.remove();
    });
  }

  function createLink(icon, key, href, lang, current) {
    const anchor = document.createElement('a');
    anchor.href = href;
    anchor.dataset.apuRouteKey = key;
    if (key === 'overview') anchor.dataset.apuOverview = 'true';
    if (href === current) anchor.setAttribute('aria-current','page');
    const iconNode = document.createElement('span');
    iconNode.setAttribute('aria-hidden','true');
    iconNode.textContent = icon;
    const label = document.createElement('span');
    label.textContent = labelFor(key, lang);
    anchor.append(iconNode,label);
    return anchor;
  }

  function rebuildV69Menu(menu, lang) {
    const current = normalizedPath();
    const fragment = document.createDocumentFragment();
    for (const [icon,key,href] of config.routes) fragment.appendChild(createLink(icon,key,href,lang,current));
    menu.replaceChildren(fragment);
    menu.setAttribute('aria-label', `${titleFor(lang)} — ${labelFor('overview',lang)}`);
    menu.dataset.apuTranslatedLanguage = lang;
  }

  function patchGenericDrawer(drawer, lang) {
    removeExitControls(drawer);
    const nav = drawer.matches('nav') ? drawer : drawer.querySelector('nav') || drawer.querySelector('.apu-final-mobile-links');
    if (!nav) return;
    const current = normalizedPath();
    const byPath = new Map(config.routes.map(route => [route[2], route]));
    const anchors = [...nav.querySelectorAll('a[href]')];
    for (const anchor of anchors) {
      let path = '';
      try { path = new URL(anchor.getAttribute('href'), location.href).pathname; } catch (_) {}
      path = path.replace(new RegExp(`^/projects/${project}`), '') || '/';
      if (!path.endsWith('/')) path += '/';
      const route = byPath.get(path);
      if (!route) continue;
      anchor.href = route[2];
      anchor.dataset.apuRouteKey = route[1];
      if (route[1] === 'overview') anchor.dataset.apuOverview = 'true';
      const spans = anchor.querySelectorAll('span');
      const label = spans.length > 1 ? spans[spans.length - 1] : anchor;
      label.textContent = labelFor(route[1],lang);
      if (route[2] === current) anchor.setAttribute('aria-current','page'); else anchor.removeAttribute('aria-current');
    }
    let overview = nav.querySelector('[data-apu-overview="true"]');
    if (!overview) {
      overview = createLink('⌂','overview','/',lang,current);
      nav.prepend(overview);
    } else if (overview !== nav.firstElementChild) {
      nav.prepend(overview);
    }
  }

  function updateHeader(lang) {
    const current = normalizedPath();
    const active = config.routes.find(route => route[2] === current) || config.routes[0];
    const title = titleFor(lang);
    const activeLabel = labelFor(active[1],lang);

    const brand = document.querySelector('.apu-v69-native-brand');
    if (brand) {
      const strong = brand.querySelector('strong');
      const small = brand.querySelector('small');
      if (strong) strong.textContent = title;
      if (small) small.textContent = activeLabel;
    }
    document.querySelectorAll('.apu-final-mobile-brand').forEach(node => {
      const strong = node.querySelector('strong');
      const small = node.querySelector('small');
      if (strong) strong.textContent = title;
      if (small) small.textContent = activeLabel;
    });
    document.querySelectorAll('.apu-final-drawer-head').forEach(node => {
      const strong = node.querySelector('strong');
      if (strong) strong.textContent = title;
    });
    const utilityTitle = document.querySelector('#apu-v624-brand-copy strong');
    if (utilityTitle) utilityTitle.textContent = fullTitleFor(lang);
    const toggle = document.querySelector('.apu-v69-native-toggle');
    if (toggle) toggle.setAttribute('aria-label', toggle.getAttribute('aria-expanded') === 'true' ? TEXT[lang].close : TEXT[lang].open);
    document.title = fullTitleFor(lang) || document.title;
  }

  function closeMenuAfterOverview() {
    document.querySelectorAll('[data-apu-overview="true"]').forEach(anchor => {
      if (anchor.dataset.apuOverviewBound === 'true') return;
      anchor.dataset.apuOverviewBound = 'true';
      anchor.addEventListener('click', event => {
        if (normalizedPath() !== '/') return;
        event.preventDefault();
        root.dataset.apuV69MenuOpen = 'false';
        document.querySelectorAll('.is-open').forEach(node => node.classList.remove('is-open'));
        document.querySelectorAll('[aria-expanded="true"]').forEach(node => node.setAttribute('aria-expanded','false'));
        scrollTo({top:0,behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'});
      });
    });
  }

  function apply() {
    if (!isMobile.matches) return;
    const lang = language();
    removeExitControls(document);
    const nativeMenu = document.querySelector('.apu-v69-malaysia-menu');
    if (nativeMenu) rebuildV69Menu(nativeMenu,lang);
    document.querySelectorAll('.apu-final-mobile-drawer,.apu-v5-mobile-nav-drawer,.apu-mobile-drawer-v65,.ai-architect-drawer').forEach(drawer => patchGenericDrawer(drawer,lang));
    updateHeader(lang);
    closeMenuAfterOverview();
    root.dataset.apuV630MobileMenuFixed = 'true';
  }

  let timer = 0;
  const schedule = () => {
    clearTimeout(timer);
    timer = setTimeout(apply,16);
  };

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',apply,{once:true}); else apply();
  addEventListener('load',apply,{once:true});
  addEventListener('apu:languagechange',apply);
  addEventListener('storage',event => { if (event.key === 'apu-ui-language') apply(); });
  isMobile.addEventListener?.('change',apply);
  [120,350,900,1800,3500].forEach(delay => setTimeout(apply,delay));

  const observer = new MutationObserver(schedule);
  observer.observe(document.documentElement,{subtree:true,childList:true});
  setTimeout(() => observer.disconnect(),10000);
})();
