// pilot.jsx — Kinema Lite (30-day pilot)
// Self-serve consumer flow: landing → checkout → confirmation → program → exercise + admin
// Reuses Kinema design tokens; no clinical surfaces.

const PROGRAM_NAME = 'Built Back';
const PRICE = '$99';
const PRICE_NUM = 99;

// ─────────────────────────────────────────────────────────────
// 01 · Landing page — what an Instagram visitor sees
// ─────────────────────────────────────────────────────────────
function LandingScreen({ onNext }) {
  return (
    <div className="app-body" style={{ background: 'var(--paper)' }}>
      <div className="app-scroll" style={{ paddingTop: 60, paddingBottom: 40 }}>
        {/* Hero */}
        <div style={{ padding: '28px 22px 18px' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.14em', textTransform: 'uppercase',
            color: 'var(--clay-2)', marginBottom: 14,
          }}>A program by Matt Midkiff, PT, DPT, CSCS</div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 42, lineHeight: 1.02, letterSpacing: '-0.035em',
            margin: 0, color: 'var(--ink)',
          }}>{PROGRAM_NAME}.</h1>
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 500,
            fontSize: 22, lineHeight: 1.2, letterSpacing: '-0.02em',
            margin: '8px 0 0', color: 'var(--muted)',
          }}>A 4-week ACL recovery program you can run yourself.</h2>
        </div>

        {/* Matt photo + intro */}
        <div style={{ padding: '12px 22px 6px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <img src="matt.png" alt="Matt Midkiff" style={{
            width: 64, height: 64, borderRadius: 999, flexShrink: 0,
            objectFit: 'cover', objectPosition: '50% 30%',
            border: '0.5px solid var(--line)',
          }}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 15, letterSpacing: '-0.005em' }}>Matt Midkiff</div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2, lineHeight: 1.35 }}>
              PT, DPT, CSCS · [X] years treating [SPECIALTY]
            </div>
          </div>
        </div>

        <div style={{ padding: '14px 22px 20px' }}>
          <p style={{
            margin: 0, fontSize: 15.5, lineHeight: 1.5,
            color: 'var(--ink-2)', letterSpacing: '-0.005em',
          }}>
            I get DMs every week from people stuck after ACL surgery — no PT nearby, or done with their sessions and still not back. This is the program I'd give you in person.
          </p>
        </div>

        {/* Hero card with sample video preview */}
        <div style={{ padding: '4px 22px' }}>
          <div style={{
            borderRadius: 18, overflow: 'hidden',
            border: '0.5px solid var(--line)',
            boxShadow: 'var(--shadow-md)',
          }}>
            <div className="video-ph" style={{ height: 200 }}>
              <div className="badge">Preview · week 1, day 1</div>
              <div className="play"><IconPlay size={22}/></div>
              <div className="duration">2:04</div>
            </div>
            <div style={{ padding: '12px 14px', background: 'var(--bone-card)' }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Quad set + heel slide</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
                Watch a full exercise before you buy
              </div>
            </div>
          </div>
        </div>

        {/* What you get */}
        <div style={{ padding: '32px 22px 8px' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 14,
          }}>What you get</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, alignItems: 'stretch' }}>
            {[
              { n: '12', l: 'Video exercises', sub: 'Filmed, cued, and progressed by Matt' },
              { n: '4', l: 'Weeks of structure', sub: 'Day-by-day plan, no guessing what to do' },
              { icon: true, l: 'Lifetime access', sub: 'Re-run the program any time' },
            ].map((it, i) => (
              <div key={i} style={{
                padding: '20px 10px 16px',
                background: 'var(--bone-card)',
                border: '0.5px solid var(--line)',
                borderRadius: 14,
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                textAlign: 'center',
              }}>
                <div style={{ height: 48, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {it.icon
                    ? <div style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--clay-soft)', color: 'var(--clay-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconCheck size={22} stroke={2.6}/></div>
                    : <div className="bignum" style={{ fontSize: 42, lineHeight: 1, letterSpacing: '-0.04em', color: 'var(--clay)' }}>{it.n}</div>
                  }
                </div>
                <div style={{
                  fontSize: 12.5, fontWeight: 600, color: 'var(--ink)',
                  marginTop: 12, lineHeight: 1.2, letterSpacing: '-0.005em',
                }}>{it.l}</div>
                <div style={{
                  fontSize: 10.5, color: 'var(--muted)', fontWeight: 400,
                  marginTop: 6, lineHeight: 1.35,
                }}>{it.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Testimonial */}
        <div style={{ padding: '24px 22px 8px' }}>
          <div className="card" style={{ padding: 20 }}>
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 500,
              fontSize: 17, lineHeight: 1.4, letterSpacing: '-0.01em',
              color: 'var(--ink)',
            }}>
              "Testimonial placeholder — pull a real quote from one of Matt's DMs or a former patient before launch."
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
              <div className="img-ph" style={{
                width: 32, height: 32, borderRadius: 999,
                fontSize: 9,
              }}>—</div>
              <div style={{ fontSize: 12, color: 'var(--muted)' }}>
                Name, age · ACL · followed program to week 4
              </div>
            </div>
          </div>
        </div>

        {/* Price + CTA */}
        <div style={{ padding: '28px 22px 12px' }}>
          <div style={{
            display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14,
          }}>
            <div className="bignum" style={{
              fontSize: 44, lineHeight: 1, letterSpacing: '-0.04em',
            }}>{PRICE}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)' }}>one-time · lifetime access</div>
          </div>
          <button className="btn clay full" style={{ height: 56, fontSize: 16 }} onClick={onNext}>
            Get the program
            <IconChevron size={16} stroke={2.4}/>
          </button>
          <div style={{
            fontSize: 12, color: 'var(--muted)', textAlign: 'center',
            marginTop: 12, letterSpacing: '0.01em',
          }}>
            Secure checkout · Stripe
          </div>
        </div>

        {/* Footnote */}
        <div style={{ padding: '24px 22px 8px', borderTop: '0.5px solid var(--line)', marginTop: 24 }}>
          <div style={{ fontSize: 11.5, color: 'var(--muted-2)', lineHeight: 1.5 }}>
            {PROGRAM_NAME} is an educational program. It is not a substitute for individualized medical advice. If you're post-op, clear new activity with your surgeon or PT.
          </div>
          <div style={{ marginTop: 14, fontSize: 11.5, color: 'var(--muted-2)' }}>
            Already a member? <a href="#" style={{ color: 'var(--muted)', textDecoration: 'underline' }}>Open the program from your email link.</a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 02 · Stripe-style checkout
// ─────────────────────────────────────────────────────────────
function CheckoutScreen({ onNext, onBack }) {
  return (
    <div className="app-body" style={{ background: '#F5F4F2' }}>
      <div className="app-scroll" style={{ paddingTop: 60, paddingBottom: 30 }}>
        {/* Header strip — Stripe-y */}
        <div style={{
          padding: '6px 22px 16px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button onClick={onBack} style={{
            background: 'transparent', border: 0, padding: 0,
            display: 'flex', alignItems: 'center', gap: 4,
            color: 'var(--muted)', cursor: 'pointer', fontSize: 14,
          }}>
            <IconBack size={18}/> Back
          </button>
          <div style={{
            fontSize: 10, color: 'var(--muted-2)',
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            <IconLock size={11} stroke={2}/>
            <span style={{ letterSpacing: '0.04em', textTransform: 'uppercase' }}>stripe</span>
          </div>
        </div>

        {/* Order summary */}
        <div style={{ padding: '0 22px 20px' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 8,
          }}>Order</div>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22, letterSpacing: '-0.02em' }}>
                {PROGRAM_NAME}
              </div>
              <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4, lineHeight: 1.4 }}>
                4-week ACL recovery program · 12 video exercises · lifetime access
              </div>
            </div>
            <div className="bignum" style={{ fontSize: 24, letterSpacing: '-0.03em' }}>{PRICE}</div>
          </div>
        </div>

        <div style={{ height: 0.5, background: 'var(--line)', margin: '0 22px 22px' }}/>

        {/* Apple Pay express */}
        <div style={{ padding: '0 22px 18px' }}>
          <button style={{
            width: '100%', height: 52, borderRadius: 12,
            background: '#000', color: '#fff', border: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            fontSize: 17, fontWeight: 500, cursor: 'pointer',
            letterSpacing: '-0.005em',
          }}>
            <span style={{ fontSize: 15 }}>Pay with</span>
            <svg width="44" height="18" viewBox="0 0 44 18" fill="#fff">
              <path d="M8.2 2.4c-.5.6-1.3 1.1-2.1 1-.1-.8.3-1.7.8-2.2.5-.6 1.4-1.1 2.1-1.1.1.8-.3 1.7-.8 2.3zm.8.9c-1.2-.1-2.2.7-2.7.7-.6 0-1.4-.6-2.4-.6-1.2 0-2.4.7-3 1.8-1.3 2.2-.3 5.5.9 7.3.6.9 1.4 1.9 2.4 1.8.9 0 1.3-.6 2.4-.6 1.1 0 1.4.6 2.4.6 1 0 1.7-.9 2.3-1.8.7-1 1-2 1-2.1 0 0-2-.8-2-3 0-1.9 1.5-2.8 1.6-2.8-.9-1.3-2.2-1.4-2.7-1.4z"/>
              <text x="13" y="13" fontFamily="-apple-system, system-ui" fontSize="11" fontWeight="600" fill="#fff">Pay</text>
            </svg>
          </button>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            margin: '18px 0 6px',
          }}>
            <div style={{ flex: 1, height: 0.5, background: 'var(--line)' }}/>
            <div style={{ fontSize: 11, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              or pay with card
            </div>
            <div style={{ flex: 1, height: 0.5, background: 'var(--line)' }}/>
          </div>
        </div>

        {/* Form */}
        <div style={{ padding: '0 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <FormField label="Email">
            <span style={{ color: 'var(--ink)' }}>jordan.reyes@gmail.com</span>
            <span style={{ color: 'var(--muted-2)', marginLeft: 'auto', fontSize: 12 }}>↵</span>
          </FormField>
          <FormField label="Card information">
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, letterSpacing: '0.06em', color: 'var(--ink)' }}>
              4242 4242 4242 4242
            </span>
            <div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
              <CardLogo brand="visa"/>
              <CardLogo brand="mc"/>
              <CardLogo brand="amex"/>
            </div>
          </FormField>
          <div style={{ display: 'flex', gap: 8 }}>
            <FormField label="Expiry" compact>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14 }}>12 / 28</span>
            </FormField>
            <FormField label="CVC" compact>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--muted-2)' }}>•••</span>
            </FormField>
          </div>
          <FormField label="Name on card">
            <span style={{ color: 'var(--ink)' }}>Jordan Reyes</span>
          </FormField>
          <FormField label="Country">
            <span style={{ color: 'var(--ink)' }}>United States</span>
            <IconChevronDown size={14} color="var(--muted-2)"/>
          </FormField>
        </div>

        {/* Pay button */}
        <div style={{ padding: '24px 22px 0' }}>
          <button onClick={onNext} style={{
            width: '100%', height: 52, borderRadius: 12,
            background: '#635BFF', color: '#fff', border: 0,
            fontSize: 16, fontWeight: 600, cursor: 'pointer',
            letterSpacing: '-0.005em',
            boxShadow: '0 2px 6px rgba(99,91,255,0.25)',
          }}>
            Pay {PRICE}
          </button>
          <div style={{
            textAlign: 'center', fontSize: 11, color: 'var(--muted-2)',
            marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}>
            <IconLock size={11} stroke={2}/> Secured by Stripe
          </div>
        </div>
      </div>
    </div>
  );
}

function FormField({ label, children, compact }) {
  return (
    <div style={{
      flex: compact ? 1 : 'initial',
      background: '#fff',
      border: '1px solid #E0DDD7',
      borderRadius: 8,
      padding: '8px 12px 10px',
    }}>
      <div style={{
        fontSize: 11, color: 'var(--muted)',
        letterSpacing: '-0.005em', marginBottom: 2,
      }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14 }}>
        {children}
      </div>
    </div>
  );
}

function CardLogo({ brand }) {
  const logos = {
    visa: { bg: '#1A1F71', text: 'VISA', size: 9 },
    mc: { bg: '#EB001B', text: 'mc', size: 9 },
    amex: { bg: '#006FCF', text: 'AMEX', size: 8 },
  };
  const l = logos[brand];
  return (
    <div style={{
      width: 26, height: 16, borderRadius: 3,
      background: l.bg, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: l.size, fontWeight: 700, letterSpacing: '0.02em',
      fontFamily: 'var(--font-display)',
    }}>{l.text}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// 03 · Post-purchase confirmation — "you're in"
// ─────────────────────────────────────────────────────────────
function ConfirmationScreen({ onNext }) {
  return (
    <div className="app-body" style={{ background: 'var(--bone)' }}>
      <div className="app-scroll" style={{
        paddingTop: 60, paddingBottom: 30,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ flex: 1, padding: '40px 28px 0', display: 'flex', flexDirection: 'column' }}>
          {/* Checkmark */}
          <div style={{
            width: 64, height: 64, borderRadius: 999,
            background: 'var(--sage)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 24,
            boxShadow: '0 6px 16px rgba(107,142,99,0.3)',
          }}>
            <IconCheck size={32} stroke={2.6}/>
          </div>

          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 36, lineHeight: 1.05, letterSpacing: '-0.03em',
            margin: '0 0 12px',
          }}>You're in, Jordan.</h1>
          <p style={{
            margin: 0, fontSize: 16, lineHeight: 1.45,
            color: 'var(--ink-2)', letterSpacing: '-0.005em',
          }}>
            Your 4-week program is unlocked. First session is 3 exercises, ~12 minutes.
          </p>

          {/* Receipt strip */}
          <div className="card" style={{
            padding: 16, marginTop: 28,
            background: 'var(--bone-card)',
          }}>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--muted)', marginBottom: 10,
            }}>Receipt</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 14 }}>
              <span style={{ color: 'var(--ink-2)' }}>{PROGRAM_NAME}</span>
              <span style={{ fontVariantNumeric: 'tabular-nums' }}>{PRICE}.00</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--muted)' }}>
              <span>Sent to jordan.reyes@gmail.com</span>
              <span style={{ fontFamily: 'var(--font-mono)' }}>#KIN-4291</span>
            </div>
          </div>

          {/* What's next */}
          <div style={{ marginTop: 28 }}>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10.5,
              letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--muted)', marginBottom: 14,
            }}>What's next</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                'Start with week 1, day 1 — quad set + heel slide',
                'Do the work in order; each week builds on the last',
                'Come back tomorrow for day 2',
              ].map((t, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 999,
                    background: 'var(--bone-2)', color: 'var(--ink-2)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
                    flexShrink: 0, marginTop: 1,
                  }}>{i + 1}</div>
                  <div style={{ fontSize: 14.5, lineHeight: 1.4, color: 'var(--ink-2)' }}>{t}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ flex: 1, minHeight: 24 }}/>

          <button className="btn clay full" style={{ height: 56, fontSize: 16, marginTop: 24 }} onClick={onNext}>
            Start the program
            <IconChevron size={16} stroke={2.4}/>
          </button>
          <div style={{
            textAlign: 'center', fontSize: 12, color: 'var(--muted)',
            marginTop: 12,
          }}>
            We sent your login link to your email
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 03b · Phase selector — where are you in recovery?
// ────────────────────────────────────────────────────────────
const PHASES = [
  { n: 1, title: 'Just had surgery', sub: 'Days 0–14 post-op', week: 1 },
  { n: 2, title: 'Working on motion', sub: 'Weeks 2–6, regaining ROM', week: 2 },
  { n: 3, title: 'Building strength', sub: 'Weeks 6–14, loading the leg', week: 3 },
  { n: 4, title: 'Past rehab, want to stay strong', sub: 'Months 4+, prevent re-injury', week: 3 },
];

function PhaseSelectorScreen({ onNext }) {
  const [sel, setSel] = React.useState(1);
  const chosen = PHASES.find(p => p.n === sel);
  return (
    <div className="app-body" style={{ background: 'var(--bone)' }}>
      <div className="app-scroll" style={{
        paddingTop: 60, paddingBottom: 30,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ flex: 1, padding: '32px 24px 0', display: 'flex', flexDirection: 'column' }}>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 30, lineHeight: 1.05, letterSpacing: '-0.03em',
            margin: '0 0 10px',
          }}>Where are you in recovery?</h1>
          <p style={{
            margin: 0, fontSize: 15, lineHeight: 1.45,
            color: 'var(--muted)', letterSpacing: '-0.005em',
          }}>We'll start you at the right week. You can always change this later.</p>

          <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {PHASES.map(p => {
              const active = p.n === sel;
              return (
                <button key={p.n} onClick={() => setSel(p.n)} style={{
                  textAlign: 'left', padding: '16px 16px', cursor: 'pointer',
                  background: active ? 'var(--bone-card)' : 'transparent',
                  border: active ? '1.5px solid var(--clay)' : '0.5px solid var(--line)',
                  borderRadius: 16,
                  display: 'flex', alignItems: 'center', gap: 14,
                }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: 999, flexShrink: 0,
                    background: active ? 'var(--clay)' : 'var(--bone-2)',
                    color: active ? '#fff' : 'var(--ink-2)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 600,
                  }}>{p.n}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontFamily: 'var(--font-display)', fontWeight: 600,
                      fontSize: 15.5, letterSpacing: '-0.01em', lineHeight: 1.2,
                      color: 'var(--ink)',
                    }}>{p.title}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 3 }}>{p.sub}</div>
                  </div>
                </button>
              );
            })}
          </div>

          <div style={{ flex: 1, minHeight: 24 }}/>

          <button className="btn clay full" style={{ height: 56, fontSize: 16, marginTop: 24 }} onClick={() => onNext(chosen.week)}>
            Continue
            <IconChevron size={16} stroke={2.4}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 04 · Member home / program view
// ────────────────────────────────────────────────────────────
const PROGRAM = [
  {
    week: 1, name: 'Wake the quad',
    exercises: [
      { id: 'w1d1', title: 'Quad set + heel slide', dur: '2:04', done: true },
      { id: 'w1d2', title: 'Straight-leg raise', dur: '1:48', done: true },
      { id: 'w1d3', title: 'Calf pump + ankle ABC', dur: '1:32', done: false },
    ],
  },
  {
    week: 2, name: 'Load + control',
    exercises: [
      { id: 'w2d1', title: 'Mini squat to chair', dur: '2:21', done: false },
      { id: 'w2d2', title: 'Step-up · 4 inch box', dur: '2:46', done: false },
      { id: 'w2d3', title: 'Wall sit · isometric', dur: '1:58', done: false },
    ],
  },
  {
    week: 3, name: 'Single-leg strength',
    exercises: [
      { id: 'w3d1', title: 'Split squat · regress', dur: '3:12', done: false },
      { id: 'w3d2', title: 'Single-leg RDL', dur: '2:54', done: false },
      { id: 'w3d3', title: 'Lateral step-down', dur: '2:38', done: false },
    ],
  },
  {
    week: 4, name: 'Stability + return',
    exercises: [
      { id: 'w4d1', title: 'Single-leg balance + reach', dur: '2:12', done: false },
      { id: 'w4d2', title: 'Forward / lateral hop · low', dur: '2:48', done: false },
      { id: 'w4d3', title: 'Movement screen + retest', dur: '4:06', done: false },
    ],
  },
];

function MemberHomeScreen({ completed, onSelectExercise, startWeek = 1 }) {
  const allEx = PROGRAM.flatMap(w => w.exercises);
  const totalDone = allEx.filter(e => completed.has(e.id)).length;
  const total = allEx.length;
  const currentWeek = startWeek;
  const nextEx = allEx.find(e => !completed.has(e.id)) || allEx[allEx.length - 1];
  const nextWk = PROGRAM.find(w => w.exercises.some(e => e.id === nextEx.id));
  const nextDay = nextWk.exercises.findIndex(e => e.id === nextEx.id) + 1;
  const todayEx = nextEx;
  const todayLabel = totalDone > 0 ? 'Pick up where you left off' : 'Today · Thursday';

  return (
    <div className="app-body">
      <div className="app-scroll" style={{ paddingBottom: 30 }}>
        {/* Header */}
        <div style={{ padding: '6px 22px 0' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 8,
          }}>Your program</div>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14 }}>
            <h1 style={{
              fontFamily: 'var(--font-display)', fontWeight: 600,
              fontSize: 32, lineHeight: 1.02, letterSpacing: '-0.03em',
              margin: 0, flex: 1,
            }}>{PROGRAM_NAME}</h1>
            <div className="img-ph" style={{
              width: 40, height: 40, borderRadius: 999, fontSize: 9,
              flexShrink: 0,
            }}>JR</div>
          </div>
          <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 6 }}>
            Week {currentWeek} of 4 · {totalDone} of {total} exercises complete
          </div>
          {/* Progress bar */}
          <div className="prog-bar clay" style={{ marginTop: 14 }}>
            <div style={{ width: `${(totalDone / total) * 100}%` }}/>
          </div>
        </div>

        {/* Today eyebrow */}
        <div style={{ padding: '22px 22px 0' }}>
          <button onClick={() => onSelectExercise(todayEx.id)} style={{
            width: '100%', textAlign: 'left', padding: '14px 16px',
            background: 'var(--bone-card)', border: '0.5px solid var(--line)',
            borderRadius: 16, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10,
                letterSpacing: '0.14em', textTransform: 'uppercase',
                color: 'var(--clay-2)', marginBottom: 4,
              }}>{todayLabel}</div>
              <div style={{
                fontFamily: 'var(--font-display)', fontWeight: 600,
                fontSize: 17, letterSpacing: '-0.01em', lineHeight: 1.2,
                color: 'var(--ink)',
              }}>{todayEx.title}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{todayEx.dur} · 3 sets · 60s rest</div>
            </div>
            <IconChevron size={16} color="var(--muted-2)"/>
          </button>
        </div>

        {/* Week sections */}
        <div style={{ padding: '22px 0 0' }}>
          {PROGRAM.map((wk, i) => (
            <WeekBlock key={i} week={wk} active={wk.week === currentWeek} completed={completed} onSelectExercise={onSelectExercise}/>
          ))}
        </div>
      </div>
    </div>
  );
}

function WeekBlock({ week, active, completed, onSelectExercise }) {
  const done = week.exercises.filter(e => completed.has(e.id)).length;
  return (
    <div style={{ marginBottom: 8 }}>
      {/* Week header */}
      <div style={{
        padding: '0 22px 10px',
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: active ? 'var(--clay-2)' : 'var(--muted-2)',
          }}>Week {week.week}{active ? ' · current' : ''}</div>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 18, letterSpacing: '-0.015em', marginTop: 2,
            color: active ? 'var(--ink)' : 'var(--muted)',
          }}>{week.name}</div>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)' }}>{done}/{week.exercises.length}</div>
      </div>

      {/* Exercise tiles */}
      <div style={{
        padding: '0 22px 18px',
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
      }}>
        {week.exercises.map((ex, i) => (
          <ExerciseTile key={ex.id} ex={ex} done={completed.has(ex.id)} dim={!active} onClick={() => onSelectExercise(ex.id)}/>
        ))}
      </div>
    </div>
  );
}

function ExerciseTile({ ex, done, dim, onClick }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', padding: 0, background: 'transparent', border: 0, cursor: 'pointer',
      opacity: dim ? 0.55 : 1,
    }}>
      <div style={{
        borderRadius: 14, overflow: 'hidden',
        border: '0.5px solid var(--line)',
        background: 'var(--bone-card)',
      }}>
        <div className="video-ph" style={{ height: 88, position: 'relative' }}>
          {!dim && (
            <div className="play" style={{ width: 32, height: 32 }}>
              <IconPlay size={14}/>
            </div>
          )}
          {done && (
            <div style={{
              position: 'absolute', top: 8, right: 8,
              width: 22, height: 22, borderRadius: 999,
              background: 'var(--sage)', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <IconCheck size={12} stroke={3}/>
            </div>
          )}
          <div className="duration" style={{ fontSize: 10 }}>{ex.dur}</div>
        </div>
        <div style={{ padding: '8px 10px 10px' }}>
          <div style={{
            fontSize: 12.5, fontWeight: 500, lineHeight: 1.25,
            letterSpacing: '-0.005em',
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
          }}>{ex.title}</div>
        </div>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// 05 · Single exercise view
// ─────────────────────────────────────────────────────────────
function ExerciseScreen({ exercise, week, onComplete, onBack }) {
  const day = week.exercises.findIndex(e => e.id === exercise.id) + 1;
  return (
    <div className="app-body" style={{ background: 'var(--bone)' }}>
      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
        {/* Video — fullscreen, top */}
        <div className="video-ph" style={{ height: 360, position: 'relative' }}>
          {/* Back button on glass */}
          <button onClick={onBack} style={{
            position: 'absolute', top: 60, left: 16, zIndex: 5,
            width: 36, height: 36, borderRadius: 999,
            background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(10px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', border: 0, cursor: 'pointer', padding: 0,
          }}>
            <IconClose size={18} stroke={2}/>
          </button>
          <div className="play"><IconPlay size={22}/></div>
          {/* Scrubber */}
          <div style={{
            position: 'absolute', bottom: 18, left: 16, right: 16,
            display: 'flex', alignItems: 'center', gap: 10,
            color: 'rgba(255,255,255,0.9)',
            fontFamily: 'var(--font-mono)', fontSize: 11,
          }}>
            <span>0:00</span>
            <div style={{ flex: 1, height: 3, borderRadius: 999, background: 'rgba(255,255,255,0.25)', position: 'relative' }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, bottom: 0,
                width: '12%', background: '#fff', borderRadius: 999,
              }}/>
            </div>
            <span>{exercise.dur}</span>
          </div>
        </div>

        {/* Info */}
        <div style={{ padding: '22px 22px 0' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 8,
          }}>Week {week.week}, day {day} · {PROGRAM_NAME}</div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 28, lineHeight: 1.1, letterSpacing: '-0.025em',
            margin: 0,
          }}>{exercise.title}</h1>
          <p style={{
            margin: '10px 0 0', fontSize: 15, lineHeight: 1.5,
            color: 'var(--ink-2)',
          }}>
            Move slowly through the full range. Quality over quantity — the form is the work.
          </p>
        </div>

        {/* Sets/reps prescription */}
        <div style={{ padding: '22px 22px 0' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 10,
          }}>Prescription</div>
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10,
          }}>
            {[
              { l: 'Sets', v: '3' },
              { l: 'Reps', v: '20' },
              { l: 'Rest', v: '30s' },
            ].map((p, i) => (
              <div key={i} className="card" style={{ padding: '14px 12px', textAlign: 'center' }}>
                <div className="bignum" style={{ fontSize: 26, letterSpacing: '-0.025em' }}>{p.v}</div>
                <div style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10,
                  letterSpacing: '0.1em', textTransform: 'uppercase',
                  color: 'var(--muted)', marginTop: 2,
                }}>{p.l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Cues */}
        <div style={{ padding: '22px 22px 0' }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 10,
          }}>Matt's cues</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              'Stop if you feel sharp pain — dull discomfort is OK',
              'Control the down phase as much as the up',
              'Keep breathing — don\'t hold your breath',
            ].map((c, i) => (
              <div key={i} style={{
                display: 'flex', gap: 12, padding: '12px 14px',
                background: 'var(--bone-card)', borderRadius: 12,
                border: '0.5px solid var(--line)',
              }}>
                <div style={{
                  width: 6, height: 6, borderRadius: 999,
                  background: 'var(--clay)', marginTop: 8, flexShrink: 0,
                }}/>
                <div style={{ fontSize: 14, lineHeight: 1.4, color: 'var(--ink-2)' }}>{c}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Sticky bottom CTA */}
      <div style={{
        padding: '12px 22px 30px',
        background: 'linear-gradient(180deg, rgba(247,244,238,0) 0%, var(--bone) 30%)',
        position: 'relative',
      }}>
        <button className="btn primary full" style={{ height: 56, fontSize: 16 }} onClick={onComplete}>
          <IconCheck size={20} stroke={2.4}/>
          Mark complete
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 06 · Admin / analytics (desktop)
// ─────────────────────────────────────────────────────────────
function AdminView() {
  // Scale-to-fit wrapper so the wide canvas doesn't cram text on narrow screens
  const NATIVE_W = 1240;
  const wrapRef = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const fit = () => {
      const w = wrapRef.current?.offsetWidth || NATIVE_W;
      setScale(Math.min(1, (w - 40) / NATIVE_W));
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  return (
    <div ref={wrapRef} style={{
      width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
      paddingBottom: 40,
    }}>
      <div style={{
        width: NATIVE_W,
        transform: `scale(${scale})`,
        transformOrigin: 'top center',
        marginBottom: scale < 1 ? `calc(-1 * (1 - ${scale}) * 700px)` : 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
      }}>
        <div style={{
          width: '100%',
          background: 'var(--bone)',
          borderRadius: 16,
          boxShadow: '0 28px 60px -20px rgba(0,0,0,0.45), 0 6px 20px -8px rgba(0,0,0,0.25)',
          overflow: 'hidden',
          border: '1px solid rgba(255,255,255,0.08)',
        }}>
          {/* Browser chrome */}
          <div style={{
            height: 36, background: '#1B1814',
            display: 'flex', alignItems: 'center', padding: '0 14px', gap: 8,
          }}>
            <div style={{ display: 'flex', gap: 6 }}>
              <div style={{ width: 11, height: 11, borderRadius: 999, background: '#FF5F57' }}/>
              <div style={{ width: 11, height: 11, borderRadius: 999, background: '#FEBC2E' }}/>
              <div style={{ width: 11, height: 11, borderRadius: 999, background: '#28C840' }}/>
            </div>
            <div style={{
              flex: 1, textAlign: 'center', fontSize: 11,
              fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
              color: 'rgba(255,255,255,0.55)',
            }}>app.builtback.com / admin</div>
          </div>

          <AdminDashboard/>
        </div>
      </div>
    </div>
  );
}

function AdminDashboard() {
  return (
    <div style={{ padding: 32, fontFamily: 'var(--font-body)' }}>
      {/* Top strip */}
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 28 }}>
        <div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 11,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 6,
          }}>{PROGRAM_NAME} · admin</div>
          <div style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 26, letterSpacing: '-0.02em',
          }}>Overview</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {['Last 30d', 'Last 7d', 'All time'].map((t, i) => (
            <button key={t} style={{
              padding: '8px 14px', borderRadius: 8, cursor: 'pointer',
              background: i === 0 ? 'var(--ink)' : 'var(--bone-card)',
              color: i === 0 ? '#fff' : 'var(--ink-2)',
              border: '1px solid ' + (i === 0 ? 'var(--ink)' : 'var(--line)'),
              fontSize: 12.5, fontWeight: 500,
              fontFamily: 'var(--font-body)',
            }}>{t}</button>
          ))}
        </div>
      </div>

      {/* 4 big numbers */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 28 }}>
        <MetricCard
          label="Signups"
          value="16"
          sub="$99 × 16"
          delta="+4 this week"
          deltaColor="sage"
        />
        <MetricCard
          label="Revenue"
          value="$1,584"
          sub="gross · before fees"
          delta="+$396 this week"
          deltaColor="sage"
        />
        <MetricCard
          label="Completion rate"
          value="71%"
          sub="avg videos watched, started"
          delta="vs 75% target"
          deltaColor="amber"
        />
        <MetricCard
          label="Active members"
          value="14"
          sub="watched a video in 7d"
          delta="2 dormant"
          deltaColor="muted"
        />
      </div>

      {/* Two-column lower */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
        {/* Recent signups */}
        <div className="card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10.5,
                letterSpacing: '0.12em', textTransform: 'uppercase',
                color: 'var(--muted)', marginBottom: 4,
              }}>Recent signups</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, letterSpacing: '-0.015em' }}>
                4 in the last 7 days
              </div>
            </div>
            <button style={{
              background: 'transparent', border: 0, color: 'var(--clay)',
              fontSize: 12.5, cursor: 'pointer', fontWeight: 500,
            }}>Export CSV →</button>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {RECENT_SIGNUPS.map((s, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '32px 1fr 120px 120px 80px',
                gap: 14, alignItems: 'center',
                padding: '12px 0',
                borderBottom: i < RECENT_SIGNUPS.length - 1 ? '0.5px solid var(--line)' : 'none',
              }}>
                <div className="img-ph" style={{
                  width: 32, height: 32, borderRadius: 999, fontSize: 10,
                }}>{s.initials}</div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 500, letterSpacing: '-0.005em' }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 1 }}>{s.email}</div>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
                  {s.when}
                </div>
                <div style={{ fontSize: 12 }}>
                  <span style={{ color: 'var(--muted)' }}>Week </span>
                  <span style={{ fontWeight: 600, color: 'var(--ink)' }}>{s.week}</span>
                  <span style={{ color: 'var(--muted)' }}> · {s.progress}</span>
                </div>
                <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', textAlign: 'right', color: 'var(--sage-2)' }}>
                  +$99
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Per-exercise completion mini-chart */}
        <div className="card" style={{ padding: 22 }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: 'var(--muted)', marginBottom: 4,
          }}>Completion by exercise</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, letterSpacing: '-0.015em', marginBottom: 16 }}>
            Where people drop off
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {EXERCISE_COMPLETION.map((e, i) => (
              <div key={i}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 5 }}>
                  <span style={{ color: 'var(--ink-2)' }}>
                    <span style={{
                      fontFamily: 'var(--font-mono)', fontSize: 10,
                      color: 'var(--muted-2)', marginRight: 6,
                    }}>W{e.w}D{e.d}</span>
                    {e.name}
                  </span>
                  <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--muted)' }}>{e.pct}%</span>
                </div>
                <div className="prog-bar" style={{ height: 4 }}>
                  <div style={{
                    width: `${e.pct}%`,
                    background: e.pct >= 70 ? 'var(--sage)' : e.pct >= 50 ? 'var(--amber)' : 'var(--clay)',
                  }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function MetricCard({ label, value, sub, delta, deltaColor }) {
  const colors = {
    sage: 'var(--sage-2)',
    amber: '#8B5E1A',
    muted: 'var(--muted)',
  };
  return (
    <div className="card" style={{ padding: 22 }}>
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 10.5,
        letterSpacing: '0.12em', textTransform: 'uppercase',
        color: 'var(--muted)', marginBottom: 10,
      }}>{label}</div>
      <div className="bignum" style={{
        fontSize: 44, letterSpacing: '-0.035em', lineHeight: 1, color: 'var(--ink)',
      }}>{value}</div>
      <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6, letterSpacing: '-0.005em' }}>
        {sub}
      </div>
      <div style={{
        fontSize: 12, color: colors[deltaColor] || 'var(--muted)',
        marginTop: 10, fontWeight: 500,
      }}>{delta}</div>
    </div>
  );
}

const RECENT_SIGNUPS = [
  { initials: 'JR', name: 'Jordan Reyes', email: 'jordan.reyes@gmail.com', when: '3h ago', week: 1, progress: '0 / 3' },
  { initials: 'SK', name: 'Sara Kostas', email: 'skostas@yahoo.com', when: 'yesterday', week: 1, progress: '2 / 3' },
  { initials: 'DT', name: 'Diego Torres', email: 'dieg.t@icloud.com', when: '2 days', week: 1, progress: '3 / 3' },
  { initials: 'AM', name: 'Aisha Mahmoud', email: 'aishaprm@gmail.com', when: '3 days', week: 2, progress: '5 / 6' },
  { initials: 'LO', name: 'Lila Ortiz', email: 'lila.ortiz@hotmail.com', when: '4 days', week: 2, progress: '4 / 6' },
  { initials: 'MC', name: 'Marcus Chen', email: 'm.chen.fit@gmail.com', when: '5 days', week: 2, progress: '6 / 6' },
];

const EXERCISE_COMPLETION = [
  { w: 1, d: 1, name: 'Quad set + heel slide', pct: 94 },
  { w: 1, d: 2, name: 'Straight-leg raise', pct: 88 },
  { w: 1, d: 3, name: 'Calf pump + ankle ABC', pct: 82 },
  { w: 2, d: 1, name: 'Mini squat to chair', pct: 76 },
  { w: 2, d: 2, name: 'Step-up · 4 inch box', pct: 68 },
  { w: 2, d: 3, name: 'Wall sit · isometric', pct: 61 },
  { w: 3, d: 1, name: 'Split squat · regress', pct: 49 },
  { w: 3, d: 2, name: 'Single-leg RDL', pct: 42 },
  { w: 3, d: 3, name: 'Lateral step-down', pct: 38 },
  { w: 4, d: 1, name: 'Single-leg balance + reach', pct: 28 },
  { w: 4, d: 2, name: 'Forward / lateral hop · low', pct: 21 },
  { w: 4, d: 3, name: 'Movement screen + retest', pct: 16 },
];

// ─────────────────────────────────────────────────────────────
// Canvas wrapper
// ─────────────────────────────────────────────────────────────
function ViewToggle({ view, onChange }) {
  const opts = [
    { id: 'flow', label: 'Interactive' },
    { id: 'all',  label: 'All screens' },
  ];
  return (
    <div style={{
      display: 'inline-flex', padding: 3, borderRadius: 999,
      background: 'rgba(255,255,255,0.08)',
      border: '0.5px solid rgba(255,255,255,0.12)',
      fontFamily: 'var(--font-mono)', fontSize: 11,
      letterSpacing: '0.06em', textTransform: 'uppercase',
    }}>
      {opts.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          padding: '7px 14px', borderRadius: 999, border: 0,
          background: view === o.id ? '#fff' : 'transparent',
          color: view === o.id ? '#1a1a1a' : 'rgba(255,255,255,0.6)',
          cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit',
          letterSpacing: 'inherit', textTransform: 'inherit',
          transition: 'all 120ms ease',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

function PilotCanvas() {
  const isPrint = typeof window !== 'undefined' && window.__BB_PRINT__;
  const [view, setView] = React.useState(isPrint ? 'all' : 'flow');
  const [screen, setScreen] = React.useState('landing');
  const [completed, setCompleted] = React.useState(() => new Set(['w1d1', 'w1d2']));
  const [selectedExId, setSelectedExId] = React.useState('w1d3');
  const [startWeek, setStartWeek] = React.useState(1);

  const allEx = PROGRAM.flatMap(w => w.exercises);
  const selectedEx = allEx.find(e => e.id === selectedExId) || allEx[0];
  const selectedWk = PROGRAM.find(w => w.exercises.some(e => e.id === selectedExId)) || PROGRAM[0];

  const goExercise = (id) => { setSelectedExId(id); setScreen('exercise'); };
  const markComplete = () => {
    setCompleted(prev => new Set([...prev, selectedExId]));
    setScreen('home');
  };

  const screenEl = (() => {
    switch (screen) {
      case 'landing':  return <LandingScreen onNext={() => setScreen('checkout')}/>;
      case 'checkout': return <CheckoutScreen onNext={() => setScreen('confirm')} onBack={() => setScreen('landing')}/>;
      case 'confirm':  return <ConfirmationScreen onNext={() => setScreen('phase')}/>;
      case 'phase':    return <PhaseSelectorScreen onNext={(w) => { setStartWeek(w); setScreen('home'); }}/>;
      case 'home':     return <MemberHomeScreen completed={completed} onSelectExercise={goExercise} startWeek={startWeek}/>;
      case 'exercise': return <ExerciseScreen exercise={selectedEx} week={selectedWk} onComplete={markComplete} onBack={() => setScreen('home')}/>;
      default: return null;
    }
  })();

  const noop = () => {};
  const snapshotCompleted = new Set(['w1d1', 'w1d2']);
  const snapshotEx = allEx.find(e => e.id === 'w1d3');
  const snapshotWk = PROGRAM.find(w => w.exercises.some(e => e.id === 'w1d3'));

  return (
    <div className="app-canvas">
      <div className="canvas-header" style={{
        maxWidth: 1320, width: '100%',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div className="meta">Built Back · Mockups</div>
        <ViewToggle view={view} onChange={setView}/>
      </div>

      {view === 'flow' ? (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <IOSDevice width={390} height={844}>
            {screenEl}
          </IOSDevice>
        </div>
      ) : (
        <div className="screens-row">
          <IOSDevice width={390} height={844}>
            <LandingScreen onNext={noop}/>
          </IOSDevice>
          <IOSDevice width={390} height={844}>
            <CheckoutScreen onNext={noop} onBack={noop}/>
          </IOSDevice>
          <IOSDevice width={390} height={844}>
            <ConfirmationScreen onNext={noop}/>
          </IOSDevice>
          <IOSDevice width={390} height={844}>
            <PhaseSelectorScreen onNext={noop}/>
          </IOSDevice>
          <IOSDevice width={390} height={844}>
            <MemberHomeScreen completed={snapshotCompleted} onSelectExercise={noop}/>
          </IOSDevice>
          <IOSDevice width={390} height={844}>
            <ExerciseScreen exercise={snapshotEx} week={snapshotWk} onComplete={noop} onBack={noop}/>
          </IOSDevice>
        </div>
      )}

      <div style={{ width: '100%', maxWidth: 1320, marginTop: 32 }}>
        <AdminView/>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<PilotCanvas/>);
