/* Reco customer journey screens. Each fills its container: a 402×874 iOS frame on the
   landing page, or the whole viewport on a real phone (window.RECO_REAL = true).
   Every screen takes optional handlers/data so the same markup serves the mockups and the live pages.
   Needs reco-ui.jsx (RecoButton), reco-mascot.jsx and reco-ticket.jsx (VoucherTicket).
   Exports: CouponUnlocked, FriendReferral, CounterStep, Presented,
            AlreadyClaimed, Unavailable */

const SB_TOP = 56;   // status-bar safe area (device mockup)
const HI_BOT = 34;   // home-indicator safe area (device mockup)
const isReal = () => !!window.RECO_REAL;
const SAMPLE_REWARD = 'קפה חינם בביקור הראשון';
const strongGreen = { color: 'var(--reco-green-deep)', fontWeight: 600 };

// ── Shell: white screen, safe-area padding, optional sticky footer
function Screen({ children, bg = '#fff', footer, footerPad = true, style = {} }) {
  const real = isReal();
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column',
                  background: bg, position: 'relative', ['--reco-stage-bg']: bg, ['--reco-page-bg']: bg, ...style }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
                    padding: `${real ? 'calc(env(safe-area-inset-top, 0px) + 18px)' : SB_TOP + 'px'} 24px 0`,
                    overflowY: real ? 'auto' : 'hidden', overflowX: 'hidden' }}>
        {children}
      </div>
      {footer && (
        <div style={{ padding: `12px 24px ${real ? 'calc(env(safe-area-inset-bottom, 0px) + 20px)' : (HI_BOT + (footerPad ? 14 : 6)) + 'px'}`,
                      background: bg, position: 'relative', zIndex: 6 }}>
          {footer}
        </div>
      )}
    </div>
  );
}

// ── Top chrome. Unused: the customer journey no longer shows a header banner. Kept so older call sites still work.
function TopBar({ business, right }) {
  return null;   // the customer journey has no header banner (also in the landing-page mockups)
  return (
    <div style={{ display: 'flex', flexDirection: 'row-reverse', alignItems: 'center', justifyContent: 'space-between', paddingTop: 4 }}>
      <RecoWordmark height={22} />
      {right !== undefined ? right : (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 30,
                       padding: '0 12px', borderRadius: 99, background: 'var(--iv-paper-warm)',
                       border: '1px solid var(--iv-line)', fontSize: 12.5, fontWeight: 500,
                       color: 'var(--iv-ink-soft)', maxWidth: '55%' }}>
          <span style={{ width: 6, height: 6, borderRadius: 99, background: 'var(--reco-green)', flexShrink: 0 }} />
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{business}</span>
        </span>
      )}
    </div>
  );
}

const Title = ({ children }) => (
  <h1 style={{ fontSize: 30, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--reco-navy)', margin: 0, lineHeight: 1.1 }}>{children}</h1>
);
const Sub = ({ children, style }) => (
  <p style={{ fontSize: 16, lineHeight: 1.45, color: 'var(--iv-ink-soft)', margin: '12px 8px 0', maxWidth: 300, ...style }}>{children}</p>
);

// ── Live countdown to a moment in time
function LiveCountdown({ endsAt, label = 'נשאר לממש', icon = true }) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);
  const left = Math.max(0, new Date(endsAt).getTime() - now);
  const d = Math.floor(left / 864e5), h = Math.floor(left / 36e5) % 24, m = Math.floor(left / 6e4) % 60, s = Math.floor(left / 1000) % 60;
  const p = n => String(n).padStart(2, '0');
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 14, color: 'var(--iv-ink-soft)' }}>
      {icon && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>}
      {label && <span>{label}</span>}
      {d > 0 && <span>{d === 1 ? 'יום ו-' : `${d} ימים ו-`}</span>}
      <b dir="ltr" style={{ fontFamily: 'var(--iv-font-mono)', fontWeight: 600, color: 'var(--reco-navy)', fontSize: 14 }}>
        {p(h)}:{p(m)}:{p(s)}
      </b>
    </div>
  );
}

// ════════════════════════════════════════ 3 · COUPON UNLOCKED
function CouponUnlocked({ business = 'קפה הציפור הכחולה', reward = SAMPLE_REWARD, days = 3, tk = {}, sender, placeId, title = 'ה-Reco שלכם מוכן', subtitle, intensity = 'playful', unlocking = false, onShare, onCopy, copied }) {
  const [phase, setPhase] = React.useState(unlocking ? 'wrapped' : 'done');
  React.useEffect(() => {
    if (!unlocking) return;
    const a = setTimeout(() => setPhase('open'), 350);
    const b = setTimeout(() => setPhase('done'), 2100);
    return () => { clearTimeout(a); clearTimeout(b); };
  }, []);
  const shown = phase === 'done';
  const place = useBizPlace({ business, placeId });
  const fade = (delay = 0) => unlocking ? {
    opacity: shown ? 1 : 0, transform: shown ? 'none' : 'translateY(14px)', pointerEvents: shown ? 'auto' : 'none',
    transition: `opacity .6s ease ${delay}s, transform .6s var(--iv-ease-soft) ${delay}s`,
  } : {};
  return (
    <Screen footer={
      <div style={fade(0.35)}>
        <RecoButton onClick={onShare} icon={
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"/></svg>
        }>שתפו עם חבר</RecoButton>
        <RecoButton variant="ghost" style={{ marginTop: 8 }} onClick={onCopy} icon={
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="9" y="9" width="11" height="11" rx="2.5"/><path d="M5 15a2 2 0 01-2-2V5a2 2 0 012-2h8a2 2 0 012 2"/></svg>
        }>{copied ? 'הקישור הועתק' : 'העתקת קישור'}</RecoButton>
      </div>
    }>
      {shown && intensity !== 'subtle' && <Confetti intensity={intensity} soft={sender !== undefined} />}
      {sender === undefined && <div style={fade()}><TopBar business={business} /></div>}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', position: 'relative', zIndex: 6 }}>
        <div style={{ marginBottom: 10, ...fade(0.1) }}>
          <RecoParrot size={68} mood="happy" style={unlocking ? undefined : { animation: 'reco-pop 0.6s var(--iv-ease-soft) both' }} />
        </div>
        <div style={fade(0.15)}><Title>{title}</Title></div>
        <div style={fade(0.2)}>{sender !== undefined
          ? <Sub style={{ fontSize: 14.5 }}>{subtitle || 'שתפו אותו עם חברים ומשפחה - הראשון לממש מרוויח!'}</Sub>
          : <Sub style={{ fontSize: 15.5 }}>שתפו אותו עם חבר. הראשון שיממש אותו מקבל <strong style={strongGreen}>{reward}</strong>.</Sub>}</div>
        {unlocking
          ? <div style={{ marginTop: 22, width: '100%' }}>
              <GiftLocked business={business} open={phase !== 'wrapped'} scale={1} reveal={{ reward, days, tk, from: sender, place }} />
            </div>
          : <VoucherTicket reward={reward} business={business} days={days} {...tk} from={sender} place={place}
                           style={{ marginTop: 22, animation: 'reco-rise 0.7s var(--iv-ease-soft) 0.15s both' }} />}
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ 4 · THE FRIEND OPENS THE LINK (nothing is reserved)
// The pin by the business name on the voucher opens the business on Google Maps.
function useBizPlace({ business, placeId }) {
  return { href: `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(business)}${placeId ? `&query_place_id=${encodeURIComponent(placeId)}` : ''}` };
}

function FriendReferral({ business = 'קפה הציפור הכחולה', friend, reward = SAMPLE_REWARD, days = 3, tk = {}, endsAt, views = 0,
                          placeId, rating, reviewCount, noPhoto, animate = true, onClaim, busy, claimLabel = 'מימוש בקופה', error }) {
  const notYet = tk.startsAt && new Date(tk.startsAt).getTime() > Date.now();
  // the voucher arrives wrapped, then the gift opens and the rest of the page settles in
  const [phase, setPhase] = React.useState(animate ? 'wrapped' : 'done');
  React.useEffect(() => {
    if (!animate) return;
    const a = setTimeout(() => setPhase('open'), 450);
    const b = setTimeout(() => setPhase('done'), 2250);
    return () => { clearTimeout(a); clearTimeout(b); };
  }, []);
  const shown = phase === 'done';
  const fade = (delay = 0) => animate ? {
    opacity: shown ? 1 : 0, transform: shown ? 'none' : 'translateY(14px)', pointerEvents: shown ? 'auto' : 'none',
    transition: `opacity .6s ease ${delay}s, transform .6s var(--iv-ease-soft) ${delay}s`,
  } : {};
  const others = views - 1;

  const place = useBizPlace({ business, placeId, rating, reviewCount, noPhoto });
  return (
    <Screen footer={
      <div style={fade(0.3)}>
        {error && <div style={{ textAlign: 'center', marginBottom: 10, fontSize: 13.5, color: '#B91C1C' }}>{error}</div>}
        <RecoButton onClick={onClaim} disabled={busy || notYet}>{notYet ? `זמין החל ${window.startWord(new Date(tk.startsAt).getTime())}` : claimLabel}</RecoButton>
      </div>
    }>
      {shown && <Confetti soft />}
      <div style={{ margin: 'auto 0', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
                    position: 'relative', zIndex: 6, padding: '10px 0 6px' }}>
        <div style={{ marginBottom: 6, animation: 'reco-pop 0.6s var(--iv-ease-soft) both' }}>
          <RecoParrot size={66} mood="happy" idle />
        </div>
        <Title>קיבלתם Reco 🎉</Title>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginTop: 14, padding: '6px 6px 6px 18px', borderRadius: 99,
                      background: '#fff', border: '1px solid var(--iv-line)', boxShadow: 'var(--iv-shadow-1)' }}>
          <span style={{ width: 36, height: 36, borderRadius: 99, background: 'var(--reco-green)', color: '#fff', display: 'flex', alignItems: 'center',
                         justifyContent: 'center', fontWeight: 700, fontSize: 16, flexShrink: 0 }}>
            {friend ? friend[0] : <RecoParrot size={22} />}
          </span>
          <span style={{ fontSize: 15, color: 'var(--iv-ink-soft)' }}>
            <strong style={{ color: 'var(--reco-navy)', fontWeight: 700 }}>{friend || 'חבר'}</strong> שלח/ה לכם מתנה
          </span>
        </div>

        {animate
          ? <div style={{ marginTop: 22, width: '100%' }}>
              <GiftLocked business={business} open={phase !== 'wrapped'} scale={1} reveal={{ reward, days, tk, from: friend || '', place }} />
            </div>
          : <VoucherTicket reward={reward} business={business} days={days} {...tk} from={friend || ''} place={place} style={{ marginTop: 20 }} />}

        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9, ...fade(0.1) }}>
          {others >= 1 && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 30, padding: '0 13px', borderRadius: 99, background: 'var(--iv-glow)',
                           color: 'var(--reco-green-deep)', fontSize: 13, fontWeight: 600 }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>
              {others === 1 ? 'עוד אדם אחד כבר צפה בשובר' : `עוד ${others} אנשים כבר צפו בשובר`}
            </span>
          )}
          <div style={{ fontSize: 13.5, lineHeight: 1.45, color: 'var(--iv-ink-soft)' }}>
            הראשון שיממש את השובר <strong style={strongGreen}>מרוויח</strong>. מהרו!
          </div>
          {endsAt && !notYet && <LiveCountdown endsAt={endsAt} />}
        </div>

      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ at the counter: verify a phone, then show the live voucher
const fieldStyle = { width: '100%', height: 56, padding: '0 16px', borderRadius: 16, border: '1.5px solid var(--iv-line-strong)',
  background: '#fff', fontFamily: 'var(--iv-font-sans)', fontSize: 20, color: 'var(--iv-ink)', outline: 'none',
  boxShadow: 'var(--iv-shadow-1)', textAlign: 'center', letterSpacing: '0.08em', direction: 'ltr', boxSizing: 'border-box' };

function CounterStep({ business, mode, value, phone, onChange, onSubmit, busy, error }) {
  const isPhone = mode === 'phone';
  return (
    <Screen footer={<RecoButton onClick={onSubmit} disabled={busy || !value.trim()}>{isPhone ? 'שלחו לי קוד' : 'אימות'}</RecoButton>}>
      <TopBar business={business} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ width: 112, height: 112, borderRadius: '50%', background: 'var(--iv-paper-warmer)', marginBottom: 22,
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <RecoParrot size={78} mood="happy" idle />
        </div>
        <Title>{isPhone ? 'אימות טלפון' : 'הזינו את הקוד'}</Title>
        <Sub style={{ fontSize: 15.5, margin: '12px 8px 22px' }}>
          {isPhone
            ? 'נשלח קוד למספר שלכם. המימוש תקף ל-30 דקות.'
            : <>שלחנו קוד למספר <span dir="ltr" style={{ fontWeight: 600, color: 'var(--reco-navy)' }}>{phone}</span></>}
        </Sub>
        {isPhone ? (
          <input style={fieldStyle} type="tel" inputMode="tel" autoComplete="tel" placeholder="050-0000000"
            value={value} onChange={e => onChange(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') onSubmit(); }} />
        ) : (
          <input style={{ ...fieldStyle, fontSize: 26, letterSpacing: '0.4em' }} type="text" inputMode="numeric" autoComplete="one-time-code"
            maxLength={6} placeholder="••••••" value={value}
            onChange={e => onChange(e.target.value.replace(/\D/g, ''))} onKeyDown={e => { if (e.key === 'Enter') onSubmit(); }} />
        )}
        {error && (
          <div style={{ marginTop: 16, padding: '10px 14px', borderRadius: 12, background: '#FEF2F2', border: '1px solid #FECACA',
                        color: '#B91C1C', fontSize: 14, maxWidth: 320 }}>{error}</div>
        )}
      </div>
    </Screen>
  );
}

// The live voucher: the same card, now full green, with a QR and a 30-minute countdown
function Presented({ business, reward, days, tk = {}, sender, placeId, rating, reviewCount, qr, codeText, startedAt, onRestart, busy }) {
  const basePlace = useBizPlace({ business, placeId, rating, reviewCount });
  const endsAt = new Date(startedAt).getTime() + 30 * 60000;
  const [now, setNow] = React.useState(Date.now());
  const [filled, setFilled] = React.useState(false);
  React.useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);
  React.useEffect(() => { const t = setTimeout(() => setFilled(true), 700); return () => clearTimeout(t); }, []);
  if (endsAt - now <= 0) {
    return (
      <Screen footer={<RecoButton onClick={onRestart} disabled={busy}>פתיחת חלון חדש</RecoButton>}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
          <div style={{ marginBottom: 8 }}><RecoParrot size={66} mood="sleep" /></div>
          <Title>חלון המימוש הסתיים</Title>
          <Sub>ה-Reco עדיין שלכם. פתחו חלון חדש כשאתם מוכנים לממש.</Sub>
        </div>
      </Screen>
    );
  }
  return (
    <Screen>
      <div style={{ margin: 'auto 0', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '10px 0 6px' }}>
        <div style={{ marginBottom: 6 }}><RecoParrot size={66} mood="happy" idle /></div>
        <Title>ה-Reco מוכן לסריקה</Title>
        <Sub style={{ fontSize: 15.5, margin: '12px 6px 0' }}>הציגו את הקוד לעובד/ת בקופה.</Sub>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 18, padding: '7px 14px', borderRadius: 99,
                      background: 'var(--iv-glow)', color: 'var(--reco-green-deep)', fontWeight: 600, fontSize: 14 }}>
          <span style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--reco-green)', animation: 'reco-bob 1.2s var(--iv-ease-inout) infinite' }} />
          פעיל כעת · <LiveCountdown endsAt={endsAt} label="" icon={false} />
        </div>
        <div style={{ width: '100%', maxWidth: 440, margin: '16px auto 0', perspective: 1400 }}>
          <div style={{ display: 'grid', transformStyle: 'preserve-3d', transition: 'transform 1.1s cubic-bezier(.45,0,.2,1)', transform: filled ? 'rotateY(180deg)' : 'none' }}>
            <div style={{ gridArea: '1 / 1', alignSelf: 'center', backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden' }}>
              <VoucherTicket reward={reward} business={business} days={days} {...tk} from={sender || ''} place={basePlace} />
            </div>
            <div style={{ gridArea: '1 / 1', backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}>
              <VoucherBack qr={qr} codeText={codeText} business={business} reward={reward} />
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ the voucher can't be used (redeemed / expired / blocked)
function AlreadyClaimed({ business = 'קפה הציפור הכחולה', reward = SAMPLE_REWARD, days = 3, tk = {},
                          title = 'ה-Reco הזה כבר מומש', body = 'נראה שמישהו הקדים אתכם.',
                          variant = 'muted', cta = 'קבלו Reco משלכם בביקור הבא', ctaHref = '/', ctaVariant = 'dark', ctaNewTab = false, placeId }) {
  const place = useBizPlace({ business, placeId });
  return (
    <Screen bg="var(--iv-paper-warm)" footer={
      cta ? <RecoButton variant={ctaVariant} onClick={() => { if (ctaNewTab) { window.open(ctaHref, '_blank') || (window.location.href = ctaHref); } else window.location.href = ctaHref; }}>{cta}</RecoButton> : null
    }>
      <TopBar business={business} right={null} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ width: 112, height: 112, borderRadius: '50%', background: '#fff', border: '1px solid var(--iv-line)', marginBottom: 20,
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <RecoParrot size={76} mood="sleep" />
        </div>
        <Title>{title}</Title>
        <Sub>{body}</Sub>
        <div style={{ marginTop: 24, width: '100%' }}>
          <VoucherTicket reward={reward} business={business} days={days} {...tk} variant={variant} place={place} tag={variant === 'muted' ? 'לא פעיל' : 'פעיל'} />
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ the voucher was already redeemed
function RedeemedView({ business, reward, days, tk = {}, sender, redeemedAt, redeemedBy, placeId }) {
  const pin = useBizPlace({ business, placeId });
  const href = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(business)}${placeId ? `&query_place_id=${encodeURIComponent(placeId)}` : ''}`;
  return (
    <Screen bg="var(--iv-paper-warm)" footer={
      <>
        <RecoButton variant="dark" onClick={() => { window.open(href, '_blank') || (window.location.href = href); }}>פתיחה בגוגל מפות</RecoButton>
        <div style={{ textAlign: 'center', marginTop: 12, fontSize: 13.5, lineHeight: 1.45, color: 'var(--iv-ink-muted)' }}>
          בביקור שלכם, סרקו את הקוד בקופה וגם אתם תוכלו לשלוח מתנה.
        </div>
      </>
    }>
      <div style={{ margin: 'auto 0', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '10px 0 6px' }}>
        <div style={{ width: 100, height: 100, borderRadius: '50%', background: '#fff', border: '1px solid var(--iv-line)', marginBottom: 20,
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ filter: 'grayscale(1) opacity(0.75)' }}><RecoParrot size={70} mood="happy" /></div>
        </div>
        <Title>מישהו הקדים אתכם</Title>
        <Sub>{sender ? `ה-Reco של ${sender} כבר מומש` : 'ה-Reco כבר מומש'}{redeemedBy ? ` על ידי ${redeemedBy}` : ''}. המקום עדיין שווה ביקור.</Sub>
        <div style={{ marginTop: 24, width: '100%' }}>
          <VoucherTicket reward={reward} business={business} days={days} {...tk} from={sender || ''} redeemed={{ at: redeemedAt }} place={pin} variant="muted" />
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ link not available (unknown / inactive)
function Unavailable({ title = 'הקישור הזה לא זמין', body = 'ייתכן שה-Reco הוסר או שהקישור שגוי.' }) {
  return (
    <Screen bg="var(--iv-paper-warm)">
      <TopBar right={null} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ width: 112, height: 112, borderRadius: '50%', background: '#fff', marginBottom: 22, border: '1px solid var(--iv-line)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <RecoParrot size={76} mood="sleep" />
        </div>
        <Title>{title}</Title>
        <Sub>{body}</Sub>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════ the issuer flow (gift: wrapped → spinner → opening)
// A small wrapped gift holding the voucher. It shows only the business name, so what is inside stays a surprise.
// With `open` the bow lifts off and the wrapping splits apart.
function GiftWrap({ h }) {
  return (
    <div style={{ position: 'relative', width: '200%', height: h, overflow: 'hidden', background: 'linear-gradient(135deg, #22C48D, #118A66)' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.08) 0 10px, transparent 10px 20px)' }} />
      <div style={{ position: 'absolute', top: 0, bottom: 0, left: '50%', width: 30, marginLeft: -15, background: 'rgba(255,255,255,0.94)' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 30, marginTop: -15, background: 'rgba(255,255,255,0.94)' }} />
    </div>
  );
}

// `reveal` = { reward, days, tk }: the real voucher waits under the wrapping (instead of the name-only teaser)
function GiftLocked({ business, open = false, scale = 0.5, reveal }) {
  const ref = React.useRef(null);
  const [h, setH] = React.useState(200);
  React.useLayoutEffect(() => {
    const el = ref.current; if (!el) return;
    const measure = () => setH(el.offsetHeight);
    measure();
    if (!window.ResizeObserver) return;
    const ro = new ResizeObserver(measure); ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return (
    <div className={`reco-gift${open ? ' open' : ''}`} style={{ zoom: scale, width: 340, maxWidth: '100%', margin: '0 auto', position: 'relative' }}>
      <div ref={ref} className="reco-gift-card">
        {reveal
          ? <VoucherTicket reward={reveal.reward} business={business} days={reveal.days} {...reveal.tk} from={reveal.from} place={reveal.place} />
          : <VoucherTicket business={business} hideDetails tag="מתנה" />}
      </div>
      <div className="reco-gift-half l" style={{ height: h }}><GiftWrap h={h} /></div>
      <div className="reco-gift-half r" style={{ height: h }}><div style={{ marginLeft: '-100%' }}><GiftWrap h={h} /></div></div>
      <div className="reco-gift-tag"><span>{business}</span></div>
      <div className="reco-gift-bow">
        <svg viewBox="0 0 88 56" width="88" height="56" aria-hidden="true">
          <path d="M44 42C31 42 12 38 10 21 8 6 25 2 35 15c4 5 7 15 9 27z" fill="#fff" stroke="#0F7F5E" strokeWidth="2" strokeLinejoin="round" />
          <path d="M44 42c13 0 32-4 34-21C80 6 63 2 53 15c-4 5-7 15-9 27z" fill="#fff" stroke="#0F7F5E" strokeWidth="2" strokeLinejoin="round" />
          <rect x="37" y="32" width="14" height="14" rx="5" fill="#fff" stroke="#0F7F5E" strokeWidth="2" />
        </svg>
      </div>
    </div>
  );
}

// Stage 1 · the pitch
function ReviewLanding({ business, onReview, busy }) {
  return (
    <Screen footer={
      <>
        <RecoButton onClick={onReview} disabled={busy} icon={
          <svg width="20" height="20" viewBox="0 0 24 24" fill="#FFD34D" aria-hidden="true"><path d="M12 2l2.9 6.3 6.9.7-5.1 4.7 1.4 6.8L12 17.8 5.9 21.2l1.4-6.8L2.2 9.7l6.9-.7z"/></svg>
        }>כתבו ביקורת בגוגל</RecoButton>
        <div style={{ textAlign: 'center', marginTop: 12, fontSize: 13.5, color: 'var(--iv-ink-muted)' }}>לחצו חזור לאחר הדירוג</div>
      </>
    }>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ position: 'relative', marginBottom: 26 }}>
          <div style={{ position: 'absolute', inset: -18, borderRadius: '50%', background: 'var(--iv-gradient-soft)', filter: 'blur(2px)' }} />
          <div style={{ position: 'relative', width: 150, height: 150, borderRadius: '50%', background: 'var(--iv-paper-warmer)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <RecoParrot size={112} mood="happy" idle />
          </div>
        </div>
        <Title>נהניתם? שלחו לחבר מתנה</Title>
        <Sub>כתבו ביקורת קצרה בגוגל, וקבלו Reco לשיתוף עם חברים ומשפחה!</Sub>
        <div style={{ marginTop: 52, width: '100%' }}><GiftLocked business={business} scale={0.46} /></div>
      </div>
    </Screen>
  );
}

// Stage 2 · back from Google
function ReviewCheck({ business, onContinue, onBack, busy }) {
  return (
    <Screen footer={
      <>
        <GoogleButton onClick={onContinue} disabled={busy} />
        <RecoButton variant="ghost" style={{ marginTop: 8 }} onClick={onBack}>עוד לא, חזרה לגוגל</RecoButton>
      </>
    }>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <Title>פרסמתם את הביקורת?</Title>
        <Sub>ברגע שהיא באוויר, ממשיכים לשליחת המתנה.</Sub>
        <div style={{ marginTop: 52, width: '100%' }}><GiftLocked business={business} scale={0.46} /></div>
      </div>
    </Screen>
  );
}

// Stage 3a · a ring spinning around the parrot
function Verifying() {
  return (
    <Screen>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ position: 'relative', width: 140, height: 140 }}>
          <svg className="reco-spin" viewBox="0 0 140 140" width="140" height="140" style={{ position: 'absolute', inset: 0 }} aria-hidden="true">
            <circle cx="70" cy="70" r="64" fill="none" stroke="var(--iv-line)" strokeWidth="6" />
            <circle cx="70" cy="70" r="64" fill="none" stroke="var(--reco-green)" strokeWidth="6" strokeLinecap="round" strokeDasharray="100 302" />
          </svg>
          <div style={{ position: 'absolute', inset: 16, borderRadius: '50%', background: 'var(--iv-paper-warmer)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <RecoParrot size={80} mood="happy" idle />
          </div>
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { RedeemedView, GiftLocked, ReviewLanding, ReviewCheck, Verifying, CouponUnlocked, FriendReferral, CounterStep, Presented, AlreadyClaimed, Unavailable, LiveCountdown });
