/*
  Navigation behaviours (COMPONENT_ARCHITECTURE §3):
   - mobile overlay open/close with focus trap, scroll lock and Esc
   - header compression flag via an IntersectionObserver sentinel (no scroll listener)
   - native CV <details> menu enhancement (outside-click / Esc close)
   - first-visit language hint (ROUTING_SPEC §3): shown once, never auto-redirects
*/

/* ---------- Mobile overlay ---------- */
const toggle = document.getElementById('mobile-nav-toggle');
const panel = document.getElementById('mobile-nav');
const closeBtn = document.getElementById('mobile-nav-close');

function focusable(el: HTMLElement): HTMLElement[] {
  return Array.from(
    el.querySelectorAll<HTMLElement>(
      'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])',
    ),
  ).filter((n) => n.offsetParent !== null);
}

function openNav(): void {
  if (!panel || !toggle) return;
  panel.dataset.open = '';
  toggle.setAttribute('aria-expanded', 'true');
  document.body.style.overflow = 'hidden';
  focusable(panel)[0]?.focus();
}
function closeNav(): void {
  if (!panel || !toggle) return;
  delete panel.dataset.open;
  toggle.setAttribute('aria-expanded', 'false');
  document.body.style.overflow = '';
  toggle.focus();
}

toggle?.addEventListener('click', openNav);
closeBtn?.addEventListener('click', closeNav);

document.addEventListener('keydown', (e) => {
  if (!panel || panel.dataset.open === undefined) return;
  if (e.key === 'Escape') closeNav();
  if (e.key === 'Tab') {
    const items = focusable(panel);
    if (items.length === 0) return;
    const first = items[0]!;
    const last = items[items.length - 1]!;
    if (e.shiftKey && document.activeElement === first) {
      e.preventDefault();
      last.focus();
    } else if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault();
      first.focus();
    }
  }
});

/* ---------- Header compression ---------- */
const header = document.getElementById('site-header');
const sentinel = document.getElementById('scroll-sentinel');
if (header && sentinel && 'IntersectionObserver' in window) {
  new IntersectionObserver(
    ([entry]) => {
      if (!entry) return;
      if (entry.isIntersecting) delete header.dataset.scrolled;
      else header.dataset.scrolled = '';
    },
    { threshold: 0 },
  ).observe(sentinel);
}

/* ---------- CV <details> menu: close on outside click / Esc ---------- */
document.querySelectorAll<HTMLDetailsElement>('.cv-menu').forEach((menu) => {
  document.addEventListener('click', (e) => {
    if (menu.open && !menu.contains(e.target as Node)) menu.open = false;
  });
  menu.addEventListener('keydown', (e) => {
    if ((e as KeyboardEvent).key === 'Escape') menu.open = false;
  });
});

/* ---------- Click-to-copy (global: contact band + contact page) ---------- */
document.querySelectorAll<HTMLElement>('[data-copy]').forEach((el) => {
  el.addEventListener('click', async () => {
    const value = el.dataset.copy ?? '';
    const labelEl = el.querySelector<HTMLElement>('[data-copy-label]');
    const done = el.dataset.copiedLabel ?? 'Copied';
    const original = labelEl?.textContent ?? '';
    try {
      await navigator.clipboard.writeText(value);
      if (labelEl) {
        labelEl.textContent = done;
        window.setTimeout(() => {
          labelEl.textContent = original;
        }, 1500);
      }
    } catch {
      /* clipboard blocked — the mailto link is still the fallback */
    }
  });
});

/* ---------- First-visit language hint ---------- */
const hint = document.getElementById('lang-hint');
if (hint) {
  const DISMISS_KEY = 'lang-hint-dismissed';
  let dismissed = false;
  try {
    dismissed = localStorage.getItem(DISMISS_KEY) === '1';
  } catch {
    /* ignore */
  }
  const prefersNo = /^(nb|nn|no)\b/i.test(navigator.language || '');
  if (!dismissed && prefersNo) {
    hint.hidden = false;
    hint.querySelector('[data-hint-dismiss]')?.addEventListener('click', () => {
      hint.hidden = true;
      try {
        localStorage.setItem(DISMISS_KEY, '1');
      } catch {
        /* ignore */
      }
    });
  }
}
