const { Icon } = window.PryzeDesignSystem_b2bad9;
const { USER, COMPANIES, REWARDS, AMOUNT_PRESETS, PTS_PER_DOLLAR, POINTS_PER_SHIFT } = window.PryzeData;

const STORES = [
  { id: 's1', name: 'Store #1', area: 'Midtown', meta: '12 on the roster · 0.8 mi' },
  { id: 's4', name: 'Store #4', area: 'Riverside', meta: '9 on the roster · 2.4 mi' },
  { id: 's12', name: 'Store #12', area: 'Airport Rd', meta: '17 on the roster · 6.1 mi' },
  { id: 's27', name: 'Store #27', area: 'Westgate', meta: '11 on the roster · 7.9 mi' },
];
const STATUSES = ["Chasing this month's goal 🎯", 'Locked in and grinding 🔥', 'Here for the free food 🍕', 'Saving for something big 💭', 'New here — say hi 👋'];
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const MONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const DOW = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
const YEARS = Array.from({ length: 44 }, (_, i) => 2010 - i);
const BASE_BONUS = 250;
const STEP_PTS = [50, 50, 75, 75];

const STEPS = [
  { kicker: 'One last thing', head: 'Where do\nyou clock in?', sub: 'Quick setup — then straight to earning.' },
  { kicker: 'Make it yours', head: 'Set up\nyour profile', sub: 'A photo, a status your crew sees, and a birthday we drop a reward on.' },
  { kicker: 'The fun part', head: 'What are you\nchasing first?', sub: 'Pick one reward to aim at — we turn it into a points target you can actually hit.' },
  { kicker: 'All set', head: 'Your\naction plan', sub: 'Exactly how you get there — points, shifts and weeks.' },
];

const SURVEY = [
  { kind: 'tiles', kicker: 'Beat 1 of 4', q: 'What actually gets you moving?', hint: 'Tap the one that hits most', multi: false, pts: 60,
    opts: [['Cash in hand', '💸'], ['Beating my record', '📈'], ['Crew shout-outs', '📣'], ['Free food', '🍕'], ['Top of the board', '🏆'], ['Time back', '🕒']],
    read: p => `${p[0]} it is. That's what we'll pay you in.` },
  { kind: 'tiles', kicker: 'Beat 2 of 4', q: 'What are you stacking for?', hint: 'Pick the one that matters most', multi: false, pts: 60,
    opts: [['Rent + bills', '🏠'], ['A trip', '✈️'], ['Something I want', '🎧'], ['School', '🎓'], ['Just stacking', '🪙']],
    read: p => `${p[0]}. Every point now has a job.` },
  { kind: 'time', kicker: 'Beat 3 of 4', q: 'When do you go hardest?', hint: 'Tap your block', multi: false, pts: 65,
    opts: [['Opening', '🌅'], ['Mid-day rush', '☀️'], ['Closing', '🌙'], ['Weekends', '🎉']],
    read: p => `${p[0]} energy. We'll drop your goals there.` },
  { kind: 'nudge', kicker: 'Last beat', q: 'How should we tap you on the shoulder?', hint: 'This is how we’ll show up', multi: false, pts: 65,
    opts: [['Daily check-in', '🔔'], ['Only when close', '🎯'], ['Weekly recap', '📊'], ['Keep it quiet', '🤫']],
    read: p => `${p[0]}. Locked.` },
];
const NUDGE_PREVIEW = {
  'Daily check-in': 'Morning. 3 goals live today — first one banks 40 pts.',
  'Only when close': 'You are 60 pts off Chick-fil-A. One shift does it.',
  'Weekly recap': 'Your week: 480 pts, 6-day streak, #3 in store.',
  'Keep it quiet': 'We will stay out of your way. Open the app whenever.',
};

function recommendedFor(r) {
  if (r.pinned > 900) return 25;
  if (r.pinned > 300) return 15;
  return 10;
}
const fmtDate = b => `${MONTHS[b.m]} ${b.d}, ${b.y}`;

const ROW = 42;

function Wheel({ items, index, onIndex, wide }) {
  const ref = React.useRef(null);
  const settle = React.useRef(null);
  React.useEffect(() => {
    if (ref.current) ref.current.scrollTop = index * ROW;
  }, []);
  const onScroll = () => {
    clearTimeout(settle.current);
    settle.current = setTimeout(() => {
      const el = ref.current;
      if (!el) return;
      const i = Math.max(0, Math.min(items.length - 1, Math.round(el.scrollTop / ROW)));
      el.scrollTo({ top: i * ROW, behavior: 'smooth' });
      if (i !== index) onIndex(i);
    }, 90);
  };
  return (
    <div className={'wh' + (wide ? ' wh-wide' : '')}>
      <div className="wh-scroll" ref={ref} onScroll={onScroll}>
        <span className="wh-pad" />
        {items.map((it, i) => (
          <button key={it} className={'wh-item' + (i === index ? ' is-on' : '')} onClick={() => { onIndex(i); ref.current.scrollTo({ top: i * ROW, behavior: 'smooth' }); }}>{it}</button>
        ))}
        <span className="wh-pad" />
      </div>
    </div>
  );
}

function CalendarSheet({ value, onPick, onClose }) {
  const [m, setM] = React.useState(value.m);
  const [d, setD] = React.useState(value.d);
  const [y, setY] = React.useState(value.y);
  const days = new Date(y, m + 1, 0).getDate();
  const dd = Math.min(d, days);
  React.useEffect(() => { onPick({ m, d: dd, y }); }, [m, dd, y]);
  return (
    <div className="onb-sheet-wrap" onClick={onClose}>
      <div className="onb-sheet cal-sheet" onClick={e => e.stopPropagation()}>
        <span className="onb-sheet-grip" />
        <p className="cal-title">Your birthday</p>
        <p className="cal-sub">Spin to set the day we spoil you on.</p>
        <div className="wh-set">
          <span className="wh-band" />
          <Wheel wide items={MONTHS} index={m} onIndex={setM} />
          <Wheel items={Array.from({ length: days }, (_, i) => String(i + 1))} index={dd - 1} onIndex={i => setD(i + 1)} />
          <Wheel items={YEARS.map(String)} index={Math.max(0, YEARS.indexOf(y))} onIndex={i => setY(YEARS[i])} />
        </div>
        <button className="auth-btn auth-btn-p" onClick={onClose}>{fmtDate({ m, d: dd, y })}</button>
      </div>
    </div>
  );
}

function OnbStatusSheet({ current, onSelect, onClose }) {
  const [pick, setPick] = React.useState(current);
  const [own, setOwn] = React.useState(STATUSES.includes(current) ? '' : current);
  const value = own.trim() || pick;
  return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Your status</p>
        <p className="pf-sheet-body">Everyone in your store sees this.</p>
        <div className="pf-status-grid">
          {STATUSES.map(s => (
            <button key={s} className={'pf-status-chip' + (s === value ? ' is-on' : '')} onClick={() => { setOwn(''); setPick(s); }}>{s}</button>
          ))}
        </div>
        <input className="pf-status-own" value={own} onChange={e => setOwn(e.target.value)} maxLength={48} placeholder="Or write your own…" />
        <button className="pf-status-save" disabled={!value} onClick={() => onSelect(value)}>Save status</button>
      </div>
    </div>
  );
}

function AmountSheet({ reward, value, onPick, onClose }) {
  const rec = recommendedFor(reward);
  return (
    <div className="onb-sheet-wrap" onClick={onClose}>
      <div className="onb-sheet" onClick={e => e.stopPropagation()}>
        <span className="onb-sheet-grip" />
        <div className="onb2-sheet-head">
          <span className="onb2-sheet-logo" style={{ background: reward.logo ? '#fff' : reward.bg }}>{reward.logo ? <img src={reward.logo} alt="" /> : <b>{reward.initials}</b>}</span>
          <div><p className="onb2-sheet-kicker">Set your target</p><h3>{reward.title}</h3></div>
        </div>
        <div className="onb2-sheet-val">
          <span className="onb2-money"><i>$</i>{value}</span>
          <span className="onb2-money-pts">{(value * PTS_PER_DOLLAR).toLocaleString()} pts to earn</span>
        </div>
        <div className="onb-amt-chips">
          {AMOUNT_PRESETS.map(a => (
            <button key={a} className={'onb-amt-chip' + (a === value ? ' is-on' : '')} onClick={() => onPick(a)}>${a}{a === rec && <em>Rec</em>}</button>
          ))}
        </div>
        <button className="auth-btn auth-btn-p" onClick={onClose}>{`Lock in $${value}`}</button>
      </div>
    </div>
  );
}

function BonusChoiceSheet({ base, onDouble, onSkip, onClose }) {
  return (
    <div className="onb-sheet-wrap" onClick={onClose}>
      <div className="onb-sheet" onClick={e => e.stopPropagation()}>
        <span className="onb-sheet-grip" />
        <p className="pd-head">💰 {base} pts are yours. Want {base * 2}?</p>
        <p className="pd-sub">Four quick beats about what motivates you — 30 seconds, and it doubles the bonus you start with.</p>
        <button className="auth-btn auth-btn-p" onClick={onDouble}>Double it — {base * 2} pts</button>
        <button className="pd-skip" onClick={onSkip}>Skip and finish with {base} pts</button>
      </div>
    </div>
  );
}

function BonusSurvey({ onDone, onSkip, onBack }) {
  const [i, setI] = React.useState(0);
  const [ans, setAns] = React.useState({});
  const [earned, setEarned] = React.useState(0);
  const [fly, setFly] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const b = SURVEY[i];
  const cur = ans[i] || [];

  React.useEffect(() => { if (!fly) return; const t = setTimeout(() => setFly(null), 1000); return () => clearTimeout(t); }, [fly]);

  const commit = () => {
    if (busy) return;
    setBusy(true);
    const picks = ans[i] || [];
    setFly({ pts: b.pts, line: b.read(picks), k: Date.now() });
    setEarned(e => e + b.pts);
    setTimeout(() => {
      setBusy(false);
      if (i === SURVEY.length - 1) onDone(ans);
      else setI(i + 1);
    }, 850);
  };

  const pick = label => {
    if (busy) return;
    if (!b.multi) { setAns(a => ({ ...a, [i]: [label] })); setTimeout(commit, 200); return; }
    setAns(a => {
      const c = a[i] || [];
      return { ...a, [i]: c.includes(label) ? c.filter(x => x !== label) : [...c, label] };
    });
  };

  return (
    <div className="auth-screen bn">
      {fly && (
        <span className="bn-flash" key={fly.k}>
          <b>+{fly.pts}</b>
          <em>{fly.line}</em>
        </span>
      )}
      <div className="auth-body bn-body">
        <div className="auth-nav onb-nav wb-nav">
          <button className="onb-back" onClick={() => i === 0 ? onBack() : setI(i - 1)}><Icon name="arrow-left" weight="bold" size={17} color="var(--fg-primary)" /></button>
          <span className="wb-line">
            <b>2× bonus · {i + 1} of {SURVEY.length}</b>
            <i><em style={{ width: Math.round(earned / BASE_BONUS * 100) + '%' }} /></i>
            <s>💰 {(BASE_BONUS + earned).toLocaleString()}</s>
          </span>
        </div>
        <div className="bn-slide" key={i}>
          <h1 className="onb2-survey-q">{b.q}</h1>
          <p className="onb2-survey-hint">{b.hint}</p>

          {b.kind === 'tiles' && (
            <div className="bn-tiles">
              {b.opts.map(([label, emoji], n) => (
                <button key={label} className={'bn-tile' + (cur.includes(label) ? ' is-on' : '')} style={{ animationDelay: n * 50 + 'ms' }} onClick={() => pick(label)}>
                  <em>{emoji}</em><b>{label}</b>
                </button>
              ))}
            </div>
          )}

          {b.kind === 'time' && (
            <div className="bn-clock">
              {b.opts.map(([label, emoji], n) => (
                <button key={label} className={'bn-block' + (cur.includes(label) ? ' is-on' : '')} style={{ animationDelay: n * 50 + 'ms' }} onClick={() => pick(label)}>
                  <em>{emoji}</em>
                  <b>{label}</b>
                  <small>{['5a – 10a', '10a – 3p', '5p – close', 'Sat + Sun'][n]}</small>
                </button>
              ))}
            </div>
          )}

          {b.kind === 'nudge' && (
            <div className="bn-nudges">
              {b.opts.map(([label, emoji], n) => (
                <button key={label} className={'bn-push' + (cur.includes(label) ? ' is-on' : '')} style={{ animationDelay: n * 50 + 'ms' }} onClick={() => pick(label)}>
                  <span className="bn-push-top"><i>{emoji}</i>Pryze<small>now</small></span>
                  <span className="bn-push-body">{NUDGE_PREVIEW[label]}</span>
                  <span className="bn-push-tag">{label}</span>
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="auth-grow" />
        {b.multi && <button className={'auth-btn ' + (cur.length ? 'auth-btn-p' : 'auth-btn-off')} disabled={!cur.length} onClick={commit}>{cur.length ? `Bank +${b.pts} pts` : 'Pick at least one'}</button>}
        {i === 0 && <button className="bn-skip" onClick={onSkip}>Skip the bonus round</button>}
      </div>
    </div>
  );
}

function BonusModal({ points, onClose, company, photo, name }) {
  const co = company || COMPANIES[USER.company];
  const pic = photo || USER.photo;
  const who = name || USER.name;
  const doubled = points > BASE_BONUS;
  React.useEffect(() => { const t = setTimeout(onClose, 3000); return () => clearTimeout(t); }, []);
  return (
    <div className="onb-celebrate">
      <span className="onb-cel-rays" />
      <button className="onb-cel-x" onClick={onClose} aria-label="Close"><Icon name="x" weight="bold" size={17} color="#fff" /></button>
      <span className="onb-cel-pop" />
      {Array.from({ length: 70 }).map((_, i) => (
        <span key={i} className={'onb-conf' + (i % 3 === 0 ? ' onb-conf-r' : '')} style={{ left: (i * 1.43 + 1) % 100 + '%', background: ['#fff', '#C9FF3D', '#FFD23D', '#FF9F6B', '#8FE3FF'][i % 5], animationDelay: (i % 14) * 90 + 'ms', animationDuration: (1.2 + (i % 5) * .38) + 's' }} />
      ))}
      {['🎉', '✨', '🔥', '⭐', '💥', '🎊', '🥳', '💫', '🙌'].map((e, i) => (
        <span key={e} className="onb-cel-burst" style={{ left: (6 + i * 10.5) + '%', animationDelay: (i % 6) * 190 + 'ms', fontSize: 22 + (i % 3) * 9 }}>{e}</span>
      ))}
      <div className="onb-cel-body">
        <div className="onb-cel-orbit">
          <span className="onb-cel-orbit-ring" />
          <span className="onb-cel-orbit-item oo1"><span className="onb-cel-orbit-item-in"><img src="../assets/pryzey.svg" alt="" /></span></span>
          <span className="onb-cel-orbit-item oo2"><span className="onb-cel-orbit-item-in">{pic ? <img src={pic} alt="" /> : <b>{who.split(' ').map(n => n[0]).join('').slice(0, 2)}</b>}</span></span>
          <span className="onb-cel-orbit-item oo3"><span className="onb-cel-orbit-item-in">{co && co.logo ? <img src={co.logo} alt="" /> : <b>{(co && co.initials) || 'P'}</b>}</span></span>
        </div>
        <p className="onb-cel-kicker">🎉 {doubled ? 'Double bonus unlocked' : 'You did it'}</p>
        <h1 className="onb-cel-h1">{'Hurray!'.split('').map((c, i) => <span key={i} style={{ animationDelay: (240 + i * 65) + 'ms' }}>{c}</span>)}</h1>
        <div className="onb-cel-pts"><i>+</i>{points.toLocaleString()}<em>pts</em></div>
        <p className="onb-cel-sub">{doubled ? 'You crushed the bonus round — your starting bonus just doubled. Huge head start on target one!' : 'Bonus banked and you are officially ready to earn. Let\'s go!'}</p>
      </div>
      <p className="onb-cel-auto">Heading to your home screen…</p>
    </div>
  );
}

function OnboardingFlow({ onDone }) {
  const [step, setStep] = React.useState(0);
  const [stores, setStores] = React.useState(['s1']);
  const [status, setStatus] = React.useState(STATUSES[0]);
  const [statusSheet, setStatusSheet] = React.useState(false);
  const [photo, setPhoto] = React.useState(USER.photo || null);
  const [bday, setBday] = React.useState({ m: 4, d: 12, y: 2001 });
  const [cal, setCal] = React.useState(false);
  const [pickId, setPickId] = React.useState(null);
  const [amounts, setAmounts] = React.useState({});
  const [sheet, setSheet] = React.useState(null);
  const [phase, setPhase] = React.useState('core');
  const [bonusSheet, setBonusSheet] = React.useState(false);
  const [survey, setSurvey] = React.useState(null);
  const [rQuery, setRQuery] = React.useState('');
  const [rVisible, setRVisible] = React.useState(12);
  const [flash, setFlash] = React.useState(null);
  const fileRef = React.useRef(null);
  const company = COMPANIES[USER.company];
  const target = REWARDS.find(r => r.id === pickId) || null;
  const rFiltered = React.useMemo(() => {
    const q = rQuery.trim().toLowerCase();
    return q ? REWARDS.filter(r => r.title.toLowerCase().includes(q)) : REWARDS.slice().sort((a, b) => (b.pinned || 0) - (a.pinned || 0));
  }, [rQuery]);
  const rShown = rFiltered.slice(0, rVisible);
  const rMore = rFiltered.length - rShown.length;
  const amountFor = r => amounts[r.id] || recommendedFor(r);
  const dollars = target ? amountFor(target) : 0;
  const totalPoints = dollars * PTS_PER_DOLLAR;
  const shifts = Math.max(1, Math.ceil(totalPoints / POINTS_PER_SHIFT));
  const weeks = Math.max(1, Math.ceil(shifts / 4));
  const milestones = [
    { pct: .33, label: 'Warm up' },
    { pct: .66, label: 'Keep it going' },
    { pct: 1, label: `Cash out for ${target ? target.title : 'your reward'}` },
  ].map(m => { const pts = Math.max(1, Math.round(totalPoints * m.pct)); return { ...m, pts, wk: Math.max(1, Math.ceil(pts / POINTS_PER_SHIFT / 4)) }; });
  const streak = Math.min(30, Math.max(5, Math.round(shifts * 0.6)));
  const bonus = survey ? BASE_BONUS * 2 : BASE_BONUS;
  const banked = STEP_PTS.slice(0, step).reduce((s, p) => s + p, 0);
  const s = STEPS[step];
  const firstStore = STORES.find(x => x.id === stores[0]) || STORES[0];
  const toggleStore = id => setStores(v => v.includes(id) ? v.filter(x => x !== id) : [...v, id]);

  React.useEffect(() => { if (!flash) return; const t = setTimeout(() => setFlash(null), 1400); return () => clearTimeout(t); }, [flash]);

  function onFile(e) {
    const f = e.target.files && e.target.files[0];
    if (f) setPhoto(URL.createObjectURL(f));
  }
  const choose = r => { setPickId(r.id); setAmounts(m => ({ ...m, [r.id]: m[r.id] || recommendedFor(r) })); setSheet(r); };
  function finish() {
    onDone({ store: firstStore.name + ' · ' + firstStore.area, stores, status, photo, bday, picks: pickId ? { [pickId]: true } : {}, amounts, survey, bonusPoints: bonus, plan: { totalPoints, shifts, weeks, streak } });
  }
  const next = () => { setFlash('+' + STEP_PTS[step] + ' pts · ' + Date.now()); setStep(x => x + 1); };

  if (phase === 'survey') return <BonusSurvey onDone={a => { setSurvey(a); setPhase('reward'); }} onSkip={() => setPhase('reward')} onBack={() => setPhase('core')} />;
  if (phase === 'reward') return <BonusModal points={bonus} onClose={finish} company={company} photo={photo} name={USER.name} />;

  return (
    <div className="auth-screen onb2">
      {flash && <span className="onb-bag" key={flash}>💰<em>{flash.split(' · ')[0]}</em></span>}
      <div className="auth-step" key={step}>
        <div className="auth-body onb2-body">
          <div className="auth-nav onb-nav wb-nav">
            <button className={'onb-back' + (step === 0 ? ' is-off' : '')} disabled={step === 0} onClick={() => setStep(x => x - 1)}><Icon name="arrow-left" weight="bold" size={17} color="var(--fg-primary)" /></button>
            <span className="wb-line">
              <b>Step {step + 1} of 4</b>
              <i><em style={{ width: Math.round(banked / BASE_BONUS * 100) + '%' }} /></i>
              <s>💰 {banked}/{BASE_BONUS}</s>
            </span>
          </div>
          {step !== 0 && (<React.Fragment><p className="onb2-kicker">{s.kicker}</p><h1 className="onb2-h1">{s.head}</h1><p className="onb2-sub">{s.sub}</p></React.Fragment>)}

          {step === 0 && (
            <React.Fragment>
              <p className="onb2-kicker">One last thing</p>
              <h1 className="onb2-h1">Which stores
do you work at?</h1>
              <p className="onb2-sub">A few quick answers so we can shape your goals and rewards around how you actually work.</p>
              <div className="onb2-locked">
                {company && company.logo ? <img src={company.logo} alt="" /> : <span className="onb-locked-fb">{(company && company.initials) || 'S'}</span>}
                <div><s>{(company && company.name) || 'Your company'}</s><small>Locked from your code</small></div>
                <Icon name="lock-simple" weight="fill" size={14} color="var(--fg-muted)" />
              </div>
              <div className="onb2-list">
                {STORES.map(x => {
                  const on = stores.includes(x.id);
                  return (
                    <button key={x.id} className={'st-row' + (on ? ' is-on' : '')} onClick={() => toggleStore(x.id)}>
                      <span className="st-box">{on && <Icon name="check" weight="bold" size={13} color="#fff" />}</span>
                      <span className="st-txt">
                        <b>{x.name} <i>{x.area}</i></b>
                        <small>{x.meta}</small>
                      </span>
                    </button>
                  );
                })}
              </div>
              <div className="auth-grow" />
              <button className={'auth-btn ' + (stores.length ? 'auth-btn-p' : 'auth-btn-off')} disabled={!stores.length} onClick={next}>{stores.length > 1 ? `Continue with ${stores.length} stores` : 'Continue with 1 store'}</button>
            </React.Fragment>
          )}

          {step === 1 && (
            <React.Fragment>
              <div className="onb2-idcard">
                <button className="onb-photo" onClick={() => fileRef.current && fileRef.current.click()}>
                  {photo ? <img src={photo} alt="" /> : <span className="onb-photo-fb">{USER.name.split(' ').map(n => n[0]).join('').slice(0, 2)}</span>}
                  <span className="onb-photo-btn"><Icon name="camera" weight="fill" size={14} color="#fff" /></span>
                </button>
                <div><b>{USER.name}</b><small>{photo ? 'Looking good' : 'Tap to add a photo'}</small></div>
              </div>
              <p className="onb2-lbl">Status</p>
              <button className="onb2-field" onClick={() => setStatusSheet(true)}>
                <span>{status}</span>
                <Icon name="pencil-simple" weight="bold" size={15} color="var(--fg-muted)" />
              </button>
              <p className="onb2-lbl">Birthday</p>
              <button className="onb2-field" onClick={() => setCal(true)}>
                <span>{fmtDate(bday)}</span>
                <Icon name="calendar-blank" weight="bold" size={17} color="var(--color-primary)" />
              </button>
              <p className="onb2-hint">Sign up for Birthday Rewards by sharing your birthday. We don't use it for anything else, and it never shows to others.</p>
              <div className="auth-grow" />
              <button className="auth-btn auth-btn-p" onClick={next}>Continue</button>
              <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onFile} />
            </React.Fragment>
          )}

          {step === 2 && (
            <React.Fragment>
              <div className="onb2-search">
                <Icon name="magnifying-glass" weight="bold" size={15} color="var(--fg-muted)" />
                <input value={rQuery} onChange={e => { setRQuery(e.target.value); setRVisible(12); }} placeholder="Search 100+ rewards" />
              </div>
              {!rQuery && <p className="onb2-poplabel">Popular picks</p>}
              {rFiltered.length === 0 ? (
                <p className="onb2-noresults">No rewards match "{rQuery}".</p>
              ) : (
                <div className="onb-grid onb2-grid">
                  {rShown.map(r => {
                    const on = pickId === r.id;
                    return (
                      <button key={r.id} className={'onb-card onb2-card' + (on ? ' is-on' : '')} onClick={() => choose(r)}>
                        <span className="onb-card-logo" style={{ background: r.logo ? '#fff' : r.bg }}>
                          {r.logo ? <img src={r.logo} alt="" /> : <b>{r.initials}</b>}
                        </span>
                        <span className="onb-card-name">{r.title}</span>
                        {on && <span className="onb-card-amt">{`$${amountFor(r)}`}</span>}
                        {on && <span className="onb-card-tick"><Icon name="check" weight="bold" size={11} color="#fff" /></span>}
                      </button>
                    );
                  })}
                </div>
              )}
              {rMore > 0 && <button className="onb2-loadmore" onClick={() => setRVisible(v => v + 12)}>Show {Math.min(12, rMore)} more &middot; {rMore} left</button>}
              <div className="auth-grow" />
              <div className="onb2-dock">
                {target && <button className="onb2-retarget" onClick={() => setSheet(target)}>{`${target.title} · $${dollars} · ${totalPoints.toLocaleString()} pts`}<Icon name="pencil-simple" weight="bold" size={13} color="var(--fg-muted)" /></button>}
                <button className={'auth-btn ' + (target ? 'auth-btn-p' : 'auth-btn-off')} disabled={!target} onClick={next}>{target ? 'Build my plan' : 'Pick your target'}</button>
              </div>
            </React.Fragment>
          )}

          {step === 3 && target && (
            <React.Fragment>
              <div className="pl-hero">
                <span className="pl-logo" style={{ background: target.logo ? '#fff' : target.bg }}>{target.logo ? <img src={target.logo} alt="" /> : <b>{target.initials}</b>}</span>
                <div className="pl-hero-txt">
                  <b>{target.title} · ${dollars}</b>
                  <em>{totalPoints.toLocaleString()} points to earn</em>
                </div>
              </div>

              <div className="tk-ticket">
                <p className="tk-kicker">Your action plan</p>
                {milestones.map((m, i) => (
                  <div className="tk-row" key={i}>
                    <span className="tk-num">{i + 1}</span>
                    <span className="tk-txt"><b>{m.label}</b><small>Earn {m.pts.toLocaleString()} pts</small></span>
                    <span className="tk-wk">{m.wk}<i>wk</i></span>
                  </div>
                ))}
                <div className="tk-perf" />
                <div className="tk-total"><span>Total to cash out</span><b>{totalPoints.toLocaleString()} pts · {weeks}w</b></div>
              </div>

              <p className="pl-note">Mostly from your daily goals — three checkpoints on the way to {target.title}.</p>

              <div className="auth-grow" />
              <div className="onb2-dock">
                <button className="auth-btn auth-btn-p" onClick={() => setBonusSheet(true)}>Claim your welcome bonus</button>
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
      {bonusSheet && <BonusChoiceSheet base={BASE_BONUS} onDouble={() => { setBonusSheet(false); setPhase('survey'); }} onSkip={() => { setBonusSheet(false); setPhase('reward'); }} onClose={() => setBonusSheet(false)} />}
      {sheet && <AmountSheet reward={sheet} value={amountFor(sheet)} onPick={a => setAmounts(m => ({ ...m, [sheet.id]: a }))} onClose={() => setSheet(null)} />}
      {cal && <CalendarSheet value={bday} onPick={setBday} onClose={() => setCal(false)} />}
      {statusSheet && <OnbStatusSheet current={status} onSelect={x => { setStatus(x); setStatusSheet(false); }} onClose={() => setStatusSheet(false)} />}
    </div>
  );
}

window.PryzeOnboarding = { OnboardingFlow, BonusModal };
