// Shared interactivity — The Friedrichshof Account

(function() {
  // ----- Reveal on scroll ----- 
  const io = new IntersectionObserver((entries) => {
    entries.forEach(e => {
      if (e.isIntersecting) {
        e.target.classList.add('in');
        io.unobserve(e.target);
      }
    });
  }, { threshold: 0.15, rootMargin: '0px 0px -10% 0px' });

  function bindReveals() {
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
  }

  // ----- Progress bar -----
  function initProgress() {
    const bar = document.querySelector('.progress');
    if (!bar) return;
    const onScroll = () => {
      const h = document.documentElement;
      const scrolled = h.scrollTop;
      const max = h.scrollHeight - h.clientHeight;
      bar.style.width = max > 0 ? (scrolled / max * 100) + '%' : '0%';
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
  }

  // ----- Parallax on hero bg -----
  function initParallax() {
    const bgs = document.querySelectorAll('[data-parallax]');
    if (!bgs.length) return;
    const onScroll = () => {
      bgs.forEach(bg => {
        const speed = parseFloat(bg.dataset.parallax) || 0.4;
        const section = bg.closest('.pinned-text-section');
        if (section) {
          const r = section.getBoundingClientRect();
          const scrollable = section.offsetHeight - window.innerHeight;
          if (scrollable <= 0) return;
          const progress = Math.max(0, Math.min(1, -r.top / scrollable));
          bg.style.backgroundPosition = `center ${(progress * 100).toFixed(2)}%`;
        } else {
          const r = bg.getBoundingClientRect();
          bg.style.transform = `translate3d(0, ${-r.top * speed}px, 0)`;
        }
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
  }

  // ----- Typewriter for chapter title -----
  function initTypewriter() {
    const el = document.querySelector('[data-typewriter]');
    if (!el) return;
    const text = el.textContent.trim();
    el.innerHTML = '<span class="typed"></span><span class="typed-cursor">&nbsp;</span>';
    const target = el.querySelector('.typed');
    let i = 0;
    const speed = 55;
    const tick = () => {
      if (i <= text.length) {
        target.textContent = text.slice(0, i);
        i++;
        setTimeout(tick, speed);
      } else {
        setTimeout(() => {
          const c = el.querySelector('.typed-cursor');
          if (c) c.style.opacity = '0';
        }, 1500);
      }
    };
    setTimeout(tick, 600);
  }

  // ----- Hamburger menu -----
  function initMenu() {
    const btn = document.querySelector('.menu-btn');
    const overlay = document.querySelector('.menu-overlay');
    const close = document.querySelector('.menu-close');
    if (!btn || !overlay) return;
    const open = () => { overlay.classList.add('open'); document.body.style.overflow = 'hidden'; };
    const shut = () => { overlay.classList.remove('open'); document.body.style.overflow = ''; };
    btn.addEventListener('click', open);
    if (close) close.addEventListener('click', shut);
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') shut();
    });
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) shut();
    });
  }

  // ----- Menu chapter filter -----
  function initMenuFilter() {
    const input = document.querySelector('.menu-filter');
    const list = document.querySelector('.menu-list');
    if (!input || !list) return;
    let empty = list.querySelector('.menu-empty');
    if (!empty) {
      empty = document.createElement('div');
      empty.className = 'menu-empty';
      empty.textContent = 'No chapters match.';
      list.appendChild(empty);
    }
    input.addEventListener('input', () => {
      const q = input.value.trim().toLowerCase();
      let any = false;
      list.querySelectorAll('.menu-chapters li').forEach(li => {
        const t = li.textContent.toLowerCase();
        const match = !q || t.includes(q);
        li.classList.toggle('hidden', !match);
        if (match) any = true;
      });
      list.querySelectorAll('.menu-part').forEach(p => {
        const visible = p.querySelectorAll('.menu-chapters li:not(.hidden)').length;
        p.style.display = visible ? '' : 'none';
      });
      list.classList.toggle('is-empty', !any);
    });
  }

  // ----- Init -----
  document.addEventListener('DOMContentLoaded', () => {
    bindReveals();
    initProgress();
    initParallax();
    initTypewriter();
    initMenu();
    initMenuFilter();
  });
})();
