// Eivi — "A four-step system" animated section
// Replaces the static LearningProcess grid. Self-contained: all animation
// utilities are inlined with fsa-prefixed names to avoid global collisions.

// ── Inline easing helpers ────────────────────────────────────────────────────
const fsaEasing = {
  easeInCubic:   (t) => t * t * t,
  easeOutCubic:  (t) => (--t) * t * t + 1,
  easeInOutSine: (t) => -(Math.cos(Math.PI * t) - 1) / 2,
};

const fsaClamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

// ── Timeline context (local, not shared with any other component) ────────────
const FSATimelineContext = React.createContext({ time: 0, duration: 16, playing: true });
const fsaUseTime     = () => React.useContext(FSATimelineContext).time;
const fsaUseTimeline = () => React.useContext(FSATimelineContext);

const FSASpriteContext = React.createContext({ localTime: 0, progress: 0, duration: 0 });
const fsaUseSprite = () => React.useContext(FSASpriteContext);

function FSASprite({ start, end, children }) {
  const { time } = fsaUseTimeline();
  if (time < start || time > end) return null;
  const dur = end - start;
  const localTime = Math.max(0, time - start);
  const progress = dur > 0 ? fsaClamp(localTime / dur, 0, 1) : 0;
  return (
    <FSASpriteContext.Provider value={{ localTime, progress, duration: dur }}>
      {children}
    </FSASpriteContext.Provider>
  );
}

// ── Animation constants ──────────────────────────────────────────────────────
const FSA_W = 1080, FSA_H = 1400, FSA_STEP_DUR = 4;
const FSA_CARD = { W: 960, H: 960, X: 60, Y: 40 };
const FSA_STEPS = [
  { src: '/assets/how-it-works/step1.png', caption: 'Log your food',    origin: '50% 48%' },
  { src: '/assets/how-it-works/step2.png', caption: 'See what happens', origin: '42% 50%' },
  { src: '/assets/how-it-works/step3.png', caption: 'Get feedback',     origin: '50% 48%' },
  { src: '/assets/how-it-works/step4.png', caption: 'Make changes',     origin: '50% 45%' },
];
const FSA_TOTAL = FSA_STEP_DUR * FSA_STEPS.length; // 16s

// ── Ambient stage: auto-looping, fits container ──────────────────────────────
function FSAAmbientStage({ children }) {
  const [time, setTime] = React.useState(0);
  const [scale, setScale] = React.useState(1);
  const wrapRef = React.useRef(null);

  // Scale canvas to fit wrapper
  React.useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const measure = () => {
      setScale(Math.max(0.05, Math.min(el.clientWidth / FSA_W, el.clientHeight / FSA_H)));
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    window.addEventListener('resize', measure);
    return () => { ro.disconnect(); window.removeEventListener('resize', measure); };
  }, []);

  // rAF loop — respects prefers-reduced-motion
  React.useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setTime(2);
      return;
    }
    let raf = null, last = null;
    const tick = (ts) => {
      if (last == null) last = ts;
      const dt = Math.min(0.1, (ts - last) / 1000);
      last = ts;
      setTime(t => (t + dt) % FSA_TOTAL);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => { if (raf) cancelAnimationFrame(raf); };
  }, []);

  const ctx = React.useMemo(
    () => ({ time, duration: FSA_TOTAL, playing: true, setTime, setPlaying: () => {} }),
    [time]
  );

  return (
    <div ref={wrapRef} style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
      <div style={{
        width: FSA_W,
        height: FSA_H,
        background: '#F9F9F9',
        position: 'relative',
        transform: 'scale(' + scale + ')',
        transformOrigin: 'center',
        flexShrink: 0,
        overflow: 'hidden',
      }}>
        <FSATimelineContext.Provider value={ctx}>
          {children}
        </FSATimelineContext.Provider>
      </div>
    </div>
  );
}

// ── Screen card (rounded rect + Ken Burns zoom) ──────────────────────────────
function FSAScreenCard({ step, zoom }) {
  return (
    <div style={{ width: FSA_CARD.W, height: FSA_CARD.H, borderRadius: 44, overflow: 'hidden', position: 'relative' }}>
      <div style={{ position: 'absolute', inset: 0, transform: 'scale(' + zoom + ')', transformOrigin: step.origin, willChange: 'transform' }}>
        <img src={step.src} alt={step.caption} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
    </div>
  );
}

// ── One step scene: card + caption, fade-and-rise in/out ─────────────────────
function FSAStepScene({ step }) {
  const { localTime, duration } = fsaUseSprite();
  const ENTRY = 0.55, EXIT = 0.45;
  const exitStart = duration - EXIT;

  const fadeRise = (delay, riseIn) => {
    let opacity = 1, ty = 0;
    const lt = localTime - delay;
    if (lt < ENTRY) {
      const t = fsaEasing.easeOutCubic(fsaClamp(lt / ENTRY, 0, 1));
      opacity = t;
      ty = (1 - t) * riseIn;
    } else if (localTime > exitStart) {
      const t = fsaEasing.easeInCubic(fsaClamp((localTime - exitStart) / EXIT, 0, 1));
      opacity = 1 - t;
      ty = -t * 18;
    }
    return { opacity, ty };
  };

  const card = fadeRise(0, 40);
  const cap  = fadeRise(0.18, 26);
  const zoom = 1.02 + 0.05 * fsaEasing.easeInOutSine(fsaClamp(localTime / duration, 0, 1));

  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', left: FSA_CARD.X, top: FSA_CARD.Y, opacity: card.opacity, transform: 'translateY(' + card.ty + 'px)', willChange: 'transform, opacity' }}>
        <FSAScreenCard step={step} zoom={zoom} />
      </div>
      <div style={{ position: 'absolute', left: 60, right: 60, top: FSA_CARD.Y + FSA_CARD.H + 78, textAlign: 'center', opacity: cap.opacity, transform: 'translateY(' + cap.ty + 'px)', willChange: 'transform, opacity' }}>
        <div style={{ fontSize: 68, lineHeight: 1.25, color: '#000000', letterSpacing: '-0.01em' }}>
          {step.caption}
        </div>
      </div>
    </div>
  );
}

// ── Numbered progress indicator ───────────────────────────────────────────────
const FSA_DOT_SIZE = 56, FSA_PILL_W = 128, FSA_DOT_FONT = 41;

function FSADotNumber({ n, color }) {
  return (
    <div style={{ position: 'absolute', left: 0, top: 0, width: FSA_DOT_SIZE, height: FSA_DOT_SIZE, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: FSA_DOT_FONT, color }}>
      {n}
    </div>
  );
}

function FSAProgressDots() {
  const time = fsaUseTime();
  const idx = Math.min(FSA_STEPS.length - 1, Math.floor(time / FSA_STEP_DUR));
  const stepProgress = fsaClamp((time - idx * FSA_STEP_DUR) / FSA_STEP_DUR, 0, 1);
  const MORPH = 0.4;

  const slotWidth = (i) => {
    const tIn = i * FSA_STEP_DUR;
    const sinceIn = ((time - tIn) % FSA_TOTAL + FSA_TOTAL) % FSA_TOTAL;
    if (sinceIn < FSA_STEP_DUR) {
      const k = fsaEasing.easeOutCubic(fsaClamp(sinceIn / MORPH, 0, 1));
      return FSA_DOT_SIZE + (FSA_PILL_W - FSA_DOT_SIZE) * k;
    }
    const sinceOut = sinceIn - FSA_STEP_DUR;
    if (sinceOut < MORPH) {
      const k = fsaEasing.easeOutCubic(fsaClamp(sinceOut / MORPH, 0, 1));
      return FSA_PILL_W + (FSA_DOT_SIZE - FSA_PILL_W) * k;
    }
    return FSA_DOT_SIZE;
  };

  return (
    <div style={{ position: 'absolute', bottom: 90, left: 0, right: 0, display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 24 }}>
      {FSA_STEPS.map((s, i) => {
        const active = i === idx;
        const fillW = FSA_DOT_SIZE + stepProgress * (FSA_PILL_W - FSA_DOT_SIZE);
        return (
          <div key={i} style={{ width: slotWidth(i), height: FSA_DOT_SIZE, borderRadius: FSA_DOT_SIZE / 2, background: '#D9F1F1', overflow: 'hidden', position: 'relative' }}>
            <FSADotNumber n={i + 1} color="#0B6F8D" />
            {active && (
              <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: fillW, background: '#1BBBBB', borderRadius: FSA_DOT_SIZE / 2, overflow: 'hidden' }}>
                <FSADotNumber n={i + 1} color="#FFFFFF" />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ── Section layout ────────────────────────────────────────────────────────────
function FourStepAnimation() {
  return (
    <section style={{ background: '#F9F9F9' }}>
      <div className="fsa-section">
        <div className="fsa-left">
          <p className="eyebrow-text fsa-eyebrow">Daily process</p>
          <h2 className="t-h2 fsa-heading">A four-step system</h2>
        </div>
        <div className="fsa-right">
          <div className="fsa-stage-wrap">
            <FSAAmbientStage>
              {FSA_STEPS.map((step, i) => (
                <FSASprite key={i} start={i * FSA_STEP_DUR} end={(i + 1) * FSA_STEP_DUR}>
                  <FSAStepScene step={step} index={i} />
                </FSASprite>
              ))}
              <FSAProgressDots />
            </FSAAmbientStage>
          </div>
        </div>
      </div>

      <style>{`
        .fsa-section {
          max-width: 1280px;
          margin: 0 auto;
          padding: 96px 48px;
          display: grid;
          grid-template-columns: 1fr auto;
          gap: 64px;
          align-items: center;
        }
        .fsa-eyebrow {
          font-size: 17px;
          text-transform: uppercase;
          letter-spacing: 0.14em;
          color: #1BBBBB;
          margin: 0 0 24px;
        }
        .fsa-heading {
          margin: 0;
        }
        .fsa-stage-wrap {
          width: min(575px, 46vw);
          aspect-ratio: 1080 / 1400;
          position: relative;
          overflow: hidden;
        }
        @media (max-width: 860px) {
          .fsa-section {
            grid-template-columns: 1fr;
            padding: 64px 24px;
            text-align: center;
          }
.fsa-stage-wrap { width: min(500px, 88vw); margin: 0 auto; }
        }
      `}</style>
    </section>
  );
}

window.FourStepAnimation = FourStepAnimation;
