/* about-scrolly.jsx — "Über Bevisible": scroll-gedrehtes Phone mit wechselnden Medien */
const { useEffect: useEffectAS, useRef: useRefAS } = React;

const ABOUT_MEDIA = [
{ type: 'img', src: window.__resources && window.__resources.teamOffice || 'assets/team-office.png', label: 'Unser Team · Solothurn',
  text: 'Mit langjähriger Erfahrung betreuen wir Unternehmen, Verbände, Vereine und Politikerinnen und Politiker bei ihrem Auftritt in den sozialen Medien.' },
{ type: 'ph', scene: 's1', icon: 'cam', label: 'Behind the Scenes',
  text: 'Wir produzieren echten Content — vor Ort, am Set und im Schnitt. Kein Stockmaterial, sondern Deine Geschichte.' },
{ type: 'ph', scene: 's2', icon: 'play', label: 'Content der wirkt',
  text: 'Von der Strategie bis zum fertigen Post: kreativ gedacht, strategisch umgesetzt — für echte Reichweite.' }];


function AsIcon({ name }) {
  const p = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'cam':return <svg width="58" height="58" viewBox="0 0 24 24"><rect x="2.5" y="6.5" width="13" height="11" rx="2.5" {...p} /><path d="M15.5 10.5l6-3v9l-6-3z" {...p} /></svg>;
    case 'play':return <svg width="58" height="58" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" {...p} /><path d="M10 8.5l6 3.5-6 3.5z" fill="currentColor" stroke="none" /></svg>;
    default:return null;
  }
}

function aMediaNodes(keyPrefix) {
  return ABOUT_MEDIA.map((m, i) =>
  <div className={`amedia ${m.scene || ''} ${i === 0 ? 'on' : ''}`} key={keyPrefix + i}>
      {m.type === 'img' ?
    <img src={m.src} alt={m.label} loading="lazy" /> :
    <span className="aghost"><AsIcon name={m.icon} /></span>}
      <span className="amedia-cap">{m.label}</span>
    </div>
  );
}

function AboutScrolly({ go }) {
  const { LinkArrow } = window;
  const secRef = useRefAS(null),rotorRef = useRefAS(null),scalerRef = useRefAS(null);
  const frontRef = useRefAS(null),backRef = useRefAS(null),copyRef = useRefAS(null);

  useEffectAS(() => {
    let raf = 0, ticking = false;
    const setOn = (face, idx) => {
      if (!face) return;
      const ms = face.querySelectorAll('.amedia');
      ms.forEach((m, i) => m.classList.toggle('on', i === idx));
    };
    const update = () => {
      ticking = false;
      const sec = secRef.current;
      if (!sec) return;
      const r = sec.getBoundingClientRect();
      const vh = window.innerHeight || 1;
      const total = sec.offsetHeight - vh;
      const scrolled = Math.min(Math.max(-r.top, 0), total);
      const p = total > 0 ? scrolled / total : 0;
      const rot = p * 360;
      if (rotorRef.current) rotorRef.current.style.transform = `rotateY(${rot}deg)`;
      // Eintritts-Skalierung, solange die Sektion von unten hereinkommt
      const ein = Math.min(Math.max((vh - r.top) / vh, 0), 1);
      const sc = p > 0 ? 1 : 0.82 + 0.18 * ein;
      if (scalerRef.current) scalerRef.current.style.transform = `scale(${sc})`;
      // Medien je sichtbarer Seite (Wechsel im "edge-on"-Moment bei 90°/270°)
      const seg = Math.round(rot / 180); // 0,1,2
      const frontIdx = seg % 2 === 0 ? seg % 3 : (seg + 1) % 3;
      const backIdx = seg % 2 === 1 ? seg % 3 : (seg + 1) % 3;
      setOn(frontRef.current, frontIdx);
      setOn(backRef.current, backIdx);
      // Begleittext synchron zum aktuell gezeigten Medium
      if (copyRef.current) {
        const items = copyRef.current.querySelectorAll('.about-step');
        const active = seg % 3;
        items.forEach((el, i) => el.classList.toggle('on', i === active));
        const cta = copyRef.current.querySelector('.about-cta');
        if (cta) cta.classList.toggle('on', p > 0.78);
        // h2 am Anfang zeigen, beim Scrollen ausblenden; Text rückt nach oben ins Zentrum
        const h2 = copyRef.current.querySelector('.about-h2');
        const body = copyRef.current.querySelector('.about-body');
        const fade = Math.min(Math.max((p - 0.08) / 0.12, 0), 1);
        if (h2) {h2.style.opacity = String(1 - fade);h2.style.transform = `translateY(${-14 * fade}px)`;}
        if (body) {const lift = (h2 ? h2.offsetHeight + 16 : 0) * fade;body.style.transform = `translateY(${-lift}px)`;}
      }
    };
    // scroll-getrieben: aktualisiert genau dann, wenn gescrollt wird —
    // unabhängig von rAF-Throttling in nicht-fokussierten Tabs
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      raf = requestAnimationFrame(update);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    // Initialzustand mehrfach setzen (Bilder/Layout können nachladen)
    update();
    const t1 = setTimeout(update, 120);
    const t2 = setTimeout(update, 480);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf); clearTimeout(t1); clearTimeout(t2);
    };
  }, []);

  return (
    <section className="about-scrolly" ref={secRef}>
      <div className="about-sticky">
        <div className="aphone-stage">
          <div className="aphone-glow" aria-hidden="true"></div>
          <div className="aphone-scaler" ref={scalerRef}>
            <div className="aphone-rotor" ref={rotorRef}>
              <div className="aface aface--front" ref={frontRef}>
                <div className="aphone-frame"><div className="aphone-screen">
                  {aMediaNodes('f')}<span className="aphone-island"></span>
                </div></div>
              </div>
              <div className="aface aface--back" ref={backRef}>
                <div className="aphone-frame"><div className="aphone-screen">
                  {aMediaNodes('b')}<span className="aphone-island"></span>
                </div></div>
              </div>
            </div>
          </div>
        </div>

        <div className="about-copy" ref={copyRef}>
          <span className="kicker" style={{ fontSize: "16px" }}>Über Bevisible</span>
          <h2 className="about-h2 section-title" style={{ marginTop: 16, maxWidth: '13ch' }}>
            Wir sind Dein <span className="grad-text">Social Media</span> Team.
          </h2>
          <div className="about-body">
            <div className="about-steps">
              {ABOUT_MEDIA.map((m, i) =>
              <p className={`about-step ${i === 0 ? 'on' : ''}`} key={i}>{m.text}</p>
              )}
            </div>
            <div className="about-cta">
              <LinkArrow onClick={() => go('ueber')}>Lerne das Team kennen</LinkArrow>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { AboutScrolly });
