/* AI Project Universe V6.16 — low-overhead mobile native scroll repair */
(() => {
  'use strict';

  const root = document.documentElement;
  const theme = () => root.dataset.scrollTheme || '';
  const studentMQ = matchMedia('(max-width: 820px)');
  const architectMQ = matchMedia('(max-width: 767px)');
  let scheduled = false;
  let aiObserver = null;

  const setImportant = (node, name, value) => {
    if (!node) return;
    if (node.style.getPropertyValue(name) !== value || node.style.getPropertyPriority(name) !== 'important') {
      node.style.setProperty(name, value, 'important');
    }
  };

  function repairStudent() {
    if (theme() !== 'student-performance' || !studentMQ.matches) return;

    setImportant(root, 'height', 'auto');
    setImportant(root, 'min-height', '100%');
    setImportant(root, 'max-height', 'none');
    setImportant(root, 'overflow-x', 'hidden');
    setImportant(root, 'overflow-y', 'auto');
    setImportant(root, 'scroll-behavior', 'auto');
    setImportant(root, 'overscroll-behavior-y', 'auto');
    setImportant(root, 'touch-action', 'pan-y pinch-zoom');

    setImportant(document.body, 'height', 'auto');
    setImportant(document.body, 'min-height', '100%');
    setImportant(document.body, 'max-height', 'none');
    setImportant(document.body, 'overflow', 'visible');
    setImportant(document.body, 'position', 'static');
    setImportant(document.body, 'scroll-behavior', 'auto');
    setImportant(document.body, 'overscroll-behavior-y', 'auto');
    setImportant(document.body, 'touch-action', 'pan-y pinch-zoom');

    document.querySelectorAll('.sp-app,.sp-main,.sp-view,.sp-view.is-active').forEach(node => {
      setImportant(node, 'height', 'auto');
      setImportant(node, 'min-height', '0');
      setImportant(node, 'max-height', 'none');
      setImportant(node, 'overflow-y', 'visible');
      setImportant(node, 'scroll-snap-type', 'none');
      setImportant(node, 'contain', 'none');
      setImportant(node, 'transform', 'none');
      setImportant(node, 'will-change', 'auto');
    });

    document.querySelectorAll('.sp-scroll-end').forEach(node => node.remove());
    root.dataset.apuV616StudentScroller = document.scrollingElement === root ? 'html' : 'document';
  }

  function getArchitectParts() {
    const drawer = document.querySelector('aside.ai-architect-drawer') || document.querySelector('.ai-architect-drawer');
    return { drawer, nav: drawer?.querySelector('nav') || null, trigger: document.querySelector('.ai-menu-trigger') };
  }

  function repairArchitect() {
    if (theme() !== 'ai-architect' || !architectMQ.matches) return;
    const { drawer, nav } = getArchitectParts();
    if (!drawer || !nav) return;

    setImportant(drawer, 'top', '58px');
    setImportant(drawer, 'bottom', 'env(safe-area-inset-bottom)');
    setImportant(drawer, 'height', 'auto');
    setImportant(drawer, 'min-height', '0');
    setImportant(drawer, 'max-height', 'none');
    setImportant(drawer, 'overflow', 'hidden');
    setImportant(drawer, 'flex-direction', 'column');
    setImportant(drawer, 'touch-action', 'pan-y');

    setImportant(nav, 'flex', '1 1 0');
    setImportant(nav, 'height', '0');
    setImportant(nav, 'min-height', '0');
    setImportant(nav, 'max-height', 'none');
    setImportant(nav, 'overflow-x', 'hidden');
    setImportant(nav, 'overflow-y', 'auto');
    setImportant(nav, 'scroll-behavior', 'auto');
    setImportant(nav, 'overscroll-behavior-y', 'contain');
    setImportant(nav, 'touch-action', 'pan-y');
    setImportant(nav, 'pointer-events', 'auto');
    nav.dataset.apuV616VerticalScroller = 'true';

    const opened = !drawer.classList.contains('hidden') && getComputedStyle(drawer).display !== 'none';
    root.classList.toggle('ai-architect-nav-open', opened);
    document.body.classList.toggle('ai-architect-nav-open', opened);
    root.dataset.apuV616AiDrawer = opened ? 'open' : 'closed';
  }

  function scheduleRepair() {
    if (scheduled) return;
    scheduled = true;
    requestAnimationFrame(() => {
      scheduled = false;
      repairStudent();
      repairArchitect();
    });
  }

  function bindArchitect() {
    if (theme() !== 'ai-architect' || !architectMQ.matches) return;
    const { drawer, trigger } = getArchitectParts();
    if (!drawer || !trigger) return;

    if (!trigger.dataset.apuV616Bound) {
      trigger.dataset.apuV616Bound = 'true';
      trigger.addEventListener('click', () => requestAnimationFrame(repairArchitect), { passive: true });
    }

    if (!aiObserver) {
      aiObserver = new MutationObserver(repairArchitect);
      aiObserver.observe(drawer, { attributes: true, attributeFilter: ['class', 'style'] });
    }
  }

  function boot() {
    scheduleRepair();
    bindArchitect();

    /* React hydration can create the drawer shortly after DOMContentLoaded. Retry briefly,
       then stop — no long-running whole-document observer, so scrolling stays smooth. */
    let tries = 0;
    const timer = setInterval(() => {
      scheduleRepair();
      bindArchitect();
      if (++tries >= 24 || (theme() !== 'ai-architect' && theme() !== 'student-performance')) clearInterval(timer);
      if (theme() === 'ai-architect' && getArchitectParts().drawer && tries >= 6) clearInterval(timer);
      if (theme() === 'student-performance' && document.querySelector('.sp-app') && tries >= 3) clearInterval(timer);
    }, 120);

    addEventListener('pageshow', scheduleRepair, { passive: true });
    addEventListener('orientationchange', () => setTimeout(scheduleRepair, 120), { passive: true });
    studentMQ.addEventListener?.('change', scheduleRepair);
    architectMQ.addEventListener?.('change', scheduleRepair);
  }

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