/* global React, INK, CREAM, PULSE, GENS, GradText, CTAButton, Reveal, useReveal, useTyping, Shimmer, Waveform, SB_EASE,
   MPill, MPillP, MShell, MRail, MHead, MCopyHead, MPhone, MAppHeader, MSheet, MSheetFooter, MGenerate */
// Mobile § 01 Your Character (train + builder) · § 03 The studio (sticky phone, 3 modes)

const { useState: mcS, useEffect: mcE } = React;
const MREF = 'assets/gen/likeness-reference.webp';
const MOUTS = [{ src: 'assets/create/out-mirror.webp', scene: 'Mirror selfie' }, { src: 'assets/create/out-garden.webp', scene: 'Garden selfie' }, { src: 'assets/create/out-gym.webp', scene: 'Gym selfie' }];
const MPROMPT = 'mirror selfie of me in a white crop top and jean shorts in my bedroom';

// keeps offscreen product videos paused
const MAutoVideo = ({ src, style, preload = 'metadata' }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const v = ref.current;
    if (!v) return;
    v.muted = true; v.loop = true;
    const rewind = () => { v.currentTime = 0; v.play().catch(() => {}); };
    v.addEventListener('ended', rewind);
    const nudge = () => {
      const r = v.getBoundingClientRect();
      const on = r.bottom > 0 && r.top < window.innerHeight && r.width > 0;
      if (on) { if (v.paused) v.play().catch(() => {}); } else if (!v.paused) v.pause();
    };
    const io = new IntersectionObserver(nudge, { threshold: 0.01 });
    io.observe(v); nudge();
    v.addEventListener('canplay', nudge);
    const t = setInterval(nudge, 800);
    return () => { io.disconnect(); clearInterval(t); v.removeEventListener('canplay', nudge); v.removeEventListener('ended', rewind); };
  }, []);
  return <video ref={ref} src={src} autoPlay muted loop playsInline preload={preload} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', ...style }} />;
};

// ---------- § 01 — Your Character ----------
const MTrainInner = () => {
  const [barRef, on] = useReveal(0.35);
  const [pct, setPct] = mcS(0);
  const [ready, setReady] = mcS(false);
  mcE(() => {
    if (!on) return;
    let raf; const t0 = performance.now();
    const step = (t) => {
      const p = Math.min(1, (t - t0) / 2200);
      setPct(Math.round(100 * (1 - Math.pow(1 - p, 2.5))));
      if (p < 1) raf = requestAnimationFrame(step); else setReady(true);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [on]);
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 16 }}>
        {[['Face', 0], ['Body', 1], ['Voice', 2]].map(([label, i]) => (
          <Reveal key={label} delay={i * 110}>
            <div style={{ borderRadius: 14, background: '#fff', boxShadow: '0 4px 20px rgba(28,27,27,0.08), inset 0 0 0 1px rgba(28,27,27,0.08)', overflow: 'hidden' }}>
              <div style={{ height: 104, position: 'relative', overflow: 'hidden' }}>
                {i === 0 && <React.Fragment>
                  <img loading="lazy" decoding="async" src="assets/gen/ref-face.webp" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 22%' }} />
                  <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 34, animation: 'sz-scan-x 2.4s cubic-bezier(0.4,0,0.2,1) infinite',
                    background: 'linear-gradient(to bottom, transparent, rgba(166,117,255,0.5) 60%, rgba(129,60,237,0.85))', boxShadow: '0 0 18px 4px rgba(129,60,237,0.4)' }} />
                </React.Fragment>}
                {i === 1 && <img loading="lazy" decoding="async" src="assets/gen/ref-body.webp" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 32%', filter: 'saturate(0.9)' }} />}
                {i === 2 && <div style={{ width: '100%', height: '100%', display: 'grid', placeItems: 'center', background: 'var(--brand-purple-50)' }}><Waveform on bars={12} h={38} /></div>}
              </div>
              <div style={{ padding: '8px 10px', fontSize: 9, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-tertiary)' }}>{label}</div>
            </div>
          </Reveal>
        ))}
      </div>
      <Reveal delay={300}>
        <div ref={barRef} style={{ borderRadius: 16, background: '#fff', boxShadow: '0 4px 20px rgba(28,27,27,0.08), inset 0 0 0 1px rgba(28,27,27,0.08)', padding: '17px 17px 15px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 11 }}>
            <span style={{ fontSize: 13.5, fontWeight: 700, color: INK }}>{ready ? 'Character ready' : 'Building your Character…'}</span>
            {ready ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10.5, fontWeight: 700, color: '#22C55E' }}>
                <svg width="12" height="12" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="7" fill="#22C55E" /><path d="M5 8.2l2 2 4-4.4" stroke="#fff" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" /></svg>
                Private · encrypted
              </span>
            ) : <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--brand-purple-600)', fontVariantNumeric: 'tabular-nums' }}>{pct}%</span>}
          </div>
          <div style={{ height: 7, borderRadius: 9999, background: 'rgb(235,231,231)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${pct}%`, borderRadius: 9999, background: PULSE, transition: 'width 0.1s linear' }} />
          </div>
          <div style={{ marginTop: 10, fontSize: 12, lineHeight: 1.5, color: 'var(--text-secondary)' }}>Locked to your likeness. Never shared, never blended with anyone else.</div>
        </div>
      </Reveal>
    </div>
  );
};

const MCB_STEPS_UNUSED = ['Origin', 'Skin', 'Eyes', 'Hair', 'Physique', 'Details'];
const MCB_PANELS_UNUSED = [
  { label: 'Origin & Ethnicity', chips: ['Afro-Latina', 'Black / African', 'Celtic', 'Iberian', 'Japanese', 'Latin American'], active: 5 },
  { label: 'Skin details', chips: ['Fair', 'Light olive', 'Tan', 'Deep', 'Freckles'], active: 2 },
  { label: 'Eye color', chips: ['Hazel', 'Brown', 'Green', 'Blue', 'Gray'], active: 0 },
  { label: 'Hair details', chips: ['Jet black · long', 'Brunette · waves', 'Blonde · bob', 'Auburn · curls'], active: 1 },
  { label: 'Physique & body', chips: ['Slim', 'Athletic', 'Curvy', 'Voluptuous', 'Hips · wide'], active: 2 },
  { label: 'Distinctive features' },
];
const { CB_WIZ, CBTile } = window;
const MCharBuilder = () => {
  const [step, setStep] = mcS(CB_WIZ.length);
  const [picks, setPicks] = mcS(() => CB_WIZ.map(w => w.sel));
  const review = step >= CB_WIZ.length;
  const w = CB_WIZ[Math.min(step, CB_WIZ.length - 1)];
  const pct = review ? 100 : Math.round(((step + 1) / CB_WIZ.length) * 100);
  return (
    <Reveal delay={120}>
      <div style={{ borderRadius: 18, background: '#fff', boxShadow: '0 12px 32px rgba(28,27,27,0.10), inset 0 0 0 1px rgba(28,27,27,0.08)', padding: 15, textAlign: 'left' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 12 }}>
          <span style={{ fontSize: 8.5, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-tertiary)', whiteSpace: 'nowrap' }}>
            {review ? 'Review' : `Step ${step + 1} of ${CB_WIZ.length}`}</span>
          <span style={{ flex: 1, height: 4, borderRadius: 9999, background: 'rgb(235,231,231)', overflow: 'hidden' }}>
            <span style={{ display: 'block', height: '100%', width: `${pct}%`, borderRadius: 9999, background: PULSE, transition: 'width 0.4s cubic-bezier(0.2,0.8,0.2,1)' }} /></span>
        </div>
        {review ? (
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: '-0.02em', color: INK, marginBottom: 9 }}>Review &amp; generate</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 5 }}>
              {CB_WIZ.map((s, i) =>
                <span key={s.t} onClick={() => setStep(i)}><CBTile small name={s.o[picks[i]][0]} src={s.o[picks[i]][1]} on /></span>)}
            </div>
          </div>
        ) : (
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: '-0.02em', color: INK, marginBottom: 2 }}>{w.t}</div>
            <div style={{ fontSize: 10.5, color: 'var(--text-secondary)', marginBottom: 10 }}>{w.s}</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
              {w.o.map(([n, c], i) =>
                <CBTile key={n} name={n} src={c} on={picks[step] === i}
                  onClick={() => setPicks(p => p.map((v, k) => (k === step ? i : v)))} />)}
            </div>
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}>
          <span onClick={() => setStep(s => Math.max(0, s - 1))} style={{ borderRadius: 9999, padding: '7px 15px', fontSize: 10, fontWeight: 600, color: 'rgba(28,27,27,0.62)', boxShadow: 'inset 0 0 0 1px rgba(28,27,27,0.14)' }}>Back</span>
          <span onClick={() => setStep(s => (s >= CB_WIZ.length ? 0 : s + 1))} style={{ borderRadius: 9999, padding: '8px 16px', background: PULSE, color: '#fff', fontSize: 10, fontWeight: 700,
            letterSpacing: '0.04em', boxShadow: '0 8px 20px -4px rgba(104,19,212,0.4)' }}>{review ? 'Generate ✦' : 'Continue →'}</span>
        </div>
      </div>
    </Reveal>
  );
};

const MCharacterSection = () => {
  const [who, setWho] = mcS(0);
  return (
    <MShell>
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 30 }}>
        <div style={{ display: 'inline-flex', gap: 4, padding: 4, borderRadius: 9999, background: '#fff',
          boxShadow: 'inset 0 0 0 1px rgba(28,27,27,0.1), 0 4px 14px rgba(28,27,27,0.06)' }}>
          {['Clone Yourself', 'Build AI Influencers'].map((l, i) => (
            <span key={l} onClick={() => setWho(i)} style={{ borderRadius: 9999, padding: '10px 20px', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', transition: 'all 0.2s',
              background: i === who ? PULSE : 'transparent', color: i === who ? '#fff' : 'rgba(28,27,27,0.6)',
              boxShadow: i === who ? '0 8px 20px -4px rgba(104,19,212,0.4)' : 'none' }}>{l}</span>
          ))}
        </div>
      </div>
      <MCopyHead k={who === 0 ? 'train' : 'builder'} />
      <div style={{ marginTop: 34 }}>
        {who === 0 ? <MTrainInner /> : <MCharBuilder />}
      </div>
    </MShell>
  );
};

// ---------- § 03 — The studio (sticky phone, 3 modes) ----------
const MVLBL = { fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-tertiary)' };
const MSRC = ['Starting Image', 'Explore Video', 'Clone Reel', 'Describe'];

const MCreateSection = () => {
  const [ref, on] = useReveal(0.3);
  const [trackRef, prog] = window.useSmoothScroll();
  const zoomDone = prog >= 0.13;
  const [phase, setPhase] = mcS('idle');
  const [typed, doneTyping] = useTyping(MPROMPT, phase !== 'idle', 28, 300);
  mcE(() => { if (on && phase === 'idle') setPhase('typing'); }, [on]);
  mcE(() => {
    if (phase === 'typing' && doneTyping) { const t = setTimeout(() => setPhase('gen'), 700); return () => clearTimeout(t); }
    if (phase === 'gen') { const t = setTimeout(() => setPhase('done'), 1900); return () => clearTimeout(t); }
    if (phase === 'done') { const t = setTimeout(() => setPhase('typing'), 5200); return () => clearTimeout(t); }
  }, [phase, doneTyping]);
  const mode = prog < 0.3 ? 0 : prog < 0.78 ? 1 : 2;
  const vsrc = mode === 1 ? Math.min(3, Math.max(0, Math.floor((prog - 0.3) / 0.12))) : 0;
  // self-scroll the source rail so the active chip stays in view as scroll advances the walkthrough
  const srcRailRef = React.useRef(null);
  mcE(() => {
    const rail = srcRailRef.current;
    if (!rail) return;
    const chip = rail.children[vsrc];
    if (!chip) return;
    rail.scrollTo({ left: Math.max(0, chip.offsetLeft - rail.offsetLeft - 12), behavior: 'smooth' });
  }, [vsrc, mode]);
  const jumpTo = (i) => {
    const el = trackRef.current;
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY;
    window.scrollTo({ top: top + [0.15, 0.35, 0.86][i] * (el.offsetHeight - window.innerHeight), behavior: 'smooth' });
  };
  // image mode — output tiles + docked Compose (anatomy from Studio · Mobile compose sheet)
  const imagePanel = (
    <div style={{ padding: '0 12px 12px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9, marginBottom: 11 }}>
        {MOUTS.slice(0, 2).map((g, i) => {
          const loading = i === 0 && phase !== 'done' && !zoomDone;
          const ready = i !== 0 || phase === 'done' || zoomDone;
          return (
            <div key={i} style={{ position: 'relative', borderRadius: 12, overflow: 'hidden', background: 'rgb(246,243,242)', aspectRatio: '4 / 3' }}>
              {loading && <Shimmer style={{ position: 'absolute', inset: 0 }} />}
              <img loading="lazy" decoding="async" src={g.src} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 18%',
                opacity: ready ? 1 : 0, filter: ready ? 'none' : 'blur(14px)',
                transition: `opacity 0.6s ${SB_EASE} ${i * 180}ms, filter 0.8s ${SB_EASE} ${i * 180}ms` }} />
              <span style={{ position: 'absolute', left: 7, bottom: 7, fontSize: 8, fontWeight: 700, color: ready ? '#fff' : 'rgba(28,27,27,0.6)',
                background: ready ? 'rgba(28,27,27,0.55)' : '#fff', borderRadius: 9999, padding: '3px 7px' }}>{ready ? `${i + 1} / 4` : 'Generating…'}</span>
            </div>
          );
        })}
      </div>
      <div style={{ borderRadius: 18, background: '#fff', boxShadow: '0 -8px 30px rgba(28,27,27,0.10), inset 0 0 0 1px rgba(28,27,27,0.08)', padding: '11px 11px 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <span style={{ fontSize: 12.5, fontWeight: 800, letterSpacing: '-0.01em', color: INK }}>Compose</span>
          <span style={{ width: 20, height: 20, borderRadius: '50%', background: 'rgb(246,243,242)', display: 'grid', placeItems: 'center' }}>
            <svg width="8" height="8" viewBox="0 0 16 16" fill="none"><path d="M4 4l8 8M12 4l-8 8" stroke="rgba(28,27,27,0.6)" strokeWidth="1.9" strokeLinecap="round"/></svg>
          </span>
        </div>
        <div style={{ borderRadius: 14, boxShadow: 'inset 0 0 0 1.5px rgba(129,60,237,0.35)', padding: 9, marginBottom: 9 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 9 }}>
            <span style={{ width: 26, height: 26, borderRadius: 8, flexShrink: 0, outline: '1.5px dashed rgba(28,27,27,0.22)', outlineOffset: -1.5, display: 'grid', placeItems: 'center' }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="rgba(28,27,27,0.4)" strokeWidth="1.8"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M4 17l5-4 3 2 4-3 4 3"/></svg>
            </span>
            <div style={{ fontSize: 11, lineHeight: 1.45, color: typed ? INK : 'rgba(28,27,27,0.42)', minHeight: 28, fontWeight: 500 }}>
              {typed || 'Describe the scene, or type @ to reference an element…'}
              {phase === 'typing' && <span style={{ display: 'inline-block', width: 2, height: 12, background: 'var(--brand-purple-500)', marginLeft: 2, verticalAlign: 'middle', animation: 'sz-blink 1s step-end infinite' }} />}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 9999, padding: '4px 9px', fontSize: 9, fontWeight: 600, background: 'rgb(246,243,242)', boxShadow: 'inset 0 0 0 1px rgba(28,27,27,0.08)', color: INK }}>
              <span style={{ width: 11, height: 11, borderRadius: '50%', backgroundImage: `url(${GENS[0].src})`, backgroundSize: 'cover', backgroundPosition: 'center 15%' }} />Image ⌄
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 9999, padding: '3px 9px 3px 3px', fontSize: 9, fontWeight: 600, background: 'var(--brand-purple-50)', boxShadow: 'inset 0 0 0 1px var(--brand-purple-200)', color: 'var(--brand-purple-700)' }}>
              <span style={{ display: 'inline-flex' }}>
                {[GENS[6], GENS[8]].map((g, i) => (
                  <span key={i} style={{ width: 15, height: 15, borderRadius: 5, border: '1.5px solid #fff', marginLeft: i ? -5 : 0, backgroundImage: `url(${g.src})`, backgroundSize: 'cover', backgroundPosition: 'center 20%' }} />
                ))}
              </span>
              Photo Control · 2
            </span>
            <span style={{ marginLeft: 'auto', width: 22, height: 22, borderRadius: '50%', background: 'rgb(246,243,242)', boxShadow: 'inset 0 0 0 1px rgba(28,27,27,0.08)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="rgba(28,27,27,0.6)" strokeWidth="2"><path d="M4 8h16M4 16h10"/><circle cx="17" cy="16" r="3"/></svg>
            </span>
          </div>
        </div>
        <MGenerate count={4} active={doneTyping} />
      </div>
    </div>
  );
  // video mode — the full-screen source sheet (anatomy from Video UI spec, mobile screens V1–V5)
  const videoBody = vsrc === 0 ? (
    <div>
      <div style={{ display: 'flex', gap: 9, marginBottom: 10 }}>
        <div style={{ position: 'relative', width: 82, borderRadius: 11, overflow: 'hidden', aspectRatio: '3/3.8', flexShrink: 0 }}>
          <img loading="lazy" decoding="async" src="assets/create/starting-image.webp" alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 25%' }} />
          <span style={{ position: 'absolute', top: 5, left: 5, fontSize: 7, fontWeight: 700, color: '#fff', background: 'rgba(28,27,27,0.55)', borderRadius: 9999, padding: '2px 6px' }}>Starting image</span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ ...MVLBL, marginBottom: 6 }}>Direct the motion</div>
          <div style={{ borderRadius: 11, background: 'rgb(235,231,231)', padding: '9px 10px', fontSize: 10, lineHeight: 1.45, color: INK, fontWeight: 500,
            boxShadow: 'inset 0 2px 6px rgba(28,27,27,0.08)' }}>
            she laughs and brings the phone closer as she blows a kiss to her fans
          </div>
        </div>
      </div>
    </div>
  ) : vsrc === 1 ? (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6, marginBottom: 9 }}>
        {[['assets/video/explore-1.mp4', '0:30', true], ['assets/video/explore-2.mp4', '0:30', false], ['assets/video/explore-3.mp4', '0:12', false]].map(([src, d, sel], i) => (
          <div key={i} style={{ position: 'relative', borderRadius: 9, overflow: 'hidden', aspectRatio: '3/4', background: '#17121e',
            outline: sel ? '2px solid var(--brand-purple-500)' : '1px solid rgba(28,27,27,0.1)', outlineOffset: sel ? 1.5 : 0 }}>
            <video src={src} muted playsInline preload="metadata" ref={el => { if (el) { el.muted = true; el.currentTime = 0.1; } }}
              style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: sel ? 1 : 0.7 }} />
            <span style={{ position: 'absolute', right: 4, bottom: 4, fontSize: 7.5, fontWeight: 700, color: '#fff', background: 'rgba(20,16,23,0.6)', borderRadius: 9999, padding: '1px 5px' }}>{d}</span>
          </div>
        ))}
      </div>
      <div style={{ ...MVLBL, marginBottom: 6 }}>Select your clips</div>
      <div style={{ position: 'relative', height: 40, borderRadius: 8, overflow: 'hidden', marginBottom: 7 }}>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: 'repeat(6,1fr)' }}>
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} style={{ position: 'relative', overflow: 'hidden', borderRight: '1px solid rgba(255,255,255,0.3)' }}>
              <video src="assets/video/explore-1.mp4" muted playsInline preload="metadata"
                ref={el => { if (el) { el.muted = true; el.currentTime = 0.4 + i * 1.4; } }}
                style={{ position: 'absolute', top: '50%', left: '50%', width: '300%', transform: `translate(-${16 + i * 11}%, -50%)`, objectFit: 'cover' }} />
            </div>
          ))}
        </div>
        <div style={{ position: 'absolute', top: 0, bottom: 0, left: '16%', width: '46%', border: '2px solid var(--brand-purple-500)', borderRadius: 7, boxSizing: 'border-box',
          boxShadow: '0 0 0 999px rgba(255,255,255,0.6)' }}>
          <span style={{ position: 'absolute', left: -1.5, top: '50%', transform: 'translateY(-50%)', width: 3, height: 15, borderRadius: 2, background: 'var(--brand-purple-500)' }} />
          <span style={{ position: 'absolute', right: -1.5, top: '50%', transform: 'translateY(-50%)', width: 3, height: 15, borderRadius: 2, background: 'var(--brand-purple-500)' }} />
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 9.5, color: 'var(--text-secondary)' }}>1 clip · <b style={{ color: INK }}>4s of 15s</b></span>
        <MPillP active style={{ fontSize: 9.5, padding: '4px 9px' }}>+ Add clip</MPillP>
      </div>
    </div>
  ) : vsrc === 2 ? (
    <div>
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        {[['assets/reel-reference.mp4', 'The reference'], ['assets/reel-clone.mp4', 'Your likeness']].map(([src, l], i) => (
          <React.Fragment key={l}>
            {i === 1 && <svg width="24" height="14" viewBox="0 0 40 20" style={{ flexShrink: 0 }}>
              <line x1="2" y1="10" x2="30" y2="10" stroke="#813CED" strokeWidth="2" strokeDasharray="3 5" strokeLinecap="round" />
              <path d="M28 4l8 6-8 6" fill="none" stroke="#813CED" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>}
            <div style={{ position: 'relative', width: 116, aspectRatio: '9/14', borderRadius: 12, overflow: 'hidden', flexShrink: 0, background: '#17121e' }}>
              <MAutoVideo src={src} />
              <span style={{ position: 'absolute', left: 4, bottom: 4, fontSize: 6.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#fff',
                background: 'rgba(18,15,24,0.6)', borderRadius: 9999, padding: '2px 5px' }}>{l}</span>
            </div>
          </React.Fragment>
        ))}
      </div>
      <div style={{ ...MVLBL, marginBottom: 6 }}>Paste a reel link</div>
      <div style={{ display: 'flex', gap: 6 }}>
        <div style={{ flex: 1, borderRadius: 11, background: 'rgb(235,231,231)', display: 'flex', alignItems: 'center', gap: 6, padding: '0 10px', height: 36, minWidth: 0 }}>
          <span style={{ fontSize: 9.5, fontWeight: 500, color: 'rgba(28,27,27,0.5)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Paste a tiktok or reel link</span>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', borderRadius: 11, padding: '0 13px', height: 36, background: PULSE, color: '#fff',
          fontSize: 9.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', boxShadow: '0 8px 20px -4px rgba(104,19,212,0.4)' }}>Fetch</span>
      </div>
    </div>
  ) : (
    <div>
      <div style={{ ...MVLBL, marginBottom: 6 }}>Describe the video you imagine</div>
      <div style={{ borderRadius: 11, background: 'rgb(235,231,231)', padding: '10px 11px', fontSize: 10.5, color: INK, lineHeight: 1.5, marginBottom: 9 }}>
        <span style={{ color: 'var(--brand-purple-700)', fontWeight: 700 }}>@Scarlett</span> sits on the edge of her bed, morning light through sheer curtains. She bites her lip, lifts her eyes to camera and smirks. Slow push-in, warm natural grade.
      </div>
      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
        {[['@ References', true], ['Video Control · 2', true], ['15s · 9:16', false]].map(([c, sel]) => <MPillP key={c} active={sel} style={{ fontSize: 9.5, padding: '5px 9px' }}>{c}</MPillP>)}
      </div>
    </div>
  );
  const videoPanel = (
    <div style={{ padding: '0 12px 12px' }}>
      <div key={'v' + vsrc} style={{ borderRadius: 18, background: '#fff', boxShadow: '0 -8px 30px rgba(28,27,27,0.12), inset 0 0 0 1px rgba(28,27,27,0.08)', padding: '13px 12px 10px', animation: `sz-status-in 0.4s ${SB_EASE}` }}>
        <div style={{ fontSize: 14, fontWeight: 800, letterSpacing: '-0.01em', color: INK, marginBottom: 2 }}>Choose your source</div>
        <div style={{ fontSize: 9.5, lineHeight: 1.45, color: 'var(--text-secondary)', marginBottom: 9 }}>Animate a starting image, copy a reference video, or describe an idea.</div>
        <div ref={srcRailRef} className="m-nosb" style={{ display: 'flex', gap: 7, overflowX: 'auto', marginBottom: 11 }}>
          {MSRC.map((s, i) => <MPill key={s} active={i === vsrc} style={{ fontSize: 9.5, padding: '5px 10px' }}>{s}</MPill>)}
        </div>
        {videoBody}
        <MSheetFooter step={vsrc === 2 ? 1 : 2} of={vsrc === 2 ? 3 : 4} cta={vsrc === 0 || vsrc === 3 ? 'Generate · 15s' : 'Continue'} gen={vsrc === 0 || vsrc === 3} />
      </div>
    </div>
  );
  // live mode — full-bleed capture (anatomy from Live Mode spec, m-capture)
  const livePanel = (
    <div style={{ padding: '0 12px 12px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div style={{ position: 'relative', borderRadius: 16, overflow: 'hidden', background: '#111', aspectRatio: '9 / 16', width: '59.5%' }}>
        <MAutoVideo src="assets/video/live-mode-studio-9x16.mp4" preload="auto" />
        <span style={{ position: 'absolute', top: 12, left: 12, display: 'inline-flex', alignItems: 'center', gap: 4, background: '#EF4444', borderRadius: 9999, padding: '3px 9px' }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#fff', animation: 'sz-pulse-dot 1.1s ease-in-out infinite' }} />
          <span style={{ fontSize: 8, fontWeight: 800, letterSpacing: '0.08em', color: '#fff' }}>LIVE</span>
        </span>
        <span style={{ position: 'absolute', bottom: 14, left: '50%', transform: 'translateX(-50%)', width: 42, height: 42, borderRadius: '50%',
          border: '2.5px solid #fff', background: 'rgba(255,255,255,0.18)', backdropFilter: 'blur(4px)' }} />
      </div>
      <div style={{ margin: '10px 0 2px', fontSize: 10, lineHeight: 1.5, color: 'var(--text-secondary)', textAlign: 'center' }}>You act, they perform — frame by frame, 6 credits a minute.</div>
    </div>
  );
  const eRaw = Math.min(1, Math.max(0, Math.min(prog / 0.14, (1 - prog) / 0.1)));
  const e = eRaw * eRaw * (3 - 2 * eRaw);
  const eIn = Math.min(1, Math.max(0, prog / 0.14)); // entrance-only: card starts high, near the CTA, then settles to center
  const vw = typeof window !== 'undefined' ? window.innerWidth : 430;
  const vh = typeof window !== 'undefined' ? window.innerHeight : 850;
  const maxScale = Math.max(1, Math.min((Math.min(vw, 460) - 28) / 342, (vh - 90) / 560));
  const scale = 1 + (maxScale - 1) * e;
  const panels = [imagePanel, videoPanel, livePanel];
  return (
    <section style={{ background: '#fff', padding: '56px 0 0' }}>
      <div style={{ padding: '0 22px' }}><MCopyHead k="studio" /></div>
      <div ref={trackRef} style={{ height: '520vh', marginTop: 6 }}>
        <div ref={ref} style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
          <div style={{ transform: `translateY(${(-(1 - eIn) * vh * 0.22).toFixed(1)}px) scale(${scale.toFixed(4)})`, transformOrigin: 'center center', willChange: 'transform', width: 342, maxWidth: 'calc(100vw - 32px)' }}>
            <div style={{ borderRadius: 24, background: CREAM, boxShadow: '0 24px 48px rgba(28,27,27,0.14), inset 0 0 0 1px rgba(28,27,27,0.08)', overflow: 'hidden' }}>
              <MAppHeader />
              <div style={{ display: 'flex', gap: 5, padding: '4px 12px 10px', flexShrink: 0 }}>
                {['Create Image', 'Create Video', 'Live Mode'].map((m, i) => (
                  <span key={m} onClick={() => jumpTo(i)} style={{ flex: 1, textAlign: 'center', borderRadius: 9999, padding: '7px 0', fontSize: 8.5, fontWeight: i === mode ? 700 : 600, cursor: 'pointer', transition: 'all 0.25s',
                    background: i === mode ? INK : '#fff', color: i === mode ? '#fff' : 'rgba(28,27,27,0.6)',
                    boxShadow: i === mode ? 'none' : 'inset 0 0 0 1px rgba(28,27,27,0.1)', whiteSpace: 'nowrap' }}>{m}</span>
                ))}
              </div>
              <div key={mode === 2 ? 'x' : mode} style={{ display: mode === 2 ? 'none' : 'block', animation: `sz-status-in 0.45s ${SB_EASE}` }}>{mode === 2 ? null : panels[mode]}</div>
              <div style={{ display: mode === 2 ? 'block' : 'none' }}>{livePanel}</div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 7, marginTop: 12, opacity: e, transition: 'opacity 0.3s' }}>
              {[0, 1, 2].map((i) => (
                <span key={i} onClick={() => jumpTo(i)} style={{ width: i === mode ? 22 : 7, height: 7, borderRadius: 9999, cursor: 'pointer',
                  background: i === mode ? PULSE : 'rgba(28,27,27,0.18)', transition: `all 0.35s ${SB_EASE}` }} />
              ))}
            </div>
          </div>
        </div>
      </div>
      <div style={{ height: 6 }}></div>
    </section>
  );
};

Object.assign(window, { MCharacterSection, MCreateSection, MAutoVideo, MCharBuilder });
