// CONFIRM SCREEN — after lock-in. Referral hook is THE star here (user rated 10/10).

function ConfirmScreen() {
  const { booking, updateBooking } = useApp();
  const [copied, setCopied] = useState(false);
  const vip = booking.vipBox;     // { boxLetter, size, seatCount, hostName, emails, mode, link }
  const std = booking.stdSeat;    // { seatLabel, plusN, emails }
  const isVip = !!vip;
  const isGroup = !!(std && std.plusN > 0);

  const dateStr = useMemo(() => {
    const d = booking.dayDate || new Date();
    const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    const dd = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    return `${dd[d.getDay()]}, ${months[d.getMonth()]} ${d.getDate()}`;
  }, [booking.dayDate]);

  const refToken = useMemo(() => {
    const raw = (booking.phone||'')+'|'+Date.now();
    let h = 0; for (let i = 0; i < raw.length; i++) h = ((h<<5)-h+raw.charCodeAt(i))|0;
    return 'anon_'+Math.abs(h).toString(36);
  }, [booking.phone]);

  const shareUrl = `https://apexopsystems.com/welcome?ref=${refToken}`;
  const shareMsg = `I just booked a private walkthrough of Apex — it's an AI built for real estate agents and it's wild. I want you on this call with me. Book the same session and we both lock in $97/mo for life (after July 7 it's $997/mo). ${shareUrl}`;

  const copyLink = () => {
    navigator.clipboard?.writeText(shareUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    }).catch(()=>{});
  };

  return (
    <div style={{
      position:'fixed',inset:0,zIndex:101,background:'var(--bg)',
      padding:'32px 20px calc(32px + env(safe-area-inset-bottom,0px))',
      overflowY:'auto',animation:'apex-slide-up 0.5s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{maxWidth:560,margin:'0 auto',textAlign:'center'}}>

        <div style={{
          width:88,height:88,margin:'0 auto 20px',borderRadius:'50%',
          background:BRAND.gradient,color:'#fff',
          display:'flex',alignItems:'center',justifyContent:'center',
          fontSize:40,fontWeight:900,
          boxShadow:'0 12px 48px rgba(124,58,237,0.35)',
          animation:'apex-glow-pulse 3s ease-in-out infinite',
        }}>✓</div>

        <h2 style={{
          fontSize:'clamp(30px,5vw,44px)',fontWeight:700,color:'var(--ink)',
          marginBottom:10,letterSpacing:'-0.8px',
        }}>{isVip
          ? <>Box {vip.boxLetter} is <em style={{
              fontStyle:'normal',background:BRAND.gradient,
              WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
            }}>yours.</em></>
          : isGroup
            ? <>All {std.plusN + 1} seats <em style={{
                fontStyle:'normal',background:BRAND.gradient,
                WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
              }}>locked in.</em></>
            : <>You're <em style={{
                fontStyle:'normal',background:BRAND.gradient,
                WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
              }}>locked in.</em></>}
        </h2>
        <p style={{fontSize:15,color:'var(--mute)',marginBottom:28,lineHeight:1.5}}>
          {isVip
            ? <>Row 1 · {vip.size} seats held under your name. We'll email the Zoom link to <strong style={{color:'var(--ink)'}}>you</strong> and to everyone on your list.</>
            : isGroup
              ? <>Your team of {std.plusN + 1} is going to this walkthrough together.</>
              : <>Check your texts — Zoom link is on the way.</>}
        </p>

        {/* VIP-only: Team invite tracker */}
        {isVip && (
          <div style={{
            background:'linear-gradient(135deg,rgba(251,191,36,0.1),rgba(124,58,237,0.08))',
            border:'1px solid rgba(251,191,36,0.35)',borderRadius:16,
            padding:'18px 18px 16px',marginBottom:18,textAlign:'left',
          }}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
              <div style={{
                fontSize:10,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',color:'#b45309',
              }}>★ Your VIP Box</div>
              <div style={{
                fontSize:11,fontWeight:800,color:'var(--ink)',letterSpacing:0.3,
              }}>Box {vip.boxLetter} · Row 1</div>
            </div>

            {/* Seat fill bar */}
            <div style={{marginBottom:14}}>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:4,fontSize:11}}>
                <span style={{fontWeight:700,color:'var(--ink)'}}>
                  {vip.seatCount} <span style={{color:'var(--mute)',fontWeight:600}}>of {vip.size} locked</span>
                </span>
                <span style={{fontWeight:700,color:'#b45309'}}>
                  {vip.size - vip.seatCount} pending
                </span>
              </div>
              <div style={{height:8,background:'var(--break-bg)',borderRadius:4,overflow:'hidden',border:'1px solid var(--border)'}}>
                <div style={{
                  height:'100%',width:`${(vip.seatCount/vip.size)*100}%`,background:BRAND.gradient,
                  transition:'width 0.6s',
                }}/>
              </div>
            </div>

            {/* Seat list */}
            <div style={{marginBottom: vip.mode==='link' ? 12 : 4}}>
              <div style={{fontSize:10,fontWeight:800,letterSpacing:1.8,textTransform:'uppercase',color:'var(--mute)',marginBottom:8}}>
                Who's in
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:6}}>
                {/* You */}
                <div style={{
                  display:'flex',alignItems:'center',gap:10,padding:'8px 10px',
                  background:'var(--card)',border:'1px solid var(--border)',borderRadius:8,
                }}>
                  <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,
                  }}>{(vip.hostName||'Y')[0]}</div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12.5,fontWeight:700,color:'var(--ink)',letterSpacing:-0.1}}>
                      {vip.hostName} <span style={{color:BRAND.purple,fontSize:10,fontWeight:700,letterSpacing:1,marginLeft:4}}>HOST</span>
                    </div>
                  </div>
                  <span style={{
                    fontSize:9,fontWeight:800,letterSpacing:1.5,color:'#10b981',
                    background:'rgba(16,185,129,0.12)',padding:'3px 7px',borderRadius:999,
                  }}>✓ LOCKED</span>
                </div>
                {/* Invitees */}
                {vip.mode === 'emails' && (vip.emails || []).map((e, i) => (
                  <div key={i} style={{
                    display:'flex',alignItems:'center',gap:10,padding:'8px 10px',
                    background:'var(--card)',border:'1px dashed var(--border-strong)',borderRadius:8,
                  }}>
                    <div style={{
                      width:26,height:26,borderRadius:'50%',flexShrink:0,
                      background:'var(--break-bg)',border:'1px solid var(--border-strong)',
                      display:'flex',alignItems:'center',justifyContent:'center',
                      fontSize:11,fontWeight:800,color:'var(--mute)',
                    }}>{(e||'?')[0].toUpperCase()}</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:12,fontWeight:600,color:'var(--ink)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{e}</div>
                      <div style={{fontSize:9.5,color:'var(--mute)',marginTop:1,letterSpacing:0.3}}>Zoom invite sent</div>
                    </div>
                    <span style={{
                      fontSize:9,fontWeight:800,letterSpacing:1.5,color:'#b45309',
                      background:'rgba(180,83,9,0.1)',padding:'3px 7px',borderRadius:999,
                    }}>PENDING</span>
                  </div>
                ))}
                {vip.mode === 'link' && Array.from({length: Math.max(0, vip.size - 1)}).map((_, i) => (
                  <div key={i} style={{
                    display:'flex',alignItems:'center',gap:10,padding:'8px 10px',
                    background:'var(--card)',border:'1px dashed var(--border-strong)',borderRadius:8,opacity:0.85,
                  }}>
                    <div style={{
                      width:26,height:26,borderRadius:'50%',flexShrink:0,
                      background:'var(--break-bg)',border:'1px dashed var(--border-strong)',
                      display:'flex',alignItems:'center',justifyContent:'center',
                      fontSize:12,color:'var(--mute)',
                    }}>?</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{fontSize:12,fontWeight:600,color:'var(--mute)',letterSpacing:0.1}}>Open — waiting for teammate</div>
                    </div>
                    <span style={{
                      fontSize:9,fontWeight:800,letterSpacing:1.5,color:'var(--mute)',
                      background:'var(--break-bg)',padding:'3px 7px',borderRadius:999,
                    }}>OPEN</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Link-mode share button */}
            {vip.mode === 'link' && vip.link && (
              <button onClick={() => {
                try { navigator.clipboard.writeText('https://' + vip.link); } catch(e){}
              }} style={{
                width:'100%',padding:'10px 12px',
                background:BRAND.gradient,color:'#fff',border:'none',borderRadius:10,
                fontFamily:'inherit',fontSize:11.5,fontWeight:800,letterSpacing:1.2,textTransform:'uppercase',
                cursor:'pointer',boxShadow:'0 6px 18px rgba(124,58,237,0.3)',
              }}>Copy Box Link · Send to Team</button>
            )}
          </div>
        )}

        {/* Group standard-seat invitee list */}
        {isGroup && (
          <div style={{
            background:'var(--card)',border:'1px solid var(--border)',borderRadius:16,
            padding:'16px 18px',marginBottom:18,textAlign:'left',
          }}>
            <div style={{fontSize:10,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',color:'var(--mute)',marginBottom:10}}>
              Your team
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              <div style={{fontSize:12.5,fontWeight:700,color:'var(--ink)',display:'flex',alignItems:'center',gap:8}}>
                <span style={{width:8,height:8,borderRadius:'50%',background:'#10b981'}}/>
                You <span style={{color:'var(--mute)',fontWeight:600,marginLeft:4}}>· seat {std.seatLabel}</span>
              </div>
              {(std.emails||[]).map((e,i) => (
                <div key={i} style={{fontSize:12,color:'var(--mute)',display:'flex',alignItems:'center',gap:8}}>
                  <span style={{width:8,height:8,borderRadius:'50%',background:'#b45309'}}/>
                  {e} <span style={{color:'var(--mute)',fontSize:10,marginLeft:4}}>· Zoom invite sent</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{
          background:'var(--card)',border:'1px solid var(--border)',
          borderRadius:16,padding:22,marginBottom:22,textAlign:'left',
          boxShadow:'var(--shadow)',
        }}>
          {[
            ['Date', dateStr],
            ['Time', booking.time],
            ['Format', 'Live on Zoom'],
            ['Your rate', '$97/mo for life'],
          ].map(([label, val], i, arr) => (
            <div key={label} style={{
              display:'flex',justifyContent:'space-between',alignItems:'center',
              padding:'10px 0',
              borderBottom: i < arr.length - 1 ? '1px solid var(--border)' : 'none',
            }}>
              <span style={{fontSize:11,fontWeight:700,letterSpacing:2,textTransform:'uppercase',color:'var(--mute)'}}>{label}</span>
              <span style={{fontSize:14,fontWeight:700,color:'var(--ink)'}}>{val}</span>
            </div>
          ))}
        </div>

        {/* THE REFERRAL BLOCK — priority over calendar */}
        <div style={{
          background:'linear-gradient(135deg,rgba(124,58,237,0.08),rgba(59,130,246,0.06))',
          border:'1.5px dashed rgba(124,58,237,0.35)',
          borderRadius:16,padding:22,marginBottom:20,textAlign:'left',
        }}>
          <div style={{
            display:'inline-block',fontSize:10,fontWeight:800,letterSpacing:2.5,textTransform:'uppercase',
            background:BRAND.gradient,color:'#fff',padding:'5px 12px',borderRadius:999,marginBottom:12,
            boxShadow:'0 4px 12px rgba(124,58,237,0.25)',
          }}>★ Founder Rate Unlocked</div>

          <h3 style={{
            fontSize:20,fontWeight:700,color:'var(--ink)',lineHeight:1.25,
            letterSpacing:'-0.4px',marginBottom:8,
          }}>{isVip
            ? <>Who else in your <em style={{
                fontStyle:'normal',background:BRAND.gradient,
                WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
              }}>market</em> needs this?</>
            : <>Who else needs to be on <em style={{
                fontStyle:'normal',background:BRAND.gradient,
                WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text',
              }}>this call</em>?</>}
          </h3>

          <p style={{fontSize:13,color:'var(--mute)',marginBottom:12,lineHeight:1.55}}>
            {isVip
              ? <>Your box is locked with your team. Now send this to <strong style={{color:'var(--ink)',fontWeight:700}}>2 agents outside your brokerage</strong> — your top competitor, a friend across town. When they book their own session, <strong style={{color:'var(--ink)',fontWeight:700}}>they lock $97/mo for life too</strong>.</>
              : <>Don't watch this alone. Invite <strong style={{color:'var(--ink)',fontWeight:700}}>2 agents</strong> you'd build with — your teammate, your broker, your top competitor. When they book the same session, <strong style={{color:'var(--ink)',fontWeight:700}}>all three of you lock in $97/mo for life</strong>.</>}
          </p>
          <p style={{
            marginBottom:16,padding:'10px 12px',
            background:'rgba(239,68,68,0.05)',borderLeft:'3px solid rgba(239,68,68,0.4)',
            borderRadius:'0 8px 8px 0',color:'var(--ink)',fontStyle:'italic',
            fontSize:12.5,lineHeight:1.55,
          }}>After July 7 they'll pay $997/mo — and wonder why they weren't on that call with you.</p>

          <a href={`sms:?&body=${encodeURIComponent(shareMsg)}`}
            style={{
              display:'flex',width:'100%',
              background:BRAND.gradient,color:'#fff',
              border:'none',borderRadius:12,padding:'16px 20px',marginBottom:10,
              fontSize:15,fontWeight:800,letterSpacing:0.5,
              alignItems:'center',justifyContent:'center',gap:10,
              boxShadow:'0 8px 24px rgba(124,58,237,0.35)',
              textDecoration:'none',
            }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
            </svg>
            Text it to 2 agents now
            <span style={{width:22,height:22,borderRadius:'50%',background:'rgba(255,255,255,0.22)',
              display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:13}}>→</span>
          </a>

          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}}>
            <a href={`https://wa.me/?text=${encodeURIComponent(shareMsg)}`} target="_blank" rel="noopener" style={btnSecondary()}>WhatsApp</a>
            <button onClick={copyLink} style={{...btnSecondary(), background: copied?'rgba(16,185,129,0.1)':undefined, borderColor: copied?'#10b981':undefined, color:copied?'#10b981':undefined}}>
              {copied ? 'Copied!' : 'Copy Link'}
            </button>
            <a href={`mailto:?subject=${encodeURIComponent('You need to see this — Apex private webinar')}&body=${encodeURIComponent(shareMsg)}`} style={btnSecondary()}>Email</a>
          </div>

          <p style={{marginTop:14,fontSize:12,color:'var(--mute)',lineHeight:1.5,fontStyle:'italic'}}>
            P.S. You don't need to explain Apex. Send them the link — the walkthrough does the talking.
          </p>
        </div>

        <div style={{fontSize:11,fontWeight:700,letterSpacing:2.5,textTransform:'uppercase',color:'var(--mute)',margin:'28px 0 10px'}}>
          Add to calendar
        </div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8}}>
          {['Google','Apple','Outlook'].map(n => (
            <button key={n} style={btnSecondary()}>{n}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

function btnSecondary() {
  return {
    background:'var(--card)',
    border:'1.5px solid var(--border)',
    borderRadius:12,padding:'12px 8px',
    fontFamily:'inherit',fontSize:12,fontWeight:700,letterSpacing:1,
    color:'var(--ink)',textDecoration:'none',cursor:'pointer',
    display:'flex',alignItems:'center',justifyContent:'center',
    transition:'all 0.2s',
  };
}

Object.assign(window, { ConfirmScreen });
