/// file: public/assets/js/modules/page-transitions.js

import { SKIP_PRELOADER_KEY } from './preloader.js';

/**
 * Single project case study URL: /work/{slug} (not the /work listing).
 */
export function isWorkProjectDetailHref(href) {
  try {
    const u = new URL(href, window.location.origin);
    if (u.origin !== window.location.origin) {
      return false;
    }
    const parts = u.pathname.split('/').filter(Boolean);
    return parts.length >= 2 && parts[0] === 'work';
  } catch {
    return false;
  }
}

function armSkipPreloaderOnce() {
  try {
    sessionStorage.setItem(SKIP_PRELOADER_KEY, '1');
  } catch (_) {}
}

/**
 * Arms sessionStorage so the next full load skips the preloader, except when
 * navigating to a project detail page (/work/slug) or on the first visit (no flag).
 */
export function initPageTransitions() {
  document.querySelectorAll('a[href^="/"]').forEach((a) => {
    if (a.target === '_blank' || a.hasAttribute('download')) {
      return;
    }
    a.addEventListener('click', (e) => {
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
        return;
      }
      const url = a.getAttribute('href');
      if (!url || url.startsWith('//')) {
        return;
      }
      if (url.startsWith('/admin') || url.startsWith('/api')) {
        return;
      }
      if (a.classList.contains('work-page__filter-option')) {
        armSkipPreloaderOnce();
        return;
      }
      if (isWorkProjectDetailHref(url)) {
        return;
      }
      armSkipPreloaderOnce();
    });
  });
}
