/* global React */
(() => {
const { useState, useEffect, useRef } = React;
const RED = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* phase: 1 post · 2 evidence · 3 question · 4 factors · 5 next cycle */
const DUR = { 0: 300, 1: 1500, 2: 2100, 3: 1300, 4: 2400, 5: 0 };
const FACTORS = ['Topic', 'Hook', 'Format', 'Timing', 'Visual style'];
const END = 5;

function FicusStory() {
  const [phase, setPhase] = useState(RED ? END : 0);
  const [playing, setPlaying] = useState(false);
  const timers = useRef([]);
  const rootRef = useRef(null);
  const phaseRef = useRef(phase); phaseRef.current = phase;
  const clear = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const run = () => {
    clear(); setPhase(0); setPlaying(true);
    let t = DUR[0];
    for (let p = 1; p <= END; p++) {
      timers.current.push(setTimeout(() => setPhase(p), t));
      t += DUR[p] || 1500;
    }
    timers.current.push(setTimeout(() => setPlaying(false), t + 200));
  };
  useEffect(() => {
    if (RED) return;
    const el = rootRef.current;
    const start = () => { if (phaseRef.current === 0) run(); };
    const seen = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.8 && r.bottom > 0) { start(); window.removeEventListener('scroll', onScroll); }
    };
    const onScroll = () => seen();
    seen();
    window.addEventListener('scroll', onScroll, { passive: true });
    if (window.IntersectionObserver) {
      const io = new IntersectionObserver((es) => {
        es.forEach((e) => { if (e.isIntersecting) { start(); io.disconnect(); } });
      }, { threshold: 0.3 });
      io.observe(el);
    }
    return () => { window.removeEventListener('scroll', onScroll); clear(); };
  }, []);
  const on = (a) => (phase >= a ? ' on' : '');
  return (
    <div className="fx" ref={rootRef} data-screen-label="Ficus: automated system, real output">
      <div className="fx-headrow">
        <div>
          <h4 className="fx-h">Automated system.<br />Real output.</h4>
          <span className="fx-hsub">Published to @FicusAgentLtd on X</span>
        </div>
        {!RED && !playing && phase >= END &&
        <button className="fx-playb" onClick={run}>↺ Replay</button>}
      </div>
      <div className="fp">
        <figure className={'fp-post' + on(1) + (phase >= END ? ' cycle' : '')}>
          <span className="fp-cy">↻ the next post starts better informed</span>
          <div className="fp-embed"><img src="assets/ficus-post-hormuz.png" alt="Post published by the Ficus system: Hormuz is moving toward conditional passage, not normality." /></div>
          <figcaption>Real post, published by the system · @FicusAgentLtd on X</figcaption>
        </figure>
        <div className={'fp-ev' + on(2)}>
          <div className="fp-m"><b>35K+</b><span>organic impressions / week</span></div>
          <div className="fp-m"><b>1–2%</b><span>average engagement rate</span></div>
          <div className="fp-m"><b>8</b><span>content categories in rotation</span></div>
          <p className="fp-cats">AI · Crypto news · Financial markets · Geopolitics · Wave analysis · Weekly BTC · Product updates · Trade recaps</p>
        </div>
      </div>
      <div className="fp-loop">
        <span className={'fp-q' + on(3)}>So what performed<span className="dot">?</span></span>
        <div className={'fp-factors' + on(4) + (phase >= END ? ' fed' : '')}>
          {FACTORS.map((f, i) =>
          <div className="fp-f" key={f} style={{ transitionDelay: (i * 150) + 'ms' }}>
            <span style={{ transitionDelay: (i * 150) + 'ms' }}>{f}</span>
            <i style={{ transitionDelay: (i * 150 + 120) + 'ms' }}></i>
          </div>)}
        </div>
        <div className={'fp-next' + on(END)}>
          <span className="fp-nk">Next cycle <b>→</b></span>
          <p className="fp-take">Performance data informs what the system creates next. Read, refine, publish again.</p>
        </div>
      </div>
    </div>);
}

window.FicusStory = FicusStory;
})();
