// BOX SEATS + STANDARD SEAT FOMO — integrated VIP row and +1/+2/+3 upsell

// ---------- Fake brokerage labels for pre-filled boxes (social proof) ----------
const FAKE_BROKERAGES = [
  'Peters Realty', 'Keller Team', 'Sotheby\u2019s NW', 'Compass HTX', 'Coldwell LA',
  'eXp Atlanta', 'Redfin SD', 'Corcoran NYC', 'Douglas Elliman', 'HomeSmart AZ',
];
const BOX_LETTERS = ['A','B','C','D','E','F','G','H','I','J','K','L'];

function slugify(s) {
  return (s||'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'') || 'agent';
}
function genBoxCode() {
  return Math.random().toString(36).slice(2,6) + Math.random().toString(36).slice(2,5);
}

// -------------------------------------------------------------------
// Invite preview — switchable via tweaks.invitePreview:
//   'boarding' (default)  — original airline boarding pass + small Zoom chip
//   'zoom'                — flat Zoom webinar card
// -------------------------------------------------------------------
function InviteTicketPreview({ hostName, sessionLabel, seatCount, boxLetter='B' }) {
  const { tweaks } = useApp();
  const style = tweaks.invitePreview || 'boarding';
  if (style === 'zoom') return <InvitePreviewZoom hostName={hostName} sessionLabel={sessionLabel} seatCount={seatCount} boxLetter={boxLetter}/>;
  return <InvitePreviewBoarding hostName={hostName} sessionLabel={sessionLabel} seatCount={seatCount} boxLetter={boxLetter}/>;
}

// ── Original boarding-pass — MATCHES the hero TicketBoarding (black header, YOU→ZOOM route, flight meta, passenger stub). ──
function InvitePreviewBoarding({ hostName, sessionLabel, seatCount, boxLetter='B' }) {
  const firstName = (hostName||'Your name').split(' ')[0] || 'Guest';
  return (
    <div style={{position:'relative',margin:'4px 0 0'}}>
      <div style={{
        position:'absolute',inset:-8,borderRadius:18,zIndex:0,
        background:'radial-gradient(ellipse at center, rgba(124,58,237,0.14) 0%, transparent 65%)',
        pointerEvents:'none',
      }}/>
      <div style={{
        position:'relative',zIndex:1,
        background:'#fafbfc',borderRadius:12,
        boxShadow:'0 16px 40px rgba(11,11,20,0.22), 0 0 0 1px rgba(11,11,20,0.08)',
        overflow:'hidden',color:'#0b0b14',
      }}>
        {/* Top stripe — BLACK like the OG */}
        <div style={{
          display:'flex',justifyContent:'space-between',alignItems:'center',
          padding:'7px 12px',
          background:'#0b0b14',color:'#fff',
          fontSize:9.5,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',
          fontFamily:'ui-monospace,SFMono-Regular,Menlo,monospace',
        }}>
          <span>✈ Boarding Pass</span>
          <span>Apex Airways</span>
          <span>Group A</span>
        </div>

        {/* Main split */}
        <div style={{display:'flex'}}>
          {/* LEFT: flight info */}
          <div style={{flex:1,minWidth:0,padding:'12px 12px 10px',borderRight:'2px dashed rgba(11,11,20,0.12)'}}>
            {/* Route — YOU → ZOOM */}
            <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:10}}>
              <div>
                <div style={{fontSize:8,fontWeight:800,letterSpacing:1.8,textTransform:'uppercase',color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace'}}>From</div>
                <div style={{fontFamily:'DM Sans,sans-serif',fontSize:20,fontWeight:800,letterSpacing:'-0.4px',lineHeight:1,color:'#0b0b14',marginTop:2}}>YOU</div>
                <div style={{fontSize:9,color:'#6b7280',marginTop:2,fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.4}}>Anywhere</div>
              </div>
              <div style={{flex:1,position:'relative',height:20,display:'flex',alignItems:'center',padding:'0 4px'}}>
                <div style={{flex:1,height:1.5,background:'repeating-linear-gradient(90deg,#0b0b14 0 3px,transparent 3px 6px)'}}/>
                <span style={{fontSize:15,color:BRAND.purple,margin:'0 2px',lineHeight:1}}>✈</span>
                <div style={{flex:1,height:1.5,background:'repeating-linear-gradient(90deg,#0b0b14 0 3px,transparent 3px 6px)'}}/>
              </div>
              <div style={{textAlign:'right'}}>
                <div style={{fontSize:8,fontWeight:800,letterSpacing:1.8,textTransform:'uppercase',color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace'}}>To</div>
                <div style={{
                  fontFamily:'DM Sans,sans-serif',fontSize:20,fontWeight:800,letterSpacing:'-0.4px',lineHeight:1,marginTop:2,
                  background:BRAND.gradient,WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
                }}>ZOOM</div>
                <div style={{fontSize:9,color:'#6b7280',marginTop:2,fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.4}}>Link in email</div>
              </div>
            </div>

            {/* Flight meta */}
            <div style={{
              display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:3,
              padding:'7px 0',
              borderTop:'1px solid rgba(11,11,20,0.08)',borderBottom:'1px solid rgba(11,11,20,0.08)',
              fontFamily:'ui-monospace,SFMono-Regular,Menlo,monospace',
            }}>
              <div><div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.2,color:'#6b7280'}}>FLIGHT</div><div style={{fontSize:10.5,fontWeight:800,color:'#0b0b14',marginTop:1}}>AX 0097</div></div>
              <div><div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.2,color:'#6b7280'}}>DEPART</div><div style={{fontSize:10.5,fontWeight:800,color:'#0b0b14',marginTop:1}}>{(sessionLabel||'TUE 4PM').toUpperCase()}</div></div>
              <div><div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.2,color:'#6b7280'}}>GATE</div><div style={{fontSize:10.5,fontWeight:800,color:BRAND.purple,marginTop:1}}>{boxLetter}{seatCount||1}</div></div>
              <div><div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.2,color:'#6b7280'}}>CLASS</div><div style={{fontSize:10.5,fontWeight:800,color:BRAND.purple,marginTop:1}}>FNDR</div></div>
            </div>
          </div>

          {/* RIGHT: seat stub */}
          <div style={{width:70,flexShrink:0,padding:'10px 8px',textAlign:'center',background:'#f4f4f7'}}>
            <div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.5,color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace'}}>PASSENGER</div>
            <div style={{fontSize:10,fontWeight:800,color:'#0b0b14',margin:'2px 0 8px',letterSpacing:0.3,textTransform:'uppercase',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{firstName}</div>
            <div style={{fontSize:7.5,fontWeight:800,letterSpacing:1.5,color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace'}}>SEAT</div>
            <div style={{fontFamily:'DM Sans,sans-serif',fontSize:20,fontWeight:800,color:BRAND.purple,letterSpacing:'-0.8px',lineHeight:1}}>{boxLetter}{seatCount||1}</div>
            <div style={{fontSize:8,color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.3,marginTop:1}}>Founder</div>
            <div style={{display:'flex',flexDirection:'column',gap:1,marginTop:8,alignItems:'center'}}>
              {[3,1,2,4,1,3,2,4,1,3].map((w,i) => (
                <span key={i} style={{height:w,width:34,background:'#0b0b14'}}/>
              ))}
            </div>
            <div style={{fontSize:7.5,marginTop:5,color:'#6b7280',fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.4}}>097·28·MAY</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Zoom-card version (previous default) ──
function InvitePreviewZoom({ hostName, sessionLabel, seatCount, boxLetter='B' }) {
  return (
    <div style={{
      background:'#ffffff',borderRadius:12,overflow:'hidden',
      boxShadow:'0 10px 24px rgba(11,11,20,0.12), 0 0 0 1px rgba(11,11,20,0.08)',
      color:'#0b0b14',
    }}>
      {/* Header bar — Zoom-y blue, calendar icon */}
      <div style={{
        display:'flex',justifyContent:'space-between',alignItems:'center',
        padding:'7px 11px',background:'#2D8CFF',color:'#fff',
        fontSize:9.5,fontWeight:800,letterSpacing:1.5,textTransform:'uppercase',
      }}>
        <span style={{display:'flex',alignItems:'center',gap:6}}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/>
          </svg>
          Zoom Invite
        </span>
        <span style={{fontWeight:700,letterSpacing:2}}>APEX OS</span>
      </div>

      {/* Body */}
      <div style={{padding:'12px 12px 10px'}}>
        <div style={{fontSize:9.5,fontWeight:800,letterSpacing:1.8,color:'#6b7280',textTransform:'uppercase',marginBottom:3}}>
          You're invited to
        </div>
        <div style={{fontSize:14.5,fontWeight:800,color:'#0b0b14',letterSpacing:-0.2,lineHeight:1.2,marginBottom:8,fontFamily:'DM Sans,sans-serif'}}>
          Apex OS · Live Walkthrough
        </div>

        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:10}}>
          <div>
            <div style={{fontSize:8.5,fontWeight:800,letterSpacing:1.5,color:'#9aa3b2',textTransform:'uppercase',marginBottom:2}}>When</div>
            <div style={{fontSize:11.5,fontWeight:700,color:'#0b0b14',lineHeight:1.3}}>{sessionLabel || 'Tue 4PM PT'}</div>
            <div style={{fontSize:10,color:'#6b7280',marginTop:1}}>45 min · live</div>
          </div>
          <div>
            <div style={{fontSize:8.5,fontWeight:800,letterSpacing:1.5,color:'#9aa3b2',textTransform:'uppercase',marginBottom:2}}>Where</div>
            <div style={{fontSize:11.5,fontWeight:700,color:'#2D8CFF',lineHeight:1.3,display:'flex',alignItems:'center',gap:4}}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg>
              Zoom
            </div>
            <div style={{fontSize:10,color:'#6b7280',marginTop:1}}>Link in email</div>
          </div>
        </div>

        <div style={{
          display:'flex',alignItems:'center',gap:8,padding:'8px 10px',
          background:'rgba(45,140,255,0.07)',borderRadius:8,
          border:'1px solid rgba(45,140,255,0.18)',
        }}>
          <div style={{
            width:26,height:26,borderRadius:'50%',flexShrink:0,
            background:BRAND.gradient,color:'#fff',
            display:'flex',alignItems:'center',justifyContent:'center',
            fontSize:11,fontWeight:800,
          }}>{(hostName||'Y')[0]}</div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:11,fontWeight:700,color:'#0b0b14',letterSpacing:-0.1,lineHeight:1.2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
              <strong>{hostName || 'Your name'}</strong> saved you a seat
            </div>
            <div style={{fontSize:9.5,color:'#6b7280',marginTop:1,letterSpacing:0.3}}>
              VIP Box {boxLetter} · {seatCount||4} seat{(seatCount||4)>1?'s':''} · Row 1
            </div>
          </div>
        </div>
      </div>

      <div style={{display:'flex',borderTop:'1px solid rgba(11,11,20,0.08)'}}>
        <div style={{flex:1,padding:'9px 8px',textAlign:'center',fontSize:10,fontWeight:800,color:'#2D8CFF',letterSpacing:1,textTransform:'uppercase'}}>
          Add to Calendar
        </div>
        <div style={{width:1,background:'rgba(11,11,20,0.08)'}}/>
        <div style={{flex:1,padding:'9px 8px',textAlign:'center',fontSize:10,fontWeight:800,color:BRAND.purple,letterSpacing:1,textTransform:'uppercase'}}>
          Join Zoom
        </div>
      </div>
    </div>
  );
}

// -------------------------------------------------------------------
// VIP BOX MODAL — slider 4-20 + unique emails + escape hatch
// -------------------------------------------------------------------
function BoxSeatModal({ open, onClose, box, onConfirm, onEscape }) {
  const { booking, tweaks } = useApp();
  const sizerStyle = tweaks.vipBoxSizer || 'slider';       // 'slider' | 'stepper' | 'chips'
  const escapeOn  = tweaks.vipEscape !== 'off';

  const [hostFirst, setHostFirst] = useState(booking.firstName || '');
  const [hostLast,  setHostLast]  = useState(booking.lastName  || '');
  const [hostEmail, setHostEmail] = useState(booking.email     || '');
  const [size,      setSize]      = useState(4);
  const [emails,    setEmails]    = useState(Array(3).fill('')); // size-1 invitees
  const [mode,      setMode]      = useState('emails'); // 'emails' | 'link'
  const [confirmed, setConfirmed] = useState(false);
  const [boxCode] = useState(genBoxCode);
  const [linkCopied, setLinkCopied] = useState(false);

  // Resize emails array whenever size changes
  useEffect(() => {
    setEmails(prev => {
      const want = size - 1;
      if (prev.length === want) return prev;
      if (prev.length > want) return prev.slice(0, want);
      return [...prev, ...Array(want - prev.length).fill('')];
    });
  }, [size]);

  // Reset on close
  useEffect(() => {
    if (!open) setTimeout(() => { setConfirmed(false); setLinkCopied(false); }, 300);
  }, [open]);

  if (!open) return null;

  const hostName = `${hostFirst} ${hostLast}`.trim() || 'You';
  const slug = slugify(hostFirst || 'agent');
  const link = `apexopsystems.com/box/${slug}-${boxCode}-${size}`;
  const boxLetter = box?.letter || 'B';

  // Validation — valid + unique emails
  const trimmed = emails.map(e => e.trim().toLowerCase());
  const emailErrs = trimmed.map((e, i) => {
    if (!e) return null;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) return 'invalid';
    if (trimmed.slice(0, i).includes(e)) return 'duplicate';
    if (e === hostEmail.trim().toLowerCase() && hostEmail) return 'host';
    return null;
  });
  const filledEmails = trimmed.filter((e,i) => e && !emailErrs[i]);
  const hostEmailTrim = hostEmail.trim().toLowerCase();
  const hostEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(hostEmailTrim);
  const conflictsHost = hostEmailTrim && trimmed.some(e => e === hostEmailTrim);

  const nameOk = hostFirst.trim() && hostEmailValid;
  const canConfirm =
    nameOk &&
    !conflictsHost &&
    (mode === 'link'
      ? true
      : filledEmails.length >= Math.min(3, size - 1) &&
        emailErrs.every(e => !e));

  const copyLink = () => {
    try { navigator.clipboard.writeText('https://' + link); } catch(e){}
    setLinkCopied(true);
    setTimeout(() => setLinkCopied(false), 2000);
  };

  const confirm = () => {
    if (onConfirm) onConfirm({
      boxId: box?.id, hostName, hostEmail: hostEmailTrim,
      emails: filledEmails, link, mode,
      seatCount: mode === 'link' ? size : filledEmails.length + 1,
      size,
    });
    // Parent routes to the dedicated ConfirmScreen; close this modal.
    if (onClose) onClose();
  };

  const escape = () => { if (onClose) onClose(); if (onEscape) onEscape(); };

  return (
    <div
      onClick={onClose}
      style={{
        position:'fixed',inset:0,zIndex:300,
        background:'rgba(11,11,20,0.75)',backdropFilter:'blur(6px)',
        padding:'20px 16px',overflowY:'auto',
        display:'flex',alignItems:'flex-start',justifyContent:'center',
        animation:'apex-fade-in 0.25s ease',
      }}>
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width:'100%',maxWidth:480,
          background:'var(--card)',borderRadius:20,
          boxShadow:'0 30px 80px rgba(0,0,0,0.5)',
          padding:'22px 20px 20px',position:'relative',marginTop:20,marginBottom:40,
          border:'1px solid var(--border)',color:'var(--ink)',
          animation:'apex-slide-up 0.3s cubic-bezier(0.16,1,0.3,1)',
        }}>
        <button onClick={onClose} style={{
          position:'absolute',top:14,right:14,
          background:'transparent',border:'none',color:'var(--mute)',
          width:30,height:30,borderRadius:'50%',cursor:'pointer',
          fontSize:16,fontWeight:700,fontFamily:'inherit',
        }}>×</button>

        {!confirmed ? (<>
          <div style={{
            display:'inline-flex',alignItems:'center',gap:6,
            fontSize:9.5,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',
            color:'#fff',background:BRAND.gradient,
            padding:'4px 10px',borderRadius:999,marginBottom:10,
            boxShadow:'0 6px 18px rgba(124,58,237,0.35)',
          }}>
            ★ VIP Box · Row 1 · Section {boxLetter}
          </div>
          <h2 style={{
            fontSize:'clamp(22px,5vw,28px)',fontWeight:800,
            letterSpacing:'-0.5px',lineHeight:1.1,margin:'0 0 6px',
            color:'var(--ink)',fontFamily:'DM Sans,sans-serif',
          }}>
            Host Box {boxLetter}
          </h2>
          <p style={{fontSize:13.5,color:'var(--mute)',lineHeight:1.5,margin:'0 0 14px'}}>
            VIP boxes are for teams & brokerages. Pick your size and lock Row 1 before the room fills.
          </p>

          {/* ── Step 1: Your seat (host) ── */}
          <div style={{
            padding:'12px 12px 10px',marginBottom:12,
            background:'rgba(124,58,237,0.06)',
            border:'1.5px solid rgba(124,58,237,0.3)',borderRadius:12,
          }}>
            <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
              <span style={{
                width:22,height:22,borderRadius:'50%',flexShrink:0,
                background:BRAND.gradient,color:'#fff',
                display:'flex',alignItems:'center',justifyContent:'center',
                fontSize:11,fontWeight:800,
              }}>1</span>
              <div style={{flex:1}}>
                <div style={{fontSize:11,fontWeight:800,color:BRAND.purple,letterSpacing:1.5,textTransform:'uppercase',lineHeight:1.1}}>
                  Your seat · Box host
                </div>
                <div style={{fontSize:10.5,color:'var(--mute)',marginTop:1,lineHeight:1.3}}>
                  We'll send your Zoom invite + calendar hold here first.
                </div>
              </div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6,marginBottom:6}}>
              <input value={hostFirst} onChange={e=>setHostFirst(e.target.value)} placeholder="First name" style={inputStyle}/>
              <input value={hostLast}  onChange={e=>setHostLast(e.target.value)}  placeholder="Last name"  style={inputStyle}/>
            </div>
            <input
              value={hostEmail} onChange={e=>setHostEmail(e.target.value)}
              placeholder="you@brokerage.com"
              type="email"
              style={{...inputStyle, borderColor: hostEmail && !hostEmailValid ? '#ef4444' : undefined}}
            />
            {hostEmail && !hostEmailValid && (
              <div style={{fontSize:10.5,color:'#ef4444',marginTop:3,paddingLeft:2,fontWeight:600}}>
                Please enter a valid email
              </div>
            )}
          </div>

          {/* ── Step 2: Box size ── */}
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
            <span style={{
              width:22,height:22,borderRadius:'50%',flexShrink:0,
              background: nameOk ? BRAND.gradient : 'var(--break-bg)',
              color: nameOk ? '#fff' : 'var(--mute)',
              display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:11,fontWeight:800,border: nameOk ? 'none' : '1px solid var(--border-strong)',
            }}>2</span>
            <div style={{fontSize:11,fontWeight:800,color: nameOk ? BRAND.purple : 'var(--mute)',letterSpacing:1.5,textTransform:'uppercase'}}>
              Box size
            </div>
          </div>

          {/* Size picker */}
          <SizerRow value={size} onChange={setSize} mode={sizerStyle}/>

          {/* ── Step 3: Invites ── */}
          <div style={{display:'flex',alignItems:'center',gap:8,marginTop:14,marginBottom:8}}>
            <span style={{
              width:22,height:22,borderRadius:'50%',flexShrink:0,
              background: nameOk ? BRAND.gradient : 'var(--break-bg)',
              color: nameOk ? '#fff' : 'var(--mute)',
              display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:11,fontWeight:800,border: nameOk ? 'none' : '1px solid var(--border-strong)',
            }}>3</span>
            <div style={{fontSize:11,fontWeight:800,color: nameOk ? BRAND.purple : 'var(--mute)',letterSpacing:1.5,textTransform:'uppercase'}}>
              Invite your {size-1}
            </div>
          </div>

          {/* Tabs */}
          <div style={{
            display:'flex',gap:4,padding:3,marginBottom:12,
            background:'var(--break-bg)',borderRadius:10,
          }}>
            {[
              {k:'emails', l:`Invite ${size-1} by email`},
              {k:'link',   l:'Share a link'},
            ].map(t => (
              <button key={t.k} onClick={()=>setMode(t.k)} style={{
                flex:1,padding:'8px 10px',
                background: mode===t.k ? 'var(--card)' : 'transparent',
                color:      mode===t.k ? 'var(--ink)'  : 'var(--mute)',
                border:'none',borderRadius:7,
                fontFamily:'inherit',fontSize:11.5,fontWeight:700,cursor:'pointer',
                boxShadow: mode===t.k ? '0 2px 6px rgba(0,0,0,0.08)' : 'none',
                letterSpacing:0.2,
              }}>{t.l}</button>
            ))}
          </div>

          {mode === 'emails' ? (
            <>
              <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6}}>
                Teammates · {filledEmails.length}/{size-1} invited
                <span style={{float:'right',color:filledEmails.length>=Math.min(3,size-1)?'#10b981':'var(--mute)',fontWeight:700}}>
                  {filledEmails.length>=Math.min(3,size-1)?'✓ ready':`min ${Math.min(3,size-1)}`}
                </span>
              </div>

              {/* Host seat 1 marker — shows your email is already locked */}
              {nameOk && (
                <div style={{
                  display:'flex',gap:6,alignItems:'center',marginBottom:6,
                  padding:'7px 10px',
                  background:'rgba(16,185,129,0.08)',
                  border:'1px solid rgba(16,185,129,0.3)',borderRadius:8,
                }}>
                  <span style={{
                    width:22,height:22,borderRadius:'50%',flexShrink:0,
                    background:'#10b981',color:'#fff',
                    display:'flex',alignItems:'center',justifyContent:'center',
                    fontSize:11,fontWeight:800,
                  }}>1</span>
                  <div style={{flex:1,minWidth:0,lineHeight:1.25}}>
                    <div style={{fontSize:11,fontWeight:800,color:'#065f46',letterSpacing:0.2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                      {hostName} <span style={{color:'#10b981',fontSize:9.5,fontWeight:800,letterSpacing:1,marginLeft:4}}>YOU · HOST</span>
                    </div>
                    <div style={{fontSize:10,color:'#065f46',opacity:0.75,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.1}}>
                      {hostEmail}
                    </div>
                  </div>
                  <span style={{fontSize:10,fontWeight:800,color:'#10b981',letterSpacing:0.5}}>✓ LOCKED</span>
                </div>
              )}

              <div style={{display:'flex',flexDirection:'column',gap:6,marginBottom:8,
                maxHeight: size>=10?260:'none',overflowY: size>=10?'auto':'visible',
                paddingRight: size>=10?4:0,
              }}>
                {emails.map((e, i) => {
                  const err = emailErrs[i];
                  return (
                    <div key={i} style={{display:'flex',gap:6,alignItems:'center'}}>
                      <span style={{
                        width:22,height:22,borderRadius:'50%',flexShrink:0,
                        background:'var(--break-bg)',border:'1px solid var(--border-strong)',
                        display:'flex',alignItems:'center',justifyContent:'center',
                        fontSize:9.5,fontWeight:800,color:'var(--mute)',letterSpacing:0.3,
                      }}>{i+2}</span>
                      <div style={{flex:1,minWidth:0}}>
                        <input
                          value={e}
                          onChange={ev => { const n=[...emails]; n[i]=ev.target.value; setEmails(n); }}
                          placeholder={`teammate${i+1}@brokerage.com`}
                          type="email"
                          style={{...inputStyle, fontSize:13, borderColor: err ? '#ef4444' : undefined}}
                        />
                        {err && (
                          <div style={{fontSize:10.5,color:'#ef4444',marginTop:2,paddingLeft:2,fontWeight:600}}>
                            {err==='duplicate' ? 'Already added above' : err==='host' ? 'That\u2019s your email' : 'Invalid email'}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          ) : (
            <div style={{
              padding:'14px 14px',background:'var(--break-bg)',borderRadius:12,marginBottom:12,
            }}>
              <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6,display:'flex',justifyContent:'space-between'}}>
                <span>Shareable link</span>
                <span style={{color:BRAND.purple,fontWeight:800}}>EXPECTS {size-1} INVITEES</span>
              </div>
              <div style={{
                display:'flex',gap:6,alignItems:'center',
                padding:'9px 10px',background:'var(--card)',
                border:'1px solid var(--border-strong)',borderRadius:8,
              }}>
                <span style={{
                  flex:1,minWidth:0,fontSize:12,fontWeight:600,color:'var(--ink)',
                  fontFamily:'ui-monospace,SFMono-Regular,Menlo,monospace',
                  overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',
                }}>{link}</span>
                <button onClick={copyLink} style={{
                  background:BRAND.gradient,color:'#fff',border:'none',
                  borderRadius:6,padding:'5px 10px',
                  fontFamily:'inherit',fontSize:10.5,fontWeight:800,letterSpacing:1,textTransform:'uppercase',cursor:'pointer',
                }}>{linkCopied ? 'Copied!' : 'Copy'}</button>
              </div>
              {/* Expected-headcount meter */}
              <div style={{marginTop:10}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:4}}>
                  <span style={{fontSize:10.5,fontWeight:700,color:'var(--mute)',letterSpacing:0.3}}>
                    Expected headcount
                  </span>
                  <span style={{fontSize:11,fontWeight:800,color:'var(--ink)',letterSpacing:0.3}}>
                    1 <span style={{color:'var(--mute)'}}>of</span> {size} locked <span style={{color:'var(--mute)'}}>·</span> {size-1} pending
                  </span>
                </div>
                <div style={{height:6,background:'var(--card)',borderRadius:3,overflow:'hidden'}}>
                  <div style={{
                    height:'100%',width:`${(1/size)*100}%`,background:BRAND.gradient,
                    transition:'width 0.4s',
                  }}/>
                </div>
                <div style={{fontSize:10.5,color:'var(--mute)',marginTop:5,lineHeight:1.4}}>
                  Each person who opens the link claims one of your {size-1} pending seats and sees the live countdown.
                </div>
              </div>
            </div>
          )}

          {/* Ticket preview */}
          <div style={{marginBottom:14}}>
            <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6}}>
              Your teammates will receive:
            </div>
            <InviteTicketPreview
              hostName={hostName}
              sessionLabel="Tue 4PM PT"
              seatCount={mode==='link'? size : filledEmails.length + 1}
              boxLetter={boxLetter}
            />
          </div>

          <button onClick={confirm} disabled={!canConfirm} style={{
            width:'100%',padding:'14px 18px',
            background: canConfirm ? BRAND.gradient : 'var(--break-bg)',
            color:      canConfirm ? '#fff'         : 'var(--mute)',
            border:'none',borderRadius:14,
            fontFamily:'inherit',fontSize:14,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
            cursor: canConfirm ? 'pointer' : 'not-allowed',
            boxShadow: canConfirm ? '0 14px 36px rgba(124,58,237,0.45)' : 'none',
            display:'flex',alignItems:'center',justifyContent:'center',gap:10,
          }}>
            {mode === 'link'
              ? `🔗 Lock Box ${boxLetter} · ${size} seats`
              : `Lock Box ${boxLetter} · Send ${filledEmails.length} Zoom invite${filledEmails.length===1?'':'s'}`}
          </button>
          <div style={{
            fontSize:11,color:'var(--mute)',textAlign:'center',marginTop:10,lineHeight:1.4,
          }}>
            Box holds until session starts · 200% ROI guarantee applies to every seat
          </div>

          {/* Escape hatch */}
          {escapeOn && (
            <button onClick={escape} style={{
              display:'flex',alignItems:'center',justifyContent:'center',gap:6,
              margin:'14px auto 0',padding:'10px 16px',
              background:'rgba(124,58,237,0.08)',
              border:'1.5px solid rgba(124,58,237,0.35)',borderRadius:10,
              color:BRAND.purple,fontSize:12.5,fontWeight:700,cursor:'pointer',
              fontFamily:'inherit',letterSpacing:0.2,
              transition:'all 0.15s',
            }}
            onMouseEnter={e=>{e.currentTarget.style.background='rgba(124,58,237,0.14)';e.currentTarget.style.borderColor=BRAND.purple;}}
            onMouseLeave={e=>{e.currentTarget.style.background='rgba(124,58,237,0.08)';e.currentTarget.style.borderColor='rgba(124,58,237,0.35)';}}
            >
              Solo, or fewer than 4 people? Grab a standard seat instead →
            </button>
          )}
        </>) : (
          /* CONFIRMATION */
          <div style={{textAlign:'center'}}>
            <div style={{
              width:64,height:64,margin:'4px auto 14px',borderRadius:'50%',
              background:BRAND.gradient,color:'#fff',
              display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:30,fontWeight:800,
              boxShadow:'0 14px 40px rgba(124,58,237,0.45)',
              animation:'apex-pulse-badge 1.4s ease-in-out infinite',
            }}>✓</div>
            <h2 style={{fontSize:24,fontWeight:800,letterSpacing:'-0.5px',color:'var(--ink)',margin:'0 0 6px',fontFamily:'DM Sans,sans-serif'}}>
              Box {boxLetter} reserved
            </h2>
            <p style={{fontSize:13.5,color:'var(--mute)',margin:'0 0 16px',lineHeight:1.5}}>
              {mode === 'link'
                ? <>Your link is copied. Expecting <strong style={{color:'var(--ink)'}}>{size-1}</strong> more from your team.</>
                : <><strong style={{color:'var(--ink)'}}>{filledEmails.length}</strong> Zoom invite{filledEmails.length===1?'':'s'} sent to your team.</>}
            </p>
            <div style={{marginBottom:14}}>
              <InviteTicketPreview hostName={hostName} sessionLabel="Tue 4PM PT" seatCount={mode==='link'? size : filledEmails.length + 1} boxLetter={boxLetter}/>
            </div>
            {mode === 'link' && (
              <div style={{
                padding:'9px 12px',marginBottom:12,
                background:'var(--break-bg)',borderRadius:10,
                fontSize:11.5,color:'var(--mute)',
                fontFamily:'ui-monospace,Menlo,monospace',letterSpacing:0.2,
                overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',
              }}>{link}</div>
            )}
            <button onClick={onClose} style={{
              width:'100%',padding:'12px 16px',
              background:BRAND.gradient,color:'#fff',border:'none',borderRadius:12,
              fontFamily:'inherit',fontSize:13,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
              cursor:'pointer',boxShadow:'0 10px 28px rgba(124,58,237,0.4)',
            }}>Done · Back to seat map</button>
          </div>
        )}
      </div>
    </div>
  );
}

// -------------------------------------------------------------------
// STANDARD SEAT MODAL — "bring a +1/+2/+3?" FOMO prompt
// -------------------------------------------------------------------
function StandardSeatModal({ open, onClose, seatLabel, onConfirm, seatIdx, onUpgradeToBox }) {
  const { booking, tweaks } = useApp();
  const variant = tweaks.standardUpsell || 'three'; // 'off' | 'one' | 'two' | 'three'
  const [plusN, setPlusN] = useState(0);
  const [emails, setEmails] = useState(Array(3).fill(''));
  const [hostEmail, setHostEmail] = useState(booking.email || '');
  const [confirmed, setConfirmed] = useState(false);

  useEffect(() => {
    if (!open) setTimeout(() => { setPlusN(0); setEmails(Array(3).fill('')); setConfirmed(false); }, 300);
  }, [open]);
  useEffect(() => { if (open) setHostEmail(booking.email || ''); }, [open, booking.email]);

  if (!open) return null;

  const maxPlus = variant === 'off' ? 0 : variant === 'one' ? 1 : variant === 'two' ? 2 : 3;
  const hostEmailTrim = hostEmail.trim().toLowerCase();
  const hostEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(hostEmailTrim);
  const trimmed = emails.slice(0, plusN).map(e => e.trim().toLowerCase());
  const emailErrs = trimmed.map((e,i) => {
    if (!e) return null;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) return 'invalid';
    if (trimmed.findIndex(x => x === e) !== i) return 'duplicate';
    if (e === hostEmailTrim) return 'host';
    return null;
  });
  const filled = trimmed.filter((e,i) => e && !emailErrs[i]);
  const canConfirm = hostEmailValid && (plusN === 0 || filled.length === plusN);

  const confirm = () => {
    if (onConfirm) onConfirm({ seatIdx, plusN, emails: filled, hostEmail: hostEmailTrim });
    if (onClose) onClose();
  };

  return (
    <div onClick={onClose} style={{
      position:'fixed',inset:0,zIndex:300,
      background:'rgba(11,11,20,0.75)',backdropFilter:'blur(6px)',
      padding:'20px 16px',overflowY:'auto',
      display:'flex',alignItems:'flex-start',justifyContent:'center',
      animation:'apex-fade-in 0.25s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width:'100%',maxWidth:440,background:'var(--card)',borderRadius:20,
        boxShadow:'0 30px 80px rgba(0,0,0,0.5)',
        padding:'22px 20px 20px',position:'relative',marginTop:60,marginBottom:40,
        border:'1px solid var(--border)',color:'var(--ink)',
        animation:'apex-slide-up 0.3s cubic-bezier(0.16,1,0.3,1)',
      }}>
        <button onClick={onClose} style={{
          position:'absolute',top:14,right:14,background:'transparent',border:'none',color:'var(--mute)',
          width:30,height:30,borderRadius:'50%',cursor:'pointer',fontSize:16,fontWeight:700,fontFamily:'inherit',
        }}>×</button>

        {!confirmed ? (<>
          <div style={{
            display:'inline-flex',alignItems:'center',gap:6,
            fontSize:9.5,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',
            color:'#10b981',background:'rgba(16,185,129,0.12)',
            padding:'4px 10px',borderRadius:999,marginBottom:10,
            border:'1px solid rgba(16,185,129,0.3)',
          }}>
            ✓ Seat {seatLabel || '#?'} reserved
          </div>

          {variant !== 'off' ? (<>
            <h2 style={{
              fontSize:'clamp(22px,5.2vw,28px)',fontWeight:800,
              letterSpacing:'-0.5px',lineHeight:1.15,margin:'0 0 6px',
              color:'var(--ink)',fontFamily:'DM Sans,sans-serif',
            }}>
              Who's coming with you?
            </h2>
            <p style={{fontSize:13.5,color:'var(--mute)',lineHeight:1.5,margin:'0 0 14px'}}>
              Don't run Apex alone. Loop in the people you'd actually build with — your assistant, your lead agent, your broker. <strong style={{color:'var(--ink)'}}>They lock $97/mo for life too</strong>, and you'll all be on the same system day one. No commitments to join now, just invites to check out Apex with you.
            </p>

            {/* Segmented picker */}
            <div style={{
              display:'flex',gap:4,padding:3,marginBottom:8,
              background:'var(--break-bg)',borderRadius:10,
            }}>
              {Array.from({length: maxPlus + 1}).map((_, n) => (
                <button key={n} onClick={() => setPlusN(n)} style={{
                  flex:1,padding:'10px 8px',
                  background: plusN===n ? BRAND.gradient : 'transparent',
                  color:      plusN===n ? '#fff'         : 'var(--ink)',
                  border:'none',borderRadius:7,
                  fontFamily:'inherit',fontSize:12,fontWeight:800,cursor:'pointer',
                  letterSpacing:0.3,
                  boxShadow: plusN===n ? '0 4px 14px rgba(124,58,237,0.4)' : 'none',
                  transition:'all 0.15s',
                }}>
                  {n===0 ? 'Just me' : n===1 ? '+1 seat' : `+${n} seats`}
                </button>
              ))}
            </div>

            {/* Upgrade-to-box prompt when maxed out */}
            {plusN === maxPlus && maxPlus > 0 && onUpgradeToBox && (
              <button onClick={onUpgradeToBox} style={{
                display:'flex',alignItems:'center',gap:10,width:'100%',
                padding:'10px 12px',marginBottom:12,
                background:'rgba(124,58,237,0.08)',
                border:'1.5px solid rgba(124,58,237,0.35)',borderRadius:10,
                fontFamily:'inherit',textAlign:'left',cursor:'pointer',
                transition:'all 0.15s',
              }}
              onMouseEnter={e=>{e.currentTarget.style.background='rgba(124,58,237,0.14)';e.currentTarget.style.borderColor=BRAND.purple;}}
              onMouseLeave={e=>{e.currentTarget.style.background='rgba(124,58,237,0.08)';e.currentTarget.style.borderColor='rgba(124,58,237,0.35)';}}
              >
                <span style={{
                  width:28,height:28,borderRadius:8,flexShrink:0,
                  background:BRAND.gradient,color:'#fff',
                  display:'flex',alignItems:'center',justifyContent:'center',
                  fontSize:15,fontWeight:800,
                }}>★</span>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:12,fontWeight:800,color:BRAND.purple,letterSpacing:0.2,lineHeight:1.3}}>
                    Got 4+ people? Save a VIP Box instead →
                  </div>
                  <div style={{fontSize:10.5,color:'var(--mute)',marginTop:1,letterSpacing:0.2}}>
                    Up to 20 seats · Row 1 · one link you share with your team
                  </div>
                </div>
              </button>
            )}

            {/* Host email — needed so we can send YOUR boarding pass */}
            <div style={{marginBottom:12}}>
              <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6}}>
                Your email · we'll send your boarding pass here
              </div>
              <input
                value={hostEmail}
                onChange={e => setHostEmail(e.target.value)}
                placeholder="you@brokerage.com"
                type="email"
                style={{...inputStyle, borderColor: hostEmail && !hostEmailValid ? '#ef4444' : undefined}}
              />
              {hostEmail && !hostEmailValid && (
                <div style={{fontSize:10.5,color:'#ef4444',marginTop:2,paddingLeft:2,fontWeight:600}}>
                  Enter a valid email
                </div>
              )}
            </div>

            {/* Email inputs */}
            {plusN > 0 && (
              <div style={{marginBottom:12}}>
                <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6}}>
                  Their emails · they get a Zoom invite + calendar hold
                </div>
                <div style={{display:'flex',flexDirection:'column',gap:6}}>
                  {Array.from({length: plusN}).map((_, i) => {
                    const err = emailErrs[i];
                    return (
                      <div key={i}>
                        <input
                          value={emails[i] || ''}
                          onChange={e => { const n=[...emails]; n[i]=e.target.value; setEmails(n); }}
                          placeholder={`teammate${i+1}@brokerage.com`}
                          type="email"
                          style={{...inputStyle, borderColor: err ? '#ef4444' : undefined}}
                        />
                        {err && (
                          <div style={{fontSize:10.5,color:'#ef4444',marginTop:2,paddingLeft:2,fontWeight:600}}>
                            {err==='duplicate' ? 'Already added above' : err==='host' ? 'That\u2019s your email' : 'Invalid email'}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Boarding pass preview — shown for Just me AND +N */}
            <div style={{marginBottom:14}}>
              <div style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)',marginBottom:6}}>
                {plusN === 0
                  ? `You'll receive:`
                  : `You + your ${plusN===1?'teammate':'teammates'} will receive:`}
              </div>
              <InviteTicketPreview
                hostName={`${booking.firstName||'You'} ${booking.lastName||''}`.trim()}
                sessionLabel="Tue 4PM PT"
                seatCount={plusN + 1}
                boxLetter={seatLabel || '#?'}
              />
            </div>
          </>) : (
            <h2 style={{fontSize:22,fontWeight:800,margin:'0 0 14px',fontFamily:'DM Sans,sans-serif',color:'var(--ink)'}}>
              You're in. Seat {seatLabel}.
            </h2>
          )}

          <button onClick={confirm} disabled={!canConfirm} style={{
            width:'100%',padding:'14px 18px',
            background: canConfirm ? BRAND.gradient : 'var(--break-bg)',
            color:      canConfirm ? '#fff'         : 'var(--mute)',
            border:'none',borderRadius:14,
            fontFamily:'inherit',fontSize:14,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
            cursor: canConfirm ? 'pointer' : 'not-allowed',
            boxShadow: canConfirm ? '0 14px 36px rgba(124,58,237,0.45)' : 'none',
          }}>
            {plusN === 0 ? 'Lock just my seat' : `Lock all ${plusN + 1} seats`}
          </button>
        </>) : (
          <div style={{textAlign:'center'}}>
            <div style={{
              width:60,height:60,margin:'4px auto 12px',borderRadius:'50%',
              background:BRAND.gradient,color:'#fff',
              display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:28,fontWeight:800,
            }}>✓</div>
            <h2 style={{fontSize:22,fontWeight:800,margin:'0 0 6px',fontFamily:'DM Sans,sans-serif'}}>
              {plusN === 0 ? 'Seat locked' : `${plusN + 1} seats locked`}
            </h2>
            <p style={{fontSize:13,color:'var(--mute)',margin:'0 0 14px',lineHeight:1.5}}>
              {plusN === 0
                ? <>We'll text you the join link before start.</>
                : <>{plusN} Zoom invite{plusN===1?'':'s'} sent to your team.</>}
            </p>
            <button onClick={onClose} style={{
              width:'100%',padding:'12px 16px',
              background:BRAND.gradient,color:'#fff',border:'none',borderRadius:12,
              fontFamily:'inherit',fontSize:13,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
              cursor:'pointer',
            }}>Continue</button>
          </div>
        )}
      </div>
    </div>
  );
}

// -------------------------------------------------------------------
// SIZER — slider / chips / stepper
// -------------------------------------------------------------------
function SizerRow({ value, onChange, mode }) {
  const CHIPS = [4, 6, 8, 10, 12, 20];
  return (
    <div style={{marginTop:6}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:6}}>
        <span style={{fontSize:10.5,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)'}}>
          Box size
        </span>
        <span style={{
          fontFamily:'DM Sans,sans-serif',fontSize:18,fontWeight:800,color:'var(--ink)',letterSpacing:-0.5,
        }}>{value} <span style={{fontSize:11,fontWeight:600,color:'var(--mute)',letterSpacing:0.3}}>seats</span></span>
      </div>

      {mode === 'chips' && (
        <div style={{display:'flex',gap:5,flexWrap:'wrap'}}>
          {CHIPS.map(n => (
            <button key={n} onClick={() => onChange(n)} style={{
              padding:'8px 14px',flex:1,minWidth:50,
              background: value===n ? BRAND.gradient : 'var(--break-bg)',
              color:      value===n ? '#fff'         : 'var(--ink)',
              border:'none',borderRadius:8,fontFamily:'inherit',fontSize:13,fontWeight:800,
              cursor:'pointer',boxShadow: value===n ? '0 4px 12px rgba(124,58,237,0.35)':'none',
            }}>{n}</button>
          ))}
        </div>
      )}

      {mode === 'stepper' && (
        <div style={{display:'flex',alignItems:'center',gap:10,
          background:'var(--break-bg)',padding:6,borderRadius:10,
        }}>
          <button onClick={() => onChange(Math.max(4, value - 1))} style={stepBtnStyle}>−</button>
          <div style={{flex:1,textAlign:'center',fontSize:22,fontWeight:800,letterSpacing:-0.5,fontFamily:'DM Sans,sans-serif',color:'var(--ink)'}}>
            {value}
          </div>
          <button onClick={() => onChange(Math.min(20, value + 1))} style={stepBtnStyle}>+</button>
        </div>
      )}

      {mode === 'slider' && (
        <>
          <input
            type="range" min={4} max={20} step={1} value={value}
            onChange={e => onChange(parseInt(e.target.value, 10))}
            style={{
              width:'100%',accentColor:BRAND.purple,height:6,cursor:'pointer',
            }}
          />
          <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--mute)',letterSpacing:0.5,fontWeight:600,marginTop:2}}>
            <span>4 · min team</span>
            <span>10</span>
            <span>20 · full brokerage</span>
          </div>
        </>
      )}
    </div>
  );
}

const inputStyle = {
  width:'100%',padding:'10px 12px',
  background:'var(--break-bg)',
  border:'1px solid var(--border-strong)',borderRadius:8,
  color:'var(--ink)',fontFamily:'inherit',fontSize:13,outline:'none',
  boxSizing:'border-box',
};

const stepBtnStyle = {
  width:40,height:40,borderRadius:8,border:'none',
  background:'var(--card)',color:'var(--ink)',
  fontSize:20,fontWeight:800,cursor:'pointer',fontFamily:'inherit',
  boxShadow:'0 2px 6px rgba(0,0,0,0.08)',
};

// -------------------------------------------------------------------
// VIP BOX ROW — 3 design styles on-theme, switchable via tweaks.vipBoxDesign
// -------------------------------------------------------------------
function VipBoxRow({ boxes, onOpenBox, myBoxId }) {
  const { tweaks } = useApp();
  const design = tweaks.vipBoxDesign || 'suite';
  if (design === 'suite')    return <VipBoxRowSuite    boxes={boxes} onOpenBox={onOpenBox} myBoxId={myBoxId}/>;
  if (design === 'ribbon')   return <VipBoxRowRibbon   boxes={boxes} onOpenBox={onOpenBox} myBoxId={myBoxId}/>;
  if (design === 'editorial')return <VipBoxRowEditorial boxes={boxes} onOpenBox={onOpenBox} myBoxId={myBoxId}/>;
  return <VipBoxRowSuite boxes={boxes} onOpenBox={onOpenBox} myBoxId={myBoxId}/>;
}

// Shared label — purple, not amber
function VipBoxLabel() {
  return (
    <div style={{
      display:'flex',alignItems:'center',gap:6,marginBottom:8,
      fontSize:9,letterSpacing:2.8,textTransform:'uppercase',color:BRAND.purple,fontWeight:800,
    }}>
      <span style={{
        display:'inline-block',width:14,height:1,
        background:`linear-gradient(90deg,transparent,${BRAND.purple})`,
      }}/>
      ★ VIP Box Seats · Row 1
      <span style={{
        display:'inline-block',flex:1,height:1,
        background:`linear-gradient(90deg,${BRAND.purple},transparent)`,
      }}/>
    </div>
  );
}

function VipBoxHint() {
  return (
    <div style={{
      fontSize:10.5,color:'var(--mute)',textAlign:'center',marginTop:8,letterSpacing:0.2,
    }}>
      VIP boxes hold <strong style={{color:'var(--ink)'}}>4–20 agents</strong> · perfect for teams & brokerages
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// FLANKING BOXES — compact vertical stacks of box tiles to the
// LEFT + RIGHT of the stadium stage (like opera boxes).
// Used when tweaks.boxPosition === 'flank' or 'opera'.
// ═══════════════════════════════════════════════════════════════════

// VIP theme palettes — 4 variants, all feel premium in their own way
const VIP_THEMES = {
  onbrand: {
    tileBg: BRAND.gradient,
    tileBorder: 'transparent',
    tileHover: '#fff',
    tileShadow: '0 4px 14px rgba(124,58,237,0.4), inset 0 1px 0 rgba(255,255,255,0.25), inset 0 -2px 0 rgba(0,0,0,0.12)',
    tileLetter: '#fff',
    tileLetterGlow: '0 1px 3px rgba(0,0,0,0.25)',
    tileMeta: 'rgba(255,255,255,0.92)',
    letterFont: 'DM Serif Display,Georgia,serif',
    signBg: BRAND.gradient,
    signBorder: 'none',
    signAccent: 'rgba(255,255,255,0.25)',
    signText: '#fff',
    signSub: 'rgba(255,255,255,0.92)',
    signShadow: '0 6px 18px rgba(124,58,237,0.45), inset 0 1px 0 rgba(255,255,255,0.2)',
    crown: '★',
    crownColor: '#fff',
  },
  gold: {
    tileBg: 'linear-gradient(180deg,#1e1a3a 0%,#15122b 100%)',
    tileBorder: 'rgba(251,191,36,0.45)',
    tileHover: '#fbbf24',
    tileShadow: '0 3px 10px rgba(124,58,237,0.25), inset 0 1px 0 rgba(255,255,255,0.08)',
    tileLetter: '#fbbf24',
    tileLetterGlow: '0 0 8px rgba(251,191,36,0.4)',
    tileMeta: 'rgba(255,255,255,0.75)',
    letterFont: 'DM Serif Display,Georgia,serif',
    signBg: 'linear-gradient(180deg,#1e1a3a 0%,#0f0b24 100%)',
    signBorder: '1px solid rgba(251,191,36,0.35)',
    signAccent: 'rgba(251,191,36,0.3)',
    signText: '#fff',
    signSub: '#fbbf24',
    signShadow: '0 6px 18px rgba(124,58,237,0.4), inset 0 1px 0 rgba(255,255,255,0.12), inset 0 -2px 0 rgba(251,191,36,0.3)',
    crown: '♛',
    crownColor: '#fbbf24',
  },
  obsidian: {
    tileBg: 'linear-gradient(180deg,#1a1a22 0%,#0a0a0f 100%)',
    tileBorder: 'rgba(255,255,255,0.2)',
    tileHover: '#fff',
    tileShadow: '0 2px 8px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.06)',
    tileLetter: '#fff',
    tileLetterGlow: '0 0 6px rgba(255,255,255,0.3)',
    tileMeta: 'rgba(255,255,255,0.6)',
    letterFont: 'DM Serif Display,Georgia,serif',
    signBg: 'linear-gradient(180deg,#0a0a0f 0%,#000 100%)',
    signBorder: '1px solid rgba(255,255,255,0.15)',
    signAccent: 'rgba(255,255,255,0.15)',
    signText: '#fff',
    signSub: 'rgba(255,255,255,0.55)',
    signShadow: '0 6px 18px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.08)',
    crown: '◆',
    crownColor: '#fff',
  },
  platinum: {
    tileBg: 'linear-gradient(180deg,#fefdf8 0%,#f5f0e1 100%)',
    tileBorder: '#b38d3f',
    tileHover: '#8b6914',
    tileShadow: '0 3px 10px rgba(179,141,63,0.2), inset 0 1px 0 rgba(255,255,255,0.6)',
    tileLetter: '#8b6914',
    tileLetterGlow: 'none',
    tileMeta: '#8b6914',
    letterFont: 'DM Serif Display,Georgia,serif',
    signBg: 'linear-gradient(180deg,#fefdf8 0%,#ebe2c5 100%)',
    signBorder: '1.5px solid #b38d3f',
    signAccent: 'rgba(139,105,20,0.2)',
    signText: '#4a3810',
    signSub: '#8b6914',
    signShadow: '0 6px 18px rgba(179,141,63,0.25), inset 0 2px 0 rgba(255,255,255,0.7), inset 0 -1.5px 0 rgba(139,105,20,0.18)',
    crown: '♛',
    crownColor: '#8b6914',
  },
};

function useVipTheme() {
  const { tweaks } = useApp();
  const key = tweaks.vipTheme || 'onbrand';
  return VIP_THEMES[key] || VIP_THEMES.onbrand;
}

function FlankBoxTile({ b, onOpenBox, myBoxId, compact=false }) {
  const t = useVipTheme();
  const isFull = b.taken >= b.size;
  const isMine = b.id === myBoxId;
  const clickable = !isFull && !isMine;
  return (
    <button
      onClick={() => clickable && onOpenBox(b)}
      disabled={!clickable}
      title={isMine ? `Your box — ${b.taken}/${b.size}` : isFull ? `Box ${b.letter} · FULL` : `Host Box ${b.letter} · ${b.size - b.taken} seats open`}
      style={{
        position:'relative',width:'100%',
        padding: compact ? '7px 4px' : '8px 6px',
        borderRadius:8,border:'1.5px solid',
        borderColor: isMine ? 'transparent' : clickable ? t.tileBorder : 'var(--border)',
        background: isMine
          ? BRAND.gradient
          : clickable
            ? t.tileBg
            : 'var(--card)',
        cursor: clickable ? 'pointer' : 'default',
        opacity: isFull ? 0.5 : 1,
        textAlign:'center',
        transition:'all 0.15s',
        boxShadow: isMine
          ? '0 6px 18px rgba(124,58,237,0.45)'
          : clickable
            ? t.tileShadow
            : 'none',
      }}
      onMouseEnter={e => { if (clickable) { e.currentTarget.style.transform='scale(1.04)'; e.currentTarget.style.borderColor=t.tileHover; }}}
      onMouseLeave={e => { if (clickable) { e.currentTarget.style.transform='scale(1)'; e.currentTarget.style.borderColor=t.tileBorder; }}}
    >
      {clickable && (
        <span style={{
          position:'absolute',top:3,right:3,
          width:5,height:5,borderRadius:'50%',background:'#10b981',
          boxShadow:'0 0 5px #10b981',
          animation:'apex-avail-blink 1.4s ease-in-out infinite',
        }}/>
      )}
      <div style={{
        fontSize: compact ? 13 : 14,fontWeight:900,letterSpacing:-0.3,lineHeight:1,
        color: isMine ? '#fff' : isFull ? 'var(--mute)' : t.tileLetter,
        fontFamily:t.letterFont,
        textShadow: clickable ? t.tileLetterGlow : 'none',
      }}>{b.letter}</div>
      <div style={{
        fontSize:7.5,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
        color: isMine ? 'rgba(255,255,255,0.9)' : clickable ? t.tileMeta : 'var(--mute)',
        marginTop:3,lineHeight:1,
      }}>
        {isMine ? 'YOURS' : isFull ? 'FULL' : `${b.size-b.taken}/${b.size}`}
      </div>
    </button>
  );
}

// Vertical stack with header; used for left/right flanks
function VipBoxFlankColumn({ boxes, onOpenBox, myBoxId, side='left' }) {
  const isLeft = side === 'left';
  const t = useVipTheme();
  return (
    <div style={{
      display:'flex',flexDirection:'column',gap:6,
      minWidth:0,position:'relative',
      paddingTop:14,
    }}>
      {/* Boxes up top — visually they sit next to the seat rows */}
      <div style={{display:'flex',flexDirection:'column',gap:4}}>
        {boxes.map(b => (
          <FlankBoxTile key={b.id} b={b} onOpenBox={onOpenBox} myBoxId={myBoxId} compact/>
        ))}
      </div>
      {/* ELITE signage — anchored at bottom, aligns with stadium floor */}
      <div style={{
        marginTop:4,
        background:t.signBg,
        borderRadius:9,padding:'9px 3px 10px',
        boxShadow:t.signShadow,
        border:t.signBorder,
        display:'flex',flexDirection:'column',alignItems:'center',gap:5,
        position:'relative',overflow:'hidden',
      }}>
        {/* Subtle shimmer */}
        <div style={{
          position:'absolute',inset:0,
          background:`linear-gradient(115deg,transparent 45%,${t.signAccent} 50%,transparent 55%)`,
          backgroundSize:'200% 100%',
          animation:'apex-shimmer 5s linear infinite',pointerEvents:'none',
        }}/>
        {/* Crown */}
        <div style={{
          fontSize:11,lineHeight:1,color:t.crownColor,
          textShadow:`0 0 8px ${t.crownColor}`,zIndex:1,opacity:0.9,
        }}>{t.crown}</div>
        <div style={{
          fontSize:8,fontWeight:900,letterSpacing:1.6,
          color:t.signText,lineHeight:1.05,
          writingMode:'vertical-rl',
          transform: isLeft ? 'rotate(180deg)' : 'none',
          textOrientation:'mixed',
          textShadow: t.signText === '#fff' ? '0 1px 3px rgba(0,0,0,0.4)' : 'none',
          padding:'4px 0',zIndex:1,
        }}>
          VIP BOX SEATS
        </div>
        <div style={{
          fontSize:6.5,fontWeight:900,letterSpacing:1,
          color:t.signSub,textAlign:'center',zIndex:1,
          padding:'0 2px',lineHeight:1.2,textTransform:'uppercase',
        }}>
          Teams of<br/>4 or more
        </div>
      </div>
    </div>
  );
}

// Horizontal opera-style: 4 corners (L-top, R-top, L-bot, R-bot)
function VipBoxOperaCorners({ boxes, onOpenBox, myBoxId, position }) {
  // position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
  const slice = (() => {
    const half = Math.ceil(boxes.length / 2);
    const left = boxes.slice(0, half);
    const right = boxes.slice(half);
    const stack = position.includes('left') ? left : right;
    const mid = Math.ceil(stack.length / 2);
    return position.includes('top') ? stack.slice(0, mid) : stack.slice(mid);
  })();
  const isTop = position.includes('top');
  const isLeft = position.includes('left');
  return (
    <div style={{
      display:'flex',flexDirection:'column',gap:3,
      padding:'5px 3px',borderRadius:8,
      background:'linear-gradient(180deg,rgba(124,58,237,0.14),rgba(124,58,237,0.04))',
      border:`1.5px solid rgba(124,58,237,0.32)`,
      position:'relative',
    }}>
      {/* Section label only on top-left and top-right */}
      {isTop && (
        <div style={{
          fontSize:7,fontWeight:900,letterSpacing:1,textTransform:'uppercase',
          color:BRAND.purple,textAlign:'center',lineHeight:1.05,
          padding:'2px 0 4px',borderBottom:'1px dashed rgba(124,58,237,0.3)',
          marginBottom:3,
        }}>
          ★ VIP<br/>BOX
        </div>
      )}
      {/* Bottom cap label */}
      {!isTop && (
        <div style={{
          fontSize:6.5,fontWeight:800,letterSpacing:0.8,textTransform:'uppercase',
          color:BRAND.purple,textAlign:'center',lineHeight:1.05,
          padding:'3px 0 2px',borderTop:'1px dashed rgba(124,58,237,0.3)',
          marginTop:3,order:99,
        }}>
          4+<br/>Teams
        </div>
      )}
      {slice.map(b => (
        <FlankBoxTile key={b.id} b={b} onOpenBox={onOpenBox} myBoxId={myBoxId} compact/>
      ))}
    </div>
  );
}

// Banner that tells user what the main seat map is: SOLO SEATS · 1-3 agents
function SoloSeatsLabel({ tone='light' }) {
  const dark = tone === 'dark';
  const ink = dark ? 'rgba(255,255,255,0.95)' : 'var(--ink)';
  const dim = dark ? 'rgba(255,255,255,0.55)' : 'var(--dim)';
  const line = dark ? 'rgba(255,255,255,0.2)' : 'var(--border-strong)';
  return (
    <div style={{
      display:'flex',alignItems:'center',gap:6,margin:'0 0 6px',
      fontSize:8.5,fontWeight:900,letterSpacing:2,textTransform:'uppercase',
      color: dark ? 'rgba(255,255,255,0.7)' : 'var(--mute)',
    }}>
      <span style={{
        display:'inline-block',width:16,height:1.5,
        background:`linear-gradient(90deg,transparent,${line})`,
      }}/>
      <span style={{color:ink}}>Solo Seats</span>
      <span style={{color:dim,letterSpacing:1,fontWeight:700}}>· for 1–3 agents</span>
      <span style={{
        display:'inline-block',flex:1,height:1.5,
        background:`linear-gradient(90deg,${line},transparent)`,
      }}/>
    </div>
  );
}

Object.assign(window, { VipBoxFlankColumn, VipBoxOperaCorners, FlankBoxTile, SoloSeatsLabel });


// ─── DESIGN 1: SUITE — on-brand purple tinted cards w/ glass shimmer ───
function VipBoxRowSuite({ boxes, onOpenBox, myBoxId }) {
  return (
    <div style={{marginBottom:12,position:'relative'}}>
      <VipBoxLabel/>
      <div style={{
        display:'grid',
        gridTemplateColumns:`repeat(${boxes.length},1fr)`,
        gap:5,padding:'2px 2px 4px',
      }}>
        {boxes.map((b) => {
          const isFull = b.taken >= b.size;
          const isMine = b.id === myBoxId;
          const hasOpen = !isFull;
          const clickable = hasOpen && !isMine;
          return (
            <button key={b.id} onClick={() => clickable && onOpenBox(b)} disabled={!clickable}
              title={isMine ? `Your box — ${b.taken}/${b.size}` : isFull ? `Box ${b.letter} · FULL${b.brokerage?` · ${b.brokerage}`:''}` : `Host Box ${b.letter} · ${b.size - b.taken} seats open`}
              style={{
                position:'relative',padding:'11px 4px 9px',
                borderRadius:10,minHeight:54,
                background: isMine
                  ? BRAND.gradient
                  : isFull
                    ? 'var(--break-bg)'
                    : 'linear-gradient(180deg,rgba(124,58,237,0.10),rgba(124,58,237,0.04))',
                border: isMine
                  ? 'none'
                  : isFull
                    ? '1px dashed var(--border-strong)'
                    : `1px solid rgba(124,58,237,0.35)`,
                boxShadow: isMine
                  ? `0 0 0 1.5px ${BRAND.purple}, 0 6px 18px rgba(124,58,237,0.4)`
                  : clickable
                    ? '0 2px 8px rgba(124,58,237,0.08)'
                    : 'none',
                cursor: clickable ? 'pointer' : 'default',
                transition:'transform 0.15s, box-shadow 0.15s',
                textAlign:'center',overflow:'hidden',opacity: isFull ? 0.6 : 1,
              }}
              onMouseEnter={e => { if (clickable) { e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 6px 16px rgba(124,58,237,0.25)'; } }}
              onMouseLeave={e => { if (clickable) { e.currentTarget.style.transform='translateY(0)'; e.currentTarget.style.boxShadow='0 2px 8px rgba(124,58,237,0.08)'; } }}
            >
              {/* Live-dot */}
              {clickable && (
                <span style={{
                  position:'absolute',top:4,right:4,
                  width:5,height:5,borderRadius:'50%',background:'#10b981',
                  boxShadow:'0 0 6px #10b981',
                }}/>
              )}
              <div style={{
                fontSize:13,fontWeight:800,letterSpacing:0.5,
                color: isMine ? '#fff' : isFull ? 'var(--mute)' : BRAND.purple,
                fontFamily:'DM Sans,sans-serif',
              }}>{b.letter}</div>
              <div style={{
                fontSize:8.5,fontWeight:700,
                color: isMine ? 'rgba(255,255,255,0.85)' : 'var(--mute)',
                letterSpacing:0.4,marginTop:2,
                textOverflow:'ellipsis',whiteSpace:'nowrap',overflow:'hidden',padding:'0 2px',
              }}>
                {isMine ? 'YOU' : isFull ? (b.brokerage || 'FULL') : `${b.size-b.taken} open`}
              </div>
            </button>
          );
        })}
      </div>
      <VipBoxHint/>
    </div>
  );
}

// ─── DESIGN 2: RIBBON — one continuous purple ribbon with segment dividers ───
function VipBoxRowRibbon({ boxes, onOpenBox, myBoxId }) {
  return (
    <div style={{marginBottom:12,position:'relative'}}>
      <VipBoxLabel/>
      <div style={{
        display:'flex',borderRadius:12,overflow:'hidden',
        border:'1px solid rgba(124,58,237,0.25)',
        background:'var(--card)',
        boxShadow:'0 4px 16px rgba(124,58,237,0.08)',
      }}>
        {boxes.map((b, i) => {
          const isFull = b.taken >= b.size;
          const isMine = b.id === myBoxId;
          const hasOpen = !isFull;
          const clickable = hasOpen && !isMine;
          const pct = b.taken / b.size;
          return (
            <button key={b.id} onClick={() => clickable && onOpenBox(b)} disabled={!clickable}
              title={isMine ? `Your box — ${b.taken}/${b.size}` : isFull ? `Box ${b.letter} · FULL${b.brokerage?` · ${b.brokerage}`:''}` : `Host Box ${b.letter} · ${b.size - b.taken} seats open`}
              style={{
                position:'relative',flex:1,
                padding:'10px 3px 9px',minHeight:54,border:'none',
                borderLeft: i>0 ? '1px solid var(--border)' : 'none',
                // OPEN = bright purple-tinted, FULL = flat/receded, MINE = filled gradient
                background: isMine
                  ? BRAND.gradient
                  : clickable
                    ? 'linear-gradient(180deg,rgba(124,58,237,0.14),rgba(124,58,237,0.05))'
                    : 'transparent',
                cursor: clickable ? 'pointer' : 'default',
                opacity: isFull ? 0.55 : 1,
                textAlign:'center',overflow:'hidden',
                transition:'background 0.15s, transform 0.15s, opacity 0.15s',
              }}
              onMouseEnter={e => { if (clickable) { e.currentTarget.style.background='linear-gradient(180deg,rgba(124,58,237,0.22),rgba(124,58,237,0.08))'; e.currentTarget.style.transform='translateY(-1px)'; } }}
              onMouseLeave={e => { if (clickable) { e.currentTarget.style.background='linear-gradient(180deg,rgba(124,58,237,0.14),rgba(124,58,237,0.05))'; e.currentTarget.style.transform='translateY(0)'; } }}
            >
              {/* Fill bar at the bottom */}
              {!isMine && (
                <div style={{
                  position:'absolute',left:0,right:0,bottom:0,height:3,
                  background: isFull ? 'var(--border-strong)' : 'var(--break-bg)',
                }}>
                  <div style={{
                    height:'100%',width:`${pct*100}%`,
                    background: BRAND.gradient, transition:'width 0.4s',
                  }}/>
                </div>
              )}
              {/* Pulsing green dot on open boxes */}
              {clickable && (
                <span style={{
                  position:'absolute',top:5,right:5,
                  width:6,height:6,borderRadius:'50%',background:'#10b981',
                  boxShadow:'0 0 6px #10b981',
                  animation:'apex-pulse 1.8s ease-in-out infinite',
                }}/>
              )}
              <div style={{
                fontSize:13,fontWeight:800,letterSpacing:0.5,
                color: isMine ? '#fff' : isFull ? 'var(--mute)' : BRAND.purple,
                fontFamily:'DM Sans,sans-serif',
              }}>{b.letter}</div>
              <div style={{
                fontSize:8.5,fontWeight:800,letterSpacing:0.4,marginTop:2,
                color: isMine ? 'rgba(255,255,255,0.85)' : clickable ? BRAND.purple : 'var(--mute)',
                textOverflow:'ellipsis',whiteSpace:'nowrap',overflow:'hidden',padding:'0 2px',
                textTransform: clickable ? 'uppercase' : 'none',
              }}>
                {isMine ? 'YOU' : isFull ? (b.brokerage || 'Full') : `${b.size-b.taken} open`}
              </div>
            </button>
          );
        })}
      </div>
      <VipBoxHint/>
    </div>
  );
}

// ─── DESIGN 3: EDITORIAL — minimal letter grid; OPEN glows, FULL recedes ───
function VipBoxRowEditorial({ boxes, onOpenBox, myBoxId }) {
  return (
    <div style={{marginBottom:12,position:'relative'}}>
      <VipBoxLabel/>
      <div style={{
        display:'grid',
        gridTemplateColumns:`repeat(${boxes.length},1fr)`,
        gap:1,padding:0,
        background:'var(--border)',
        border:'1px solid var(--border)',borderRadius:10,overflow:'hidden',
      }}>
        {boxes.map((b) => {
          const isFull = b.taken >= b.size;
          const isMine = b.id === myBoxId;
          const hasOpen = !isFull;
          const clickable = hasOpen && !isMine;
          return (
            <button key={b.id} onClick={() => clickable && onOpenBox(b)} disabled={!clickable}
              title={isMine ? `Your box — ${b.taken}/${b.size}` : isFull ? `Box ${b.letter} · FULL${b.brokerage?` · ${b.brokerage}`:''}` : `Host Box ${b.letter} · ${b.size - b.taken} seats open`}
              style={{
                position:'relative',padding:'10px 3px 9px',
                border:'none',minHeight:58,
                // OPEN = subtle purple wash, FULL = neutral card, MINE = gradient
                background: isMine
                  ? BRAND.gradient
                  : clickable
                    ? 'rgba(124,58,237,0.08)'
                    : 'var(--card)',
                cursor: clickable ? 'pointer' : 'default',
                opacity: isFull ? 0.55 : 1,
                textAlign:'center',overflow:'hidden',
                transition:'background 0.15s, opacity 0.15s',
              }}
              onMouseEnter={e => { if (clickable) e.currentTarget.style.background='rgba(124,58,237,0.16)'; }}
              onMouseLeave={e => { if (clickable) e.currentTarget.style.background='rgba(124,58,237,0.08)'; }}
            >
              {/* Pulsing green dot on open */}
              {clickable && (
                <span style={{
                  position:'absolute',top:5,right:5,
                  width:6,height:6,borderRadius:'50%',background:'#10b981',
                  boxShadow:'0 0 6px #10b981',
                  animation:'apex-pulse 1.8s ease-in-out infinite',
                }}/>
              )}
              <div style={{
                fontSize:15,fontWeight:800,letterSpacing:-0.3,
                color: isMine ? '#fff' : isFull ? 'var(--mute)' : BRAND.purple,
                fontFamily:'DM Sans,sans-serif',lineHeight:1,
              }}>{b.letter}</div>
              <div style={{
                fontSize:8,fontWeight:800,letterSpacing:1.5,textTransform:'uppercase',
                color: isMine ? 'rgba(255,255,255,0.85)' : clickable ? BRAND.purple : 'var(--mute)',
                marginTop:5,
                textOverflow:'ellipsis',whiteSpace:'nowrap',overflow:'hidden',padding:'0 2px',
              }}>
                {isMine ? 'Hosting' : isFull ? 'Full' : 'Open'}
              </div>
              <div style={{
                fontSize:8.5,fontWeight:600,
                color: isMine ? 'rgba(255,255,255,0.75)' : clickable ? 'var(--ink)' : 'var(--mute)',
                fontFamily:'ui-monospace,SFMono-Regular,Menlo,monospace',
                marginTop:1,letterSpacing:-0.2,
              }}>
                {isMine ? `${b.taken}/${b.size}` : isFull ? (b.brokerage || 'taken').slice(0,7) : `${b.size-b.taken}/${b.size}`}
              </div>
            </button>
          );
        })}
      </div>
      <VipBoxHint/>
    </div>
  );
}

// -------------------------------------------------------------------
// BoxInviteBanner — ?box=slug-code-size URL landing
// -------------------------------------------------------------------
function BoxInviteBanner() {
  const { updateBooking } = useApp();
  const [invite, setInvite] = useState(null);

  useEffect(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      const box = p.get('box');
      if (!box) return;
      const m = /^([a-z0-9-]+)-([a-z0-9]+)(?:-(\d+))?$/i.exec(box);
      const host = m ? m[1].split('-').map(w => w[0].toUpperCase()+w.slice(1)).join(' ') : 'A teammate';
      const size = m && m[3] ? parseInt(m[3], 10) : 8;
      // Simulate a claimed count: random 2..size-2 so there's visible progress + scarcity
      const claimed = Math.max(1, Math.min(size - 1, Math.floor(size * 0.4) + 1));
      setInvite({ host, size, claimed, session: 'Tue · 4PM PT' });
    } catch(e){}
  }, []);

  if (!invite) return null;

  const save = () => updateBooking({ step: 'time' });
  const pct = Math.round((invite.claimed / invite.size) * 100);

  return (
    <div style={{
      background:'rgba(124,58,237,0.06)',
      border:'1px solid rgba(124,58,237,0.3)',borderRadius:14,
      padding:'14px 16px',marginBottom:16,position:'relative',overflow:'hidden',
    }}>
      <div style={{
        position:'absolute',inset:0,
        background:'linear-gradient(115deg,transparent 40%,rgba(124,58,237,0.09) 50%,transparent 60%)',
        backgroundSize:'200% 100%',animation:'apex-shimmer 6s linear infinite',pointerEvents:'none',
      }}/>
      <div style={{position:'relative',zIndex:1}}>
        <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:10}}>
          <div style={{
            width:38,height:38,borderRadius:'50%',flexShrink:0,
            background:BRAND.gradient,color:'#fff',
            display:'flex',alignItems:'center',justifyContent:'center',
            boxShadow:'0 6px 16px rgba(124,58,237,0.35)',
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="#fff">
              <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/>
            </svg>
          </div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:10,fontWeight:800,letterSpacing:2,textTransform:'uppercase',color:BRAND.purple,marginBottom:2}}>
              ★ You're invited to a VIP Box
            </div>
            <div style={{fontSize:14,fontWeight:700,color:'var(--ink)',lineHeight:1.3}}>
              <strong>{invite.host}</strong> saved you a Row 1 seat · {invite.session}
            </div>
          </div>
        </div>
        {/* Expected-headcount progress */}
        <div style={{marginBottom:10}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:4}}>
            <span style={{fontSize:10.5,fontWeight:700,color:'var(--mute)',letterSpacing:0.3}}>Box fill</span>
            <span style={{fontSize:11.5,fontWeight:800,color:'var(--ink)',letterSpacing:0.3}}>
              {invite.claimed}<span style={{color:'var(--mute)',fontWeight:600}}> of {invite.size} claimed</span>
              <span style={{color:BRAND.purple,fontWeight:800,marginLeft:6}}>· {invite.size - invite.claimed} left</span>
            </span>
          </div>
          <div style={{height:6,background:'var(--card)',borderRadius:3,overflow:'hidden',border:'1px solid var(--border)'}}>
            <div style={{
              height:'100%',width:`${pct}%`,background:BRAND.gradient,
              transition:'width 0.4s',
            }}/>
          </div>
        </div>
        <button onClick={save} style={{
          width:'100%',background:BRAND.gradient,color:'#fff',border:'none',
          borderRadius:10,padding:'11px 14px',
          fontFamily:'inherit',fontSize:12,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',cursor:'pointer',
          boxShadow:'0 8px 22px rgba(124,58,237,0.4)',
        }}>Claim your Row 1 seat →</button>
      </div>
    </div>
  );
}

Object.assign(window, {
  FAKE_BROKERAGES, BOX_LETTERS,
  BoxSeatModal, StandardSeatModal, SizerRow,
  VipBoxRow, VipBoxRowSuite, VipBoxRowRibbon, VipBoxRowEditorial,
  VipBoxLabel, VipBoxHint,
  BoxInviteBanner, InviteTicketPreview, InvitePreviewBoarding, InvitePreviewZoom,
});
