// Hero Workflow Tape — plays one real KMO workflow row by row, ends in a
// concrete outcome, then cross-fades to the next. Three workflows total.
// Hero-safe per spec v2: no ERP / accounting / banking endpoints.
//
// Motion budget:
//   beat tween 180ms, stagger 700ms, outcome appears 400ms after last beat,
//   1s hold, 240ms cross-fade. ~6s/cycle, 3 cycles = ~18s loop.
//
// prefers-reduced-motion: render workflow #1 in its end-state, no rotation.

const HeroWorkflowPanel = ({ lang }) => {
  const workflows = (window.HERO_WORKFLOWS && window.HERO_WORKFLOWS[lang]) || [];
  const reduced = React.useRef(
    typeof window !== 'undefined' &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches
  );

  const [wfIdx, setWfIdx] = React.useState(0);
  const [beatIdx, setBeatIdx] = React.useState(reduced.current ? 5 : 0);
  const [showOutcome, setShowOutcome] = React.useState(reduced.current);
  const [fading, setFading] = React.useState(false);
  const [paused, setPaused] = React.useState(false);
  const inViewRef = React.useRef(true);
  const wrapRef = React.useRef(null);

  // Pause when out of viewport
  React.useEffect(() => {
    if (!wrapRef.current) return;
    const io = new IntersectionObserver(
      ([entry]) => { inViewRef.current = entry.isIntersecting; },
      { threshold: 0.2 }
    );
    io.observe(wrapRef.current);
    return () => io.disconnect();
  }, []);

  // Sequencer
  React.useEffect(() => {
    if (reduced.current) return;
    if (paused) return;

    const wf = workflows[wfIdx];
    if (!wf) return;

    const timers = [];

    // Reset
    setBeatIdx(0);
    setShowOutcome(false);
    setFading(false);

    // Beats
    const BEAT_STEP = 700;
    for (let i = 1; i <= wf.beats.length; i++) {
      timers.push(setTimeout(() => {
        if (inViewRef.current) setBeatIdx(i);
      }, i * BEAT_STEP));
    }
    // Outcome strap
    const outcomeAt = wf.beats.length * BEAT_STEP + 400;
    timers.push(setTimeout(() => {
      if (inViewRef.current) setShowOutcome(true);
    }, outcomeAt));

    // Hold + fade out
    const fadeAt = outcomeAt + 1400;
    timers.push(setTimeout(() => {
      if (inViewRef.current) setFading(true);
    }, fadeAt));

    // Advance
    timers.push(setTimeout(() => {
      if (inViewRef.current) {
        setWfIdx((i) => (i + 1) % workflows.length);
      } else {
        // when offscreen, skip to next on resume
      }
    }, fadeAt + 240));

    return () => timers.forEach(clearTimeout);
  }, [wfIdx, paused, workflows.length]);

  if (workflows.length === 0) return null;
  const wf = workflows[wfIdx];

  return (
    <div
      ref={wrapRef}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
      tabIndex={0}
      aria-label={
        lang === 'nl'
          ? `Voorbeeld werkstroom: ${wf.pillTitle} in ${wf.outcome.after}.`
          : `Example workflow: ${wf.pillTitle} in ${wf.outcome.after}.`
      }
      style={{
        position: 'relative',
        width: '100%',
        maxWidth: 560,
        background: 'var(--bg-raised)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--radius-card)',
        padding: 0,
        overflow: 'hidden',
        opacity: fading ? 0 : 1,
        transition: 'opacity 240ms var(--ease)',
        outline: 'none',
        fontFamily: 'var(--font-sans)',
      }}
    >
      {/* Header bar */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 16,
        padding: '14px 18px',
        borderBottom: '1px solid var(--border)',
        background: 'color-mix(in oklab, var(--bg-muted) 50%, transparent)',
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <span style={{
            width: 6, height: 6, borderRadius: 999,
            background: 'var(--accent)',
            boxShadow: '0 0 0 4px color-mix(in oklab, var(--accent) 25%, transparent)',
            flexShrink: 0,
          }}/>
          <span className="mono" style={{ color: 'var(--ink-muted)', fontSize: 10 }}>LIVE</span>
          <span style={{
            width: 1, height: 12, background: 'var(--border-strong)', flexShrink: 0,
          }}/>
          <span style={{
            fontFamily: 'var(--font-sans)',
            fontSize: 13,
            fontWeight: 500,
            color: 'var(--ink-primary)',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          }}>
            {wf.pillTitle}
          </span>
        </div>
        <span className="mono" style={{
          color: 'var(--ink-muted)', fontSize: 10, whiteSpace: 'nowrap', flexShrink: 0,
        }}>
          {wf.audience}
        </span>
      </div>

      {/* Beats */}
      <ol role="list" aria-live="off" style={{
        listStyle: 'none',
        margin: 0,
        padding: '12px 18px',
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
      }}>
        {wf.beats.map((b, i) => {
          const visible = i < beatIdx;
          return (
            <li key={i} style={{
              display: 'grid',
              gridTemplateColumns: '60px 1fr auto auto',
              alignItems: 'center',
              gap: 12,
              opacity: visible ? 1 : 0,
              transform: visible ? 'translateY(0)' : 'translateY(4px)',
              transition: 'opacity 180ms var(--ease), transform 180ms var(--ease)',
              fontSize: 13,
              minHeight: 22,
            }}>
              <span className="mono" style={{ color: 'var(--ink-muted)', fontSize: 11 }}>
                {b.time}
              </span>
              <span style={{ color: 'var(--ink-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {b.label}
              </span>
              <span className="mono" style={{
                color: 'var(--ink-muted)',
                fontSize: 11,
                textAlign: 'right',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                maxWidth: 200,
              }}>
                {b.meta}
              </span>
              <span aria-hidden="true" style={{
                width: 14, height: 14, borderRadius: 999,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: 'color-mix(in oklab, var(--accent) 18%, transparent)',
                color: 'var(--accent)',
                flexShrink: 0,
              }}>
                <svg width="9" height="9" viewBox="0 0 12 12" fill="none">
                  <path d="M2.5 6.2 5 8.7l4.5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </span>
            </li>
          );
        })}
      </ol>

      {/* Outcome strap */}
      <div style={{
        borderTop: '1px solid var(--border)',
        padding: '14px 18px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 16,
        flexWrap: 'wrap',
        background: 'color-mix(in oklab, var(--accent) 7%, transparent)',
        opacity: showOutcome ? 1 : 0,
        transform: showOutcome ? 'translateY(0)' : 'translateY(4px)',
        transition: 'opacity 220ms var(--ease), transform 220ms var(--ease)',
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
               style={{ color: 'var(--accent)', flexShrink: 0, transform: 'translateY(2px)' }}>
            <circle cx="12" cy="13" r="8"/>
            <path d="M12 9v4l2 2M9 2h6"/>
          </svg>
          <span className="mono" style={{
            color: 'var(--ink-muted)', fontSize: 12, textDecoration: 'line-through',
          }}>
            {wf.outcome.before}
          </span>
          <span className="mono" style={{ color: 'var(--ink-muted)', fontSize: 12 }}>\u2192</span>
          <span className="mono-num" style={{
            color: 'var(--accent)', fontSize: 18, fontWeight: 600,
          }}>
            {wf.outcome.after}
          </span>
        </div>
        <div className="mono" style={{
          fontSize: 11, color: 'var(--ink-muted)', whiteSpace: 'nowrap',
        }}>
          {wf.outcome.counterPrefix}{' '}
          <span className="mono-num" style={{ color: 'var(--ink-primary)', fontWeight: 500 }}>
            {wf.outcome.counterValue}
          </span>
        </div>
      </div>

      {/* Stack footer */}
      <div style={{
        borderTop: '1px solid var(--border)',
        padding: '10px 18px',
        fontFamily: 'var(--font-mono)',
        fontSize: 10,
        letterSpacing: '0.06em',
        color: 'var(--ink-muted)',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
      }}>
        {wf.stack}
      </div>

      {/* Workflow indicator dots */}
      <div style={{
        position: 'absolute',
        top: 14,
        right: 'calc(18px + 110px)',
      }}/>

      {/* Bottom-right dot indicator */}
      <div style={{
        position: 'absolute',
        right: 14,
        bottom: 14,
        display: 'inline-flex',
        gap: 4,
        pointerEvents: 'none',
      }}>
        {workflows.map((_, i) => (
          <span key={i} style={{
            width: 5, height: 5, borderRadius: 999,
            background: i === wfIdx ? 'var(--accent)' : 'var(--border-strong)',
            transition: 'background-color 200ms var(--ease)',
          }}/>
        ))}
      </div>
    </div>
  );
};

window.HeroWorkflowPanel = HeroWorkflowPanel;
// Keep old name available so app.jsx doesn't break if it still references it
window.HeroMotion = HeroWorkflowPanel;

// =============================================================
// HeroFlowBackdrop — ambient streamers behind the hero only.
// No labels, no nodes. Honours prefers-reduced-motion.
// =============================================================
const HeroFlowBackdrop = () => {
  const reduced = typeof window !== 'undefined' &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    if (reduced) return;
    let raf;
    const start = performance.now();
    const loop = (t) => {
      setTick((t - start) / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [reduced]);

  const streamers = [
    { x1: -50, y1:  90, c1x: 320, c1y:  70, c2x: 680, c2y: 220, x2: 1050, y2: 200, off: 0.0  },
    { x1: -50, y1: 230, c1x: 260, c1y: 210, c2x: 760, c2y: 340, x2: 1050, y2: 310, off: 0.25 },
    { x1: -50, y1: 390, c1x: 300, c1y: 380, c2x: 700, c2y: 470, x2: 1050, y2: 450, off: 0.50 },
    { x1: -50, y1: 560, c1x: 250, c1y: 600, c2x: 760, c2y: 510, x2: 1050, y2: 600, off: 0.75 },
  ];

  const bz = (t, p0, p1, p2, p3) => {
    const u = 1 - t;
    return u*u*u*p0 + 3*u*u*t*p1 + 3*u*t*t*p2 + t*t*t*p3;
  };

  return (
    <svg
      viewBox="0 0 1000 800"
      preserveAspectRatio="xMidYMid slice"
      aria-hidden="true"
      style={{
        position: 'absolute', inset: 0,
        width: '100%', height: '100%',
        opacity: 0.22, pointerEvents: 'none',
        zIndex: 0,
      }}
    >
      {streamers.map((s, i) => {
        const d = `M ${s.x1} ${s.y1} C ${s.c1x} ${s.c1y}, ${s.c2x} ${s.c2y}, ${s.x2} ${s.y2}`;
        return (
          <g key={i}>
            <path d={d} fill="none" stroke="var(--accent)" strokeOpacity="0.28" strokeWidth="0.8" />
            {!reduced && [0, 0.5].map((seed, j) => {
              const t = ((tick * 0.06) + seed + s.off) % 1;
              const cx = bz(t, s.x1, s.c1x, s.c2x, s.x2);
              const cy = bz(t, s.y1, s.c1y, s.c2y, s.y2);
              const fade = Math.sin(t * Math.PI);
              return <circle key={j} cx={cx} cy={cy} r="2.2" fill="var(--accent)" opacity={fade} />;
            })}
          </g>
        );
      })}
    </svg>
  );
};

window.HeroFlowBackdrop = HeroFlowBackdrop;
