/// file: public/assets/js/modules/menu.js

import { isWorkProjectDetailHref } from './page-transitions.js';
import { SKIP_PRELOADER_KEY } from './preloader.js';

/** Scroll position before modal lock; restored when menu closes. */
let discoverLockScrollY = 0;

export function initMenu() {
  const overlay = document.getElementById('discover-overlay');
  const openBtn = document.getElementById('menu-open');
  const closeBtn = document.getElementById('menu-close');
  const backdrop = overlay?.querySelector('[data-discover-backdrop]');
  if (!overlay || !openBtn || !closeBtn) return;

  const heroVideo = document.querySelector('[data-home-hero-video-wrap] video');
  const cursorGlowReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  let glowMoveRaf = 0;
  let glowPending = /** @type {{ x: number; y: number } | null} */ (null);

  const flushDiscoverGlow = () => {
    glowMoveRaf = 0;
    if (!glowPending || !overlay.classList.contains('is-open')) return;
    const { x, y } = glowPending;
    glowPending = null;
    overlay.style.setProperty('--discover-mx', `${x}%`);
    overlay.style.setProperty('--discover-my', `${y}%`);
    /* Parallax mesh drift (CSS uses px; reduced-motion handled in CSS). */
    overlay.style.setProperty('--discover-tx', `${(x - 50) * -8}px`);
    overlay.style.setProperty('--discover-ty', `${(y - 50) * -6}px`);
  };

  const onDiscoverPointerMove = (e) => {
    if (cursorGlowReduced || !overlay.classList.contains('is-open')) return;
    const box = overlay.getBoundingClientRect();
    if (box.width < 1 || box.height < 1) return;
    const x = Math.max(0, Math.min(100, ((e.clientX - box.left) / box.width) * 100));
    const y = Math.max(0, Math.min(100, ((e.clientY - box.top) / box.height) * 100));
    glowPending = { x, y };
    if (!glowMoveRaf) {
      glowMoveRaf = window.requestAnimationFrame(flushDiscoverGlow);
    }
  };

  window.addEventListener('pointermove', onDiscoverPointerMove, { passive: true });

  const setOpen = (open) => {
    const wasOpen = overlay.classList.contains('is-open');
    if (open === wasOpen) return;
    // #region agent log
    const __dbgSnap = (phase) => {
      const header = document.getElementById('site-header');
      const hr = header?.getBoundingClientRect();
      const or = overlay.getBoundingClientRect();
      const payload = {
        sessionId: 'a7b56f',
        runId: 'pre-fix',
        hypothesisId: 'H1-H5',
        location: 'menu.js:setOpen',
        message: 'discover overlay ' + phase,
        data: {
          phase,
          willOpen: open,
          scrollY: window.scrollY,
          innerWidth: window.innerWidth,
          docClientW: document.documentElement.clientWidth,
          scrollbarGap: window.innerWidth - document.documentElement.clientWidth,
          headerLeft: hr ? Math.round(hr.left * 1000) / 1000 : null,
          headerWidth: hr ? Math.round(hr.width * 1000) / 1000 : null,
          overlayLeft: Math.round(or.left * 1000) / 1000,
          htmlOverflowY: getComputedStyle(document.documentElement).overflowY,
          bodyOverflowY: getComputedStyle(document.body).overflowY,
          bodyHasPinned: document.body.classList.contains('discover-menu-open--scroll-pinned'),
        },
        timestamp: Date.now(),
      };
      fetch('http://127.0.0.1:7317/ingest/e1b4e355-c45c-4a87-9906-b6bb0d8fb797', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': 'a7b56f' },
        body: JSON.stringify(payload),
      }).catch(() => {});
    };
    __dbgSnap('before-toggle');
    // #endregion
    overlay.classList.toggle('is-open', open);
    overlay.setAttribute('aria-hidden', open ? 'false' : 'true');
    openBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
    if (open) {
      discoverLockScrollY = window.scrollY || document.documentElement.scrollTop || 0;
      document.body.classList.toggle('discover-menu-open--scroll-pinned', discoverLockScrollY > 0);
      if (discoverLockScrollY > 0) {
        document.body.style.setProperty('--discover-lock-y', `${discoverLockScrollY}px`);
      } else {
        document.body.style.removeProperty('--discover-lock-y');
      }
    } else {
      document.body.classList.remove('discover-menu-open--scroll-pinned');
      document.body.style.removeProperty('--discover-lock-y');
    }
    document.documentElement.classList.toggle('discover-scroll-lock', open);
    document.body.classList.toggle('discover-menu-open', open);
    if (!open) {
      window.requestAnimationFrame(() => {
        window.scrollTo(0, discoverLockScrollY);
      });
    }
    if (heroVideo instanceof HTMLVideoElement) {
      if (open) {
        heroVideo.pause();
      } else {
        heroVideo.play().catch(() => {});
      }
    }
    if (open) {
      if (!cursorGlowReduced) {
        overlay.style.setProperty('--discover-mx', '50%');
        overlay.style.setProperty('--discover-my', '50%');
        overlay.style.setProperty('--discover-tx', '0px');
        overlay.style.setProperty('--discover-ty', '0px');
      }
      openBtn.blur();
      requestAnimationFrame(() => {
        closeBtn.focus({ preventScroll: true });
      });
    } else {
      closeBtn.blur();
      requestAnimationFrame(() => {
        const el = document.activeElement;
        if (el instanceof HTMLElement && overlay.contains(el)) {
          el.blur();
        }
      });
    }
    // #region agent log
    requestAnimationFrame(() => {
      const header = document.getElementById('site-header');
      const hr = header?.getBoundingClientRect();
      const or = overlay.getBoundingClientRect();
      fetch('http://127.0.0.1:7317/ingest/e1b4e355-c45c-4a87-9906-b6bb0d8fb797', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': 'a7b56f' },
        body: JSON.stringify({
          sessionId: 'a7b56f',
          runId: 'pre-fix',
          hypothesisId: 'H1-H5',
          location: 'menu.js:setOpen',
          message: 'discover overlay after-rAF',
          data: {
            phase: 'after-rAF',
            isOpen: open,
            scrollY: window.scrollY,
            innerWidth: window.innerWidth,
            docClientW: document.documentElement.clientWidth,
            scrollbarGap: window.innerWidth - document.documentElement.clientWidth,
            headerLeft: hr ? Math.round(hr.left * 1000) / 1000 : null,
            headerWidth: hr ? Math.round(hr.width * 1000) / 1000 : null,
            overlayLeft: Math.round(or.left * 1000) / 1000,
            htmlOverflowY: getComputedStyle(document.documentElement).overflowY,
            bodyOverflowY: getComputedStyle(document.body).overflowY,
            bodyHasPinned: document.body.classList.contains('discover-menu-open--scroll-pinned'),
          },
          timestamp: Date.now(),
        }),
      }).catch(() => {});
    });
    // #endregion
  };

  openBtn.addEventListener('click', () => setOpen(!overlay.classList.contains('is-open')));
  closeBtn.addEventListener('click', () => setOpen(false));
  if (backdrop) {
    backdrop.addEventListener('click', () => setOpen(false));
  }

  /* Document capture: runs before the overlay subtree (pointer-events / stacking quirks on <nav>). */
  const onDocClickCapture = (e) => {
    const isOpen = overlay.classList.contains('is-open');
    const el = e.target instanceof Element ? e.target : null;
    if (!isOpen) return;
    const link = el?.closest('a.discover-overlay__link[href]') ?? null;
    if (!link || !overlay.contains(link)) return;
    if (link.target === '_blank' || link.hasAttribute('download')) return;
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const href = link.getAttribute('href');
    if (!href || href.startsWith('//')) return;
    const internal =
      href.startsWith('/') && !href.startsWith('/admin') && !href.startsWith('/api');
    if (!internal) return;

    e.preventDefault();
    e.stopPropagation();
    setOpen(false);
    if (!isWorkProjectDetailHref(href)) {
      try {
        sessionStorage.setItem(SKIP_PRELOADER_KEY, '1');
      } catch (_) {}
    }
    window.location.href = href;
  };
  document.addEventListener('click', onDocClickCapture, true);

  window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && overlay.classList.contains('is-open')) setOpen(false);
  });
}
