/// file: public/assets/js/page-work.js

import { initWorkPolyBg } from './modules/work-poly-bg.js';

function scrollStep() {
  return Math.round(window.innerHeight * 0.72);
}

export function initWorkPage() {
  const grid = document.getElementById('work-grid');
  const root = document.querySelector('[data-work-root]');
  if (!grid) return;

  initWorkPolyBg(root);

  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const revealEls = grid.querySelectorAll('[data-work-reveal]');

  if (reduced || !('IntersectionObserver' in window) || !revealEls.length) {
    revealEls.forEach((el) => el.classList.add('is-revealed'));
  } else {
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((en) => {
          if (!en.isIntersecting) return;
          en.target.classList.add('is-revealed');
          io.unobserve(en.target);
        });
      },
      { threshold: 0.04, rootMargin: '0px 0px -6% 0px' }
    );
    revealEls.forEach((el) => io.observe(el));
  }

  const btnUp = root?.querySelector('[data-work-scroll="up"]');
  const btnDown = root?.querySelector('[data-work-scroll="down"]');
  if (!btnUp || !btnDown) return;

  const syncArrows = () => {
    const y = window.scrollY || 0;
    const max = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);
    const atTop = y < 32;
    const atBottom = y > max - 32;
    btnUp.disabled = atTop;
    btnDown.disabled = atBottom;
    btnUp.setAttribute('aria-disabled', atTop ? 'true' : 'false');
    btnDown.setAttribute('aria-disabled', atBottom ? 'true' : 'false');
  };

  const scrollByDir = (dir) => {
    const delta = dir === 'up' ? -scrollStep() : scrollStep();
    window.scrollBy({
      top: delta,
      behavior: reduced ? 'auto' : 'smooth',
    });
  };

  btnUp.addEventListener('click', () => scrollByDir('up'));
  btnDown.addEventListener('click', () => scrollByDir('down'));

  syncArrows();
  window.addEventListener('scroll', syncArrows, { passive: true });
  window.addEventListener('resize', syncArrows);
}
