// 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-section');
        if (section) {
          // Inside sticky container: getBoundingClientRect on the bg itself is always
          // ~0 because the sticky parent pins it. Track the outer section's scroll
          // progress instead. The bg has inset:-15% 0 so it extends beyond the stage;
          // overflow:hidden clips the edges, giving the image room to travel.
          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));
          const shift = (progress - 0.5) * speed * 400;
          bg.style.transform = `translate3d(0, ${shift}px, 0)`;
        } else {
          const r = bg.getBoundingClientRect();
          const offset = -r.top * speed;
          bg.style.transform = `translate3d(0, ${offset}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);
    });
  }

  // ----- Tweaks integration -----
  function initTweaksListener() {
    window.addEventListener('message', (e) => {
      const d = e.data;
      if (!d || typeof d !== 'object') return;
      if (d.type === '__re_tweaks_apply') applyTweaks(d.tweaks);
    });
    try {
      const saved = localStorage.getItem('re_tweaks');
      if (saved) applyTweaks(JSON.parse(saved));
    } catch(e) {}
  }

  function applyTweaks(t) {
    if (!t) return;
    const root = document.documentElement;
    if (t.grain != null) root.style.setProperty('--grain-opacity', t.grain);
    if (t.effects != null) root.dataset.effects = t.effects ? 'on' : 'off';
    if (t.mode) root.dataset.mode = t.mode;
  }

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