// process.jsx — Scrollytelling "Our Process"
// Dramatic motion: per-step video backgrounds that crossfade, parallax layers,
// floating particles, animated counters, choreographed text, morphing glyph, progress meter

const PROCESS_VIDEOS = [
  "https://stream.mux.com/8wrHPCX2dC3msyYU9ObwqNdm00u3ViXvOSHUMRYSEe5Q.m3u8",
  "https://v1.pinimg.com/videos/mc/hls/2d/e9/25/2de925e37e614c574691f5a4e2eda33a.m3u8",
  "https://stream.mux.com/blULaJm2RMbAmsrwxLrBdgEx9yI1do2yM89vHTkdA6I.m3u8",
  "https://stream.mux.com/r6pXRAJb3005XEEbl1hYU1x01RFJDSn7KQApwNGgAHHbU.m3u8",
];

const PROCESS_STEPS = [
  {
    num: '01',
    kicker: 'Discovery',
    title: 'Listen before we sketch.',
    body: 'Every engagement starts with understanding — the business, the audience, the voice, and the unspoken reasons behind the brief. We ask the questions clients haven\'t thought to answer yet.',
    bullets: ['Stakeholder interviews', 'Audience mapping', 'Competitive audit', 'Scope alignment'],
    duration: '1 — 2 weeks',
    metric: { value: 24, suffix: ' hrs', label: 'First response' },
  },
  {
    num: '02',
    kicker: 'Design',
    title: 'Type, motion, and restraint.',
    body: 'We design in the browser, not in boards. Type systems, color, motion, and layout are explored together — because they only mean anything when they\'re moving, loading, and being read.',
    bullets: ['Type + color system', 'Motion principles', 'Responsive behavior', 'Component library'],
    duration: '2 — 3 weeks',
    metric: { value: 3, suffix: ' rounds', label: 'Direction refinement' },
  },
  {
    num: '03',
    kicker: 'Build',
    title: 'Hand-coded, not assembled.',
    body: 'No bloated page-builders, no borrowed templates. Every site is hand-written — optimized for speed, accessibility, and longevity. We care about the 95th-percentile load time as much as the hero animation.',
    bullets: ['Hand-written HTML/CSS/JS', 'Performance budgets', 'A11y pass', 'CMS wiring (optional)'],
    duration: '2 — 4 weeks',
    metric: { value: 98, suffix: '/100', label: 'Lighthouse target' },
  },
  {
    num: '04',
    kicker: 'Launch',
    title: 'And then we stay close.',
    body: 'We don\'t disappear at launch. Launch is a beginning — we monitor, analyze, and refine together. A website is a living thing, and the best ones grow slowly, on purpose.',
    bullets: ['QA + pre-launch', 'Soft + hard launch', 'Analytics review', 'Care plan handoff'],
    duration: '1 week + ongoing',
    metric: { value: 12, suffix: ' mo', label: 'Included care' },
  },
];

const GLYPHS = [
  "M 100 30 a 70 70 0 1 0 0.1 0 Z",
  "M 100 20 L 180 100 L 100 180 L 20 100 Z",
  "M 40 40 L 160 40 Q 180 40 180 60 L 180 140 Q 180 160 160 160 L 40 160 Q 20 160 20 140 L 20 60 Q 20 40 40 40 Z",
  "M 30 160 Q 100 20 170 160 L 170 165 Q 100 25 30 165 Z",
];

// Animated counter
function Counter({ value, suffix = '', duration = 1.4 }) {
  const [display, setDisplay] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const from = 0;
    const to = value;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / (duration * 1000));
      const eased = 1 - Math.pow(1 - t, 3);
      setDisplay(Math.round(from + (to - from) * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <span>{display}{suffix}</span>;
}

// Per-step video background with crossfade
function StepVideo({ src, active }) {
  const videoRef = React.useRef(null);
  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    if (src.includes('.m3u8')) {
      if (v.canPlayType('application/vnd.apple.mpegurl')) {
        v.src = src;
      } else if (window.Hls && window.Hls.isSupported()) {
        const hls = new window.Hls();
        hls.loadSource(src);
        hls.attachMedia(v);
        return () => hls.destroy();
      }
    } else {
      v.src = src;
    }
  }, [src]);
  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    if (active) v.play().catch(() => {});
  }, [active]);
  return (
    <motion.video
      ref={videoRef}
      muted playsInline loop autoPlay
      animate={{ opacity: active ? 1 : 0, scale: active ? 1 : 1.08 }}
      transition={{ duration: 1.2, ease: [0.16, 1, 0.3, 1] }}
      style={{
        position: 'absolute', inset: 0,
        width: '100%', height: '100%',
        objectFit: 'cover',
        opacity: 0,
      }}
    />
  );
}

// Floating geometric noise — subtle particles that drift
function ParticleField({ count = 18 }) {
  const particles = React.useMemo(() =>
    Array.from({ length: count }, (_, i) => ({
      id: i,
      x: Math.random() * 100,
      y: Math.random() * 100,
      size: 1 + Math.random() * 3,
      duration: 14 + Math.random() * 18,
      delay: Math.random() * 10,
    })), [count]);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      {particles.map(p => (
        <motion.span
          key={p.id}
          animate={{
            y: [0, -30, 0, 30, 0],
            x: [0, 15, 0, -15, 0],
            opacity: [0.15, 0.5, 0.15],
          }}
          transition={{ duration: p.duration, delay: p.delay, repeat: Infinity, ease: 'easeInOut' }}
          style={{
            position: 'absolute',
            left: `${p.x}%`,
            top: `${p.y}%`,
            width: p.size,
            height: p.size,
            borderRadius: '50%',
            background: 'var(--ink-950)',
            opacity: 0.2,
          }}
        />
      ))}
    </div>
  );
}

function Process() {
  const ref = React.useRef(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ['start start', 'end end'] });
  const smooth = useSpring(scrollYProgress, { stiffness: 120, damping: 28, mass: 0.4 });

  const [activeIdx, setActiveIdx] = React.useState(0);
  useMotionValueEvent(smooth, 'change', (v) => {
    const i = Math.min(PROCESS_STEPS.length - 1, Math.max(0, Math.floor(v * PROCESS_STEPS.length)));
    setActiveIdx(i);
  });

  // Glyph transforms
  const rotate = useTransform(smooth, [0, 1], [0, 540]);
  const scale = useTransform(smooth, [0, 0.5, 1], [0.9, 1.12, 0.95]);
  const glyphY = useTransform(smooth, [0, 1], [-20, 20]);

  // Parallax for background layers
  const bgY = useTransform(smooth, [0, 1], ['0%', '-15%']);
  const midY = useTransform(smooth, [0, 1], ['0%', '-8%']);

  // Progress bar
  const barWidth = useTransform(smooth, [0, 1], ['0%', '100%']);
  // Side gauge tick position (percent vertical)
  const gaugeY = useTransform(smooth, [0, 1], ['0%', '100%']);

  // Big number shadow behind glyph
  const bigNumY = useTransform(smooth, [0, 1], [0, -40]);

  return (
    <section ref={ref} style={{ position: 'relative', background: 'var(--ink-000)' }} data-screen-label="Process">

      {/* Sticky intro header */}
      <div style={{ position: 'relative', padding: '160px 0 80px', zIndex: 3 }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'end' }}>
            <div>
              <FadeUp>
                <div className="eyebrow" style={{ marginBottom: 24 }}>— The Process</div>
              </FadeUp>
              <h2 className="h2" style={{ fontSize: 'clamp(44px, 6.5vw, 96px)', textWrap: 'balance' }}>
                <div><SplitWords text="Four acts." /></div>
                <div><SplitWords text="No mystery." delay={0.1} em={[1]} /></div>
              </h2>
            </div>
            <FadeUp delay={0.2}>
              <p className="lead">
                A transparent, linear engagement — from first conversation to
                post-launch. Scroll through to see how a project moves through
                the studio.
              </p>
            </FadeUp>
          </div>
        </div>
      </div>

      {/* Sticky scrolly container */}
      <div style={{ position: 'relative' }}>
        {/* Sticky viewport */}
        <div style={{ position: 'sticky', top: 0, height: '100vh', overflow: 'hidden' }}>

          {/* Parallax video layer — all 4 videos stacked, crossfade by active step */}
          <motion.div style={{ position: 'absolute', inset: '-10% 0', y: bgY, zIndex: 0 }}>
            {PROCESS_VIDEOS.map((src, i) => (
              <StepVideo key={i} src={src} active={i === activeIdx} />
            ))}
          </motion.div>

          {/* Scrim gradient on top of video */}
          <div style={{
            position: 'absolute', inset: 0, zIndex: 1,
            background: 'linear-gradient(180deg, rgba(6,6,7,.55) 0%, rgba(6,6,7,.7) 50%, rgba(6,6,7,.85) 100%)',
            pointerEvents: 'none',
          }} />

          {/* Noise particles */}
          <motion.div style={{ position: 'absolute', inset: 0, y: midY, zIndex: 2 }}>
            <ParticleField count={24} />
          </motion.div>

          {/* Oversized ghost number behind glyph */}
          <motion.div
            style={{
              position: 'absolute',
              left: '10%', top: '50%', y: bigNumY,
              transform: 'translateY(-50%)',
              fontFamily: 'var(--font-display)',
              fontSize: 'clamp(400px, 50vw, 800px)',
              fontStyle: 'italic',
              lineHeight: 0.8,
              color: 'rgba(255,255,255,0.08)',
              opacity: 1,
              pointerEvents: 'none',
              zIndex: 2,
              fontWeight: 400,
            }}
          >
            <AnimatePresence mode="wait">
              <motion.span
                key={activeIdx}
                initial={{ opacity: 0, x: -60, filter: 'blur(20px)' }}
                animate={{ opacity: 1, x: 0, filter: 'blur(0px)' }}
                exit={{ opacity: 0, x: 60, filter: 'blur(20px)' }}
                transition={{ duration: 0.9, ease: [0.16, 1, 0.3, 1] }}
                style={{ display: 'inline-block' }}
              >
                {PROCESS_STEPS[activeIdx].num}
              </motion.span>
            </AnimatePresence>
          </motion.div>

          {/* Two-column content grid */}
          <div style={{
            position: 'relative', zIndex: 5,
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            alignItems: 'center',
            height: '100%',
          }}>
            {/* Left — glyph + rings */}
            <div style={{ position: 'relative', height: '100%', display: 'grid', placeItems: 'center' }}>
              <motion.div style={{ position: 'relative', width: '65%', maxWidth: 520, aspectRatio: '1', display: 'grid', placeItems: 'center', y: glyphY }}>

                {/* Multiple rotating ring sets */}
                <motion.svg
                  viewBox="0 0 200 200"
                  style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.3 }}
                  animate={{ rotate: 360 }}
                  transition={{ duration: 60, repeat: Infinity, ease: 'linear' }}
                >
                  {[92, 96].map((r, i) => (
                    <circle key={i} cx="100" cy="100" r={r} fill="none" stroke="rgba(255,255,255,0.35)" strokeWidth="0.3" strokeDasharray={i === 0 ? "1 3" : "4 8"} />
                  ))}
                </motion.svg>
                <motion.svg
                  viewBox="0 0 200 200"
                  style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.4 }}
                  animate={{ rotate: -360 }}
                  transition={{ duration: 40, repeat: Infinity, ease: 'linear' }}
                >
                  {[60, 75].map((r, i) => (
                    <circle key={i} cx="100" cy="100" r={r} fill="none" stroke="rgba(255,255,255,0.4)" strokeWidth="0.5" strokeDasharray="2 6" />
                  ))}
                </motion.svg>

                {/* Tick marks around outer ring */}
                <svg viewBox="0 0 200 200" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
                  {Array.from({ length: 48 }).map((_, i) => {
                    const angle = (i / 48) * Math.PI * 2 - Math.PI / 2;
                    const inner = 86, outer = 92;
                    const x1 = 100 + Math.cos(angle) * inner;
                    const y1 = 100 + Math.sin(angle) * inner;
                    const x2 = 100 + Math.cos(angle) * outer;
                    const y2 = 100 + Math.sin(angle) * outer;
                    const major = i % 12 === 0;
                    return (
                      <motion.line
                        key={i}
                        x1={x1} y1={y1} x2={x2} y2={y2}
                        stroke="rgba(255,255,255,0.9)"
                        strokeWidth={major ? 0.8 : 0.4}
                        initial={{ opacity: 0 }}
                        animate={{ opacity: major ? 0.85 : 0.35 }}
                        transition={{ delay: i * 0.01, duration: 0.4 }}
                      />
                    );
                  })}
                </svg>

                {/* Morphing glyph */}
                <motion.svg
                  viewBox="0 0 200 200"
                  style={{ width: '100%', height: '100%', rotate, scale, position: 'relative', zIndex: 2 }}
                >
                  <AnimatePresence mode="wait">
                    <motion.path
                      key={activeIdx}
                      d={GLYPHS[activeIdx]}
                      fill="none"
                      stroke="#fafaf6"
                      strokeWidth="1.4"
                      initial={{ opacity: 0, pathLength: 0, scale: 0.85 }}
                      animate={{ opacity: 1, pathLength: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 1.15 }}
                      transition={{ duration: 1, ease: [0.16, 1, 0.3, 1] }}
                    />
                  </AnimatePresence>
                  {/* pulsing center dot */}
                  <motion.circle
                    cx="100" cy="100" r="2"
                    fill="#fafaf6"
                    animate={{ r: [2, 3.5, 2] }}
                    transition={{ duration: 2.4, repeat: Infinity, ease: 'easeInOut' }}
                  />
                </motion.svg>

                {/* Glyph label */}
                <div style={{ position: 'absolute', bottom: -28, left: 0, right: 0, textAlign: 'center' }}>
                  <AnimatePresence mode="wait">
                    <motion.div
                      key={activeIdx}
                      className="mono"
                      initial={{ opacity: 0, y: 14, letterSpacing: '0.3em' }}
                      animate={{ opacity: 1, y: 0, letterSpacing: '0.14em' }}
                      exit={{ opacity: 0, y: -14 }}
                      transition={{ duration: 0.6 }}
                      style={{ color: 'rgba(250,249,246,0.85)' }}
                    >
                      {PROCESS_STEPS[activeIdx].num} — {PROCESS_STEPS[activeIdx].kicker}
                    </motion.div>
                  </AnimatePresence>
                </div>
              </motion.div>
            </div>

            {/* Right — chapter content */}
            <div style={{ padding: '0 var(--gutter)' }}>
              <AnimatePresence mode="wait">
                <motion.div
                  key={activeIdx}
                  initial={{ opacity: 0, y: 28 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -28 }}
                  transition={{ duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
                  style={{ maxWidth: 560 }}
                >
                  <motion.div
                    initial={{ scaleX: 0 }}
                    animate={{ scaleX: 1 }}
                    transition={{ duration: 0.8, delay: 0.1, ease: [0.16, 1, 0.3, 1] }}
                    style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24, transformOrigin: 'left' }}
                  >
                    <span className="mono" style={{ color: '#fafaf6' }}>{PROCESS_STEPS[activeIdx].num}</span>
                    <span style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.25)' }} />
                    <span className="mono" style={{ color: 'rgba(250,249,246,0.7)' }}>{PROCESS_STEPS[activeIdx].duration}</span>
                  </motion.div>

                  <div className="eyebrow" style={{ marginBottom: 20, color: 'rgba(250,249,246,0.7)' }}>{PROCESS_STEPS[activeIdx].kicker}</div>

                  {/* Title with word-by-word entrance */}
                  <h3 className="display" style={{ fontSize: 'clamp(32px, 3.2vw, 52px)', lineHeight: 1.05, marginBottom: 24, textWrap: 'balance', color: '#fafaf6' }}>
                    {PROCESS_STEPS[activeIdx].title.split(' ').map((word, wi) => (
                      <motion.span
                        key={wi}
                        initial={{ opacity: 0, y: '60%', filter: 'blur(8px)' }}
                        animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
                        transition={{ delay: 0.15 + wi * 0.06, duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
                        style={{ display: 'inline-block', marginRight: '0.22em' }}
                      >
                        {word}
                      </motion.span>
                    ))}
                  </h3>

                  <motion.p
                    initial={{ opacity: 0, y: 16 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4, duration: 0.7 }}
                    style={{ fontSize: 16, lineHeight: 1.6, color: 'rgba(250,249,246,0.85)', marginBottom: 32, maxWidth: '44ch' }}
                  >
                    {PROCESS_STEPS[activeIdx].body}
                  </motion.p>

                  <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    {PROCESS_STEPS[activeIdx].bullets.map((b, k) => (
                      <motion.li
                        key={k}
                        initial={{ opacity: 0, x: -16 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 0.5 + k * 0.08, duration: 0.55 }}
                        style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 13, color: 'rgba(250,249,246,0.9)' }}
                      >
                        <motion.span
                          animate={{ scale: [1, 1.4, 1] }}
                          transition={{ delay: 0.6 + k * 0.08, duration: 0.7 }}
                          style={{ width: 6, height: 6, border: '1px solid rgba(250,249,246,0.55)', borderRadius: '50%', display: 'inline-block', flexShrink: 0 }}
                        />
                        {b}
                      </motion.li>
                    ))}
                  </ul>

                  {/* Animated metric card */}
                  <motion.div
                    initial={{ opacity: 0, y: 20, scale: 0.96 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    transition={{ delay: 0.6, duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
                    className="glass"
                    style={{ padding: '20px 24px', display: 'flex', alignItems: 'baseline', gap: 16, borderRadius: 3 }}
                  >
                    <div
                      className="display"
                      style={{ fontSize: 48, lineHeight: 1, fontStyle: 'italic', color: '#fafaf6' }}
                    >
                      <Counter value={PROCESS_STEPS[activeIdx].metric.value} suffix={PROCESS_STEPS[activeIdx].metric.suffix} />
                    </div>
                    <div className="mono" style={{ color: 'rgba(250,249,246,0.7)' }}>
                      {PROCESS_STEPS[activeIdx].metric.label}
                    </div>
                  </motion.div>
                </motion.div>
              </AnimatePresence>

              {/* step pips */}
              <div style={{ marginTop: 40, display: 'flex', gap: 8 }}>
                {PROCESS_STEPS.map((_, i) => (
                  <motion.span
                    key={i}
                    animate={{
                      width: i === activeIdx ? 56 : 22,
                      opacity: i <= activeIdx ? 1 : 0.25,
                    }}
                    transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }}
                    style={{ height: 2, background: 'var(--ink-950)', display: 'inline-block' }}
                  />
                ))}
              </div>

              {/* progress bar */}
              <div style={{ marginTop: 16, height: 1, background: 'var(--glass-border)', position: 'relative', overflow: 'hidden' }}>
                <motion.div style={{
                  width: barWidth,
                  height: '100%',
                  background: 'var(--ink-950)',
                  position: 'absolute',
                  left: 0, top: 0,
                }} />
              </div>
            </div>
          </div>

          {/* Left-edge vertical gauge */}
          <div style={{
            position: 'absolute',
            left: 32, top: '50%', transform: 'translateY(-50%)',
            height: '50%',
            zIndex: 6,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 12,
          }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--ink-700)' }}>00</div>
            <div style={{ flex: 1, width: 1, background: 'var(--glass-border)', position: 'relative' }}>
              <motion.div
                style={{
                  position: 'absolute',
                  top: gaugeY,
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: 9, height: 9,
                  background: 'var(--ink-950)',
                  borderRadius: '50%',
                }}
              />
              <motion.div
                style={{
                  position: 'absolute',
                  top: 0, left: 0,
                  width: '100%',
                  height: gaugeY,
                  background: 'var(--ink-950)',
                }}
              />
            </div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--ink-700)' }}>FIN</div>
          </div>

          {/* Right-edge step counter */}
          <div style={{
            position: 'absolute',
            right: 32, top: 32,
            zIndex: 6,
            display: 'flex',
            alignItems: 'baseline',
            gap: 6,
          }}>
            <AnimatePresence mode="wait">
              <motion.span
                key={activeIdx}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -12 }}
                className="display"
                style={{ fontSize: 36, fontStyle: 'italic', color: 'var(--ink-950)' }}
              >
                {PROCESS_STEPS[activeIdx].num}
              </motion.span>
            </AnimatePresence>
            <span className="mono" style={{ color: 'var(--ink-700)' }}>/ {String(PROCESS_STEPS.length).padStart(2, '0')}</span>
          </div>
        </div>

        {/* Scroll spacers — one per step */}
        {PROCESS_STEPS.map((_, i) => (
          <div key={i} style={{ height: '100vh' }} />
        ))}
      </div>

      {/* Outro CTA */}
      <div className="container" style={{ padding: '120px 0 160px', position: 'relative', zIndex: 3 }}>
        <FadeUp>
          <div className="glass" style={{ padding: '72px 56px', borderRadius: 3, textAlign: 'center', maxWidth: 900, margin: '0 auto' }}>
            <div className="eyebrow" style={{ marginBottom: 20 }}>— Ready?</div>
            <h3 className="display" style={{ fontSize: 'clamp(36px, 4.2vw, 68px)', marginBottom: 28, textWrap: 'balance' }}>
              Let's build something <em>inevitable.</em>
            </h3>
            <p className="lead" style={{ margin: '0 auto 36px' }}>
              Two project slots remain for summer 2026. Tell us about your project
              — we respond to every inquiry within two business days.
            </p>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 12, flexWrap: 'wrap' }}>
              <a href="contact.html" className="btn btn--primary">Start a project <span className="arrow">→</span></a>
              <a href="pricing.html" className="btn btn--ghost">See pricing</a>
            </div>
          </div>
        </FadeUp>
      </div>
    </section>
  );
}

Object.assign(window, { Process });
