// Reveal-on-scroll + ambient animation system
window.initReveals = function initReveals() {

  // ── 1. Slide-up (default) ───────────────────────────────
  const upSelectors = [
    '.s-head',
    '.s-head h2', '.s-head .lede',
    '.problem-row',
    '.arch-grid', '.arch-col',
    '.stat-block .stat',
    '.tract-stats .cell',
    '.tract-grid > .card',
    '.cmu',
    '.team-row', '.advisor-row',
    '.price-card', '.price-foot',
    '.cta-tile', '.cta h2', '.cta .lede', '.cta .contact-row',
    '.module-row > div', '.module-vis',
    '.thesis h2',
    '.tracts-cta',
    '.mctx-card',
    '.anstat',
    '.rev-card',
    '.rev-exp-row',
    '.comp-diff-card',
    '.vt-item',
    '.fw-card',
    '.fw-step',
    '.faq-item',
    '.usecase-card',
    '.uc-hero',
    '.uc-ecosystem-wrap',
    '.uc-explorer',
    '.uc-explorer-card',
    '.home-portal-head',
    '.home-portal-card',
    '.home-summary-main', '.home-summary-aside',
    '.incol',
    '.cta-cap-line',
    '.extinction-punch',
    '.tm-module',
    '.tm-lc',
    '.tm-fr',
    '.tm-advisor-row',
    '.loop-col',
    '.vision-p',
    '.vision-timeline',
    '.comp-thesis',
    '.comp-map-wrap',
    '.comp-table-wrap',
    '.comp-punch',
    '.mctx-punch',
    '.appnow-punch',
    '.fw-fde',
    '.footer-bottom',
  ];

  // ── 2. Slide-in from left ──────────────────────────────
  const leftSelectors = [
    '.col-l',
    '.ftr-brand',
  ];

  // ── 3. Slide-in from right ─────────────────────────────
  const rightSelectors = [
    '.col-r',
    '.module-vis',
    '.home-summary-aside',
  ];

  // ── 4. Fade + scale up (cards, badges) ────────────────
  const scaleSelectors = [
    '.tprev-card',
    '.tag',
    '.home-portal-tag',
    '.hstat',
    '.logo-cell',
    '.fw-vertical',
    '.cmu-block',
    '.comp-diff-check',
    '.vt-connector',
  ];

  // ── 5. Stagger children ────────────────────────────────
  const staggerParents = [
    { sel: '.mctx-grid',        child: '.mctx-card' },
    { sel: '.tract-stats',      child: '.cell' },
    { sel: '.tract-grid',       child: '.card' },
    { sel: '.rev-grid',         child: '.rev-card' },
    { sel: '.comp-diff-grid',   child: '.comp-diff-card' },
    { sel: '.usecase-grid',     child: '.usecase-card' },
    { sel: '.uc-explorer-list', child: '.uc-explorer-item' },
    { sel: '.fw-grid',          child: '.fw-card' },
    { sel: '.fw-steps',         child: '.fw-step' },
    { sel: '.tm-leader-grid',   child: '.tm-lc' },
    { sel: '.tm-fellow-panel',  child: '.tm-fr' },
    { sel: '.logo-grid-5',      child: '.logo-cell' },
    { sel: '.faq-list',         child: '.faq-item' },
    { sel: '.incubation-cols',  child: '.incol' },
    { sel: '.vision-timeline',  child: '.vt-item' },
    { sel: '.cta-capabilities', child: '.cta-cap-line' },
    { sel: '.loop-cols',        child: '.loop-col' },
    { sel: '.home-portal-grid', child: '.home-portal-card' },
    { sel: '.problem-list',     child: '.problem-row' },
  ];

  const allUp    = new Set(upSelectors);
  const allLeft  = new Set(leftSelectors);
  const allRight = new Set(rightSelectors);
  const allScale = new Set(scaleSelectors);

  const applyReveal = (el, variant, delay = 0) => {
    if (el._revealDone) return;
    el._revealDone = true;
    el.classList.add('reveal', `reveal--${variant}`);
    if (delay > 0) el.style.setProperty('--reveal-delay', `${delay}ms`);
  };

  // Apply stagger first (override individual)
  staggerParents.forEach(({ sel, child }) => {
    document.querySelectorAll(sel).forEach(parent => {
      parent.querySelectorAll(child).forEach((el, idx) => {
        applyReveal(el, 'up', idx * 80);
      });
    });
  });

  // Apply directional reveals
  document.querySelectorAll(leftSelectors.join(',')).forEach(el  => applyReveal(el, 'left'));
  document.querySelectorAll(rightSelectors.join(',')).forEach(el => applyReveal(el, 'right'));
  document.querySelectorAll(scaleSelectors.join(',')).forEach(el => applyReveal(el, 'scale'));
  document.querySelectorAll(upSelectors.join(',')).forEach(el    => applyReveal(el, 'up'));

  // ── IntersectionObserver ───────────────────────────────
  const obs = new IntersectionObserver(
    (entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          obs.unobserve(e.target);
        }
      });
    },
    { threshold: 0.06, rootMargin: '0px 0px -32px 0px' }
  );

  document.querySelectorAll('.reveal').forEach(el => obs.observe(el));

  // ── Animated counters ─────────────────────────────────
  const counterObs = new IntersectionObserver((entries) => {
    entries.forEach(e => {
      if (!e.isIntersecting) return;
      const el = e.target;
      const raw = el.textContent.trim();
      const match = raw.match(/^([\d.]+)([KMB%+×x]*)$/);
      if (!match) return;
      const target = parseFloat(match[1]);
      const suffix = match[2] || '';
      const isFloat = match[1].includes('.');
      const duration = 1400;
      const start = performance.now();
      const step = (now) => {
        const p = Math.min((now - start) / duration, 1);
        const ease = 1 - Math.pow(1 - p, 3);
        const cur = target * ease;
        el.textContent = (isFloat ? cur.toFixed(1) : Math.round(cur)) + suffix;
        if (p < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
      counterObs.unobserve(el);
    });
  }, { threshold: 0.5 });

  document.querySelectorAll(
    '.hstat-num, .anstat-num, .home-summary-stat-num, .home-portal-mini-num, .home-portal-stat-num'
  ).forEach(el => counterObs.observe(el));

  // ── Page-transition fade on internal links ─────────────
  const overlay = document.createElement('div');
  overlay.className = 'page-transition-overlay';
  document.body.appendChild(overlay);

  document.querySelectorAll('a[href]').forEach(link => {
    const href = link.getAttribute('href');
    // Only same-site .html links, not mailto/external/anchor
    if (!href || href.startsWith('mailto') || href.startsWith('http') || href.startsWith('#')) return;
    if (!href.endsWith('.html') && !href.match(/^[a-z0-9-]+\.html/)) return;
    link.addEventListener('click', (e) => {
      e.preventDefault();
      overlay.classList.add('active');
      setTimeout(() => { window.location.href = href; }, 280);
    });
  });

  // ── Image fade-in on load ──────────────────────────────
  document.querySelectorAll('img').forEach(img => {
    if (img.complete) {
      img.classList.add('loaded');
    } else {
      img.addEventListener('load', () => img.classList.add('loaded'), { once: true });
    }
  });

  return obs;
};
