// Act 3 — THE FOUR SYSTEMS. Not a card grid: each system is a value proposition and an
// "enterable" port the network spine threads through, linking out to its child domain.

const { useEffect: useEffectS, useRef: useRefS } = React;

function Port({ s }) {
  const host = s.href.replace(/^https?:\/\//, '');
  return (
    <a className="wb-port" href={s.href} target="_blank" rel="noopener noreferrer"
       data-port={s.id} data-screen-label={'System ' + s.index}>
      <span className="wb-port__seam" />
      {/* network waypoint anchors back to the index on the left */}
      <span className="wb-port__index" data-node={s.id}>{s.index}</span>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <span className="wb-port__name">{s.name}</span>
          <span className={'wb-badge wb-badge--' + (s.status === 'building' ? 'building' : 'live')}>
            {s.status === 'building' ? 'Building' : 'Live'}
          </span>
        </div>
        <p className="wb-port__prop">{s.prop}</p>
        <span className="wb-port__host">{host}</span>
      </div>
    </a>
  );
}

function Systems() {
  const ref = useRefS(null);
  // mark the port nearest viewport-center as active (drives the seam + index accent on scroll)
  useEffectS(() => {
    const ports = Array.from(ref.current.querySelectorAll('.wb-port'));
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const mid = window.innerHeight / 2;
        let best = null, bd = Infinity;
        ports.forEach((p) => {
          const r = p.getBoundingClientRect();
          if (r.bottom < 0 || r.top > window.innerHeight) { p.setAttribute('data-active', 'false'); return; }
          const d = Math.abs((r.top + r.bottom) / 2 - mid);
          if (d < bd) { bd = d; best = p; }
        });
        ports.forEach((p) => p.setAttribute('data-active', String(p === best)));
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, []);

  return (
    <section className="wb-act" id="systems" data-section="systems" data-screen-label="Four Systems">
      <div className="wb-shell">
        <div className="wb-reveal" style={{ maxWidth: '46ch' }}>
          <div className="wb-eyebrow"><span className="wb-eyebrow__num">03</span><span>Four Systems</span></div>
          <h2 className="wb-display wb-display--m" style={{ marginTop: 22 }}>
            Four ports off the central node. All still in build.
          </h2>
        </div>
        <div className="wb-systems wb-reveal" ref={ref} style={{ marginTop: 56 }}>
          {WB.systems.map((s) => <Port key={s.id} s={s} />)}
        </div>
      </div>
    </section>
  );
}

window.Systems = Systems;
