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

/** Set before in-app navigation to skip the full branded preloader on the next load. */
export const SKIP_PRELOADER_KEY = 'saneksa:skipPreloaderOnce';

export function initPreloader() {
  const el = document.getElementById('preloader');
  if (!el) return;

  try {
    if (sessionStorage.getItem(SKIP_PRELOADER_KEY)) {
      sessionStorage.removeItem(SKIP_PRELOADER_KEY);
      el.classList.add('is-done');
      document.body.classList.remove('overflow-hidden');
      const bar = el.querySelector('.preloader__bar-fill');
      if (bar) {
        bar.classList.add('origin-left');
        bar.style.transform = 'scaleX(1)';
      }
      return;
    }
  } catch (_) {}

  document.body.classList.add('overflow-hidden');
  const bar = el.querySelector('.preloader__bar-fill');
  if (bar) {
    bar.classList.add('origin-left');
    bar.style.transform = 'scaleX(0)';
  }

  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const durationMs = reduced ? 180 : 2800;
  const settleMs = reduced ? 120 : 380;
  const start = performance.now();

  /** Ease-out: fast start, very soft landing */
  const easeOutQuart = (t) => 1 - (1 - t) ** 4;

  const tick = (now) => {
    const t = Math.min(1, (now - start) / durationMs);
    const eased = easeOutQuart(t);
    if (bar) bar.style.transform = `scaleX(${eased})`;
    if (t < 1) {
      requestAnimationFrame(tick);
    } else {
      window.setTimeout(() => {
        el.classList.add('is-done');
        document.body.classList.remove('overflow-hidden');
      }, settleMs);
    }
  };

  requestAnimationFrame(tick);
}
