(() => {
  'use strict';

  const CONFIG = {"slug": "computer-vision", "icon": "/icons/icon-64.png", "title": "Computer Vision Image Classification"};
  const projectPrefix = `/projects/${CONFIG.slug}`;
  const iconUrl = CONFIG.icon || '/icons/icon-64.png';
  const mobile = matchMedia('(max-width: 760px)');

  function cleanPath(pathname) {
    if (!pathname) return '/';
    let path = pathname;
    try { path = new URL(pathname, location.href).pathname; } catch (_) {}
    if (path === projectPrefix || path === `${projectPrefix}/`) return '/';
    if (path.startsWith(`${projectPrefix}/`)) {
      path = path.slice(projectPrefix.length);
      if (!path.startsWith('/')) path = `/${path}`;
      return path || '/';
    }
    return path;
  }

  function standaloneHref(raw) {
    if (!raw || raw.startsWith('#') || /^(mailto:|tel:|javascript:|data:)/i.test(raw)) return raw;
    let url;
    try { url = new URL(raw, location.href); } catch (_) { return raw; }
    if (url.origin !== location.origin) return raw;
    const translated = cleanPath(url.pathname);
    if (translated === url.pathname) return raw;
    return `${translated}${url.search}${url.hash}`;
  }

  function rewriteAnchor(anchor) {
    if (!anchor || !anchor.getAttribute) return;
    const raw = anchor.getAttribute('href');
    const translated = standaloneHref(raw);
    if (translated && translated !== raw) {
      anchor.setAttribute('href', translated);
      anchor.dataset.apuV629RouteFixed = 'true';
    }
  }

  function rewriteAll(root = document) {
    if (root.matches?.('a[href]')) rewriteAnchor(root);
    root.querySelectorAll?.('a[href]').forEach(rewriteAnchor);
  }

  function routeFromAnchor(anchor) {
    const raw = anchor?.getAttribute?.('href');
    if (!raw || raw.startsWith('#') || /^(mailto:|tel:|javascript:|data:)/i.test(raw)) return null;
    let url;
    try { url = new URL(raw, location.href); } catch (_) { return null; }
    if (url.origin !== location.origin) return null;
    const pathname = cleanPath(url.pathname);
    // Only handle a local physical project page or a translated legacy project route.
    const wasLegacy = url.pathname === projectPrefix || url.pathname.startsWith(`${projectPrefix}/`);
    const isLocalPage = pathname === '/' || !!pathname.match(/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*\/?$/);
    if (!wasLegacy && !anchor.dataset.apuV629RouteFixed) return null;
    if (!isLocalPage) return null;
    return `${pathname}${url.search}${url.hash}`;
  }

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

  function handleNavigation(event) {
    const anchor = event.target.closest?.('a[href]');
    if (!anchor) return;
    const destination = routeFromAnchor(anchor);
    if (!destination) return;
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation?.();
    closeMenus();
    requestAnimationFrame(() => location.assign(destination));
  }

  function syncProjectIcons(root = document) {
    const selectors = [
      '.apu-v69-native-mark',
      '.apu-final-mobile-mark',
      '.apu-v52-cv-mark',
      '.apu-v54-cv-mobile-mark',
      '.apu-v5-mobile-project-mark',
      '.apu-mobile-project-mark',
      '.apu-mobile-header-v65 [class*="mark"]'
    ].join(',');
    root.querySelectorAll?.(selectors).forEach(mark => {
      if (mark.dataset.apuV629IconSynced === 'true') return;
      if (!mark.closest('header,nav,[class*="mobile" i]')) return;
      mark.dataset.apuV629IconSynced = 'true';
      mark.classList.add('apu-v629-synced-project-icon');
      const img = document.createElement('img');
      img.src = iconUrl;
      img.alt = '';
      img.width = 64;
      img.height = 64;
      img.decoding = 'async';
      mark.replaceChildren(img);
    });
  }

  function normalizeHistoryMethod(name) {
    const original = history[name];
    if (typeof original !== 'function') return;
    history[name] = function(state, title, url) {
      if (typeof url === 'string') url = standaloneHref(url) || url;
      return original.call(this, state, title, url);
    };
  }

  normalizeHistoryMethod('pushState');
  normalizeHistoryMethod('replaceState');

  // Capture phase is deliberate: React/router handlers must not send a standalone site
  // to the old /projects/<slug>/... portal path.
  document.addEventListener('click', handleNavigation, true);

  function boot() {
    rewriteAll(document);
    if (mobile.matches) syncProjectIcons(document);
    const observer = new MutationObserver(records => {
      for (const record of records) {
        record.addedNodes.forEach(node => {
          if (node.nodeType !== 1) return;
          rewriteAll(node);
          if (mobile.matches) syncProjectIcons(node);
        });
        if (record.type === 'attributes' && record.target.matches?.('a[href]')) rewriteAnchor(record.target);
      }
    });
    observer.observe(document.documentElement, {subtree:true, childList:true, attributes:true, attributeFilter:['href']});
    setTimeout(() => { rewriteAll(document); if (mobile.matches) syncProjectIcons(document); }, 300);
    setTimeout(() => { rewriteAll(document); if (mobile.matches) syncProjectIcons(document); }, 1200);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, {once:true});
  else boot();
})();
