function IdentityGate(props){
  var onIdentified=props.onIdentified;
  var params=new URLSearchParams(window.location.search);
  var eventId=params.get('event')||'';

  var stored=null;
  try{stored=JSON.parse(localStorage.getItem('lineconic_guest'))}catch(e){}

  var[email,setEmail]=useState(stored&&stored.email?stored.email:'');
  var[firstName,setFirstName]=useState('');
  var[needsName,setNeedsName]=useState(false);
  var[busy,setBusy]=useState(false);
  var[error,setError]=useState(null);
  var[welcomeMsg,setWelcomeMsg]=useState(null);
  var[marketingConsent,setMarketingConsent]=useState(false);

  // Auto-identify if we have a stored guest for this event
  var didAutoRef=useRef(false);
  useEffect(function(){
    if(stored&&stored.guestId&&stored.eventId===eventId&&!didAutoRef.current){
      didAutoRef.current=true;
      onIdentified(stored);
    }
  },[]);

  function anonEntry(){
    var fallback={guestId:'anon_'+Math.random().toString(36).substr(2,9),email:email.trim(),firstName:firstName.trim()||null,showCount:1,eventId:eventId||'walk-in'};
    localStorage.setItem('lineconic_guest',JSON.stringify(fallback));
    onIdentified(fallback);
  }

  function submit(e){
    if(e)e.preventDefault();
    if(busy)return;
    if(!email.trim())return;
    setBusy(true);setError(null);
    // No event ID — skip API, allow anonymous entry with friendly message
    if(!eventId){
      setBusy(false);
      var name=email.trim().split('@')[0];
      setWelcomeMsg({name:name,count:1});
      setTimeout(function(){anonEntry()},1200);
      return;
    }
    var body={email:email.trim(),eventId:eventId};
    if(needsName&&firstName.trim())body.firstName=firstName.trim();
    if(marketingConsent)body.marketingConsent=true;
    fetch('https://meetcircuit.xyz/api/lineconic/identify',{
      method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)
    }).then(function(r){return r.json()}).then(function(data){
      setBusy(false);
      if(data.guestId){
        var guest={guestId:data.guestId,email:email.trim(),firstName:data.firstName||firstName.trim()||null,showCount:data.showCount||1,eventId:eventId,marketingConsent:marketingConsent};
        localStorage.setItem('lineconic_guest',JSON.stringify(guest));
        var name=guest.firstName||email.trim().split('@')[0];
        var count=guest.showCount||1;
        setWelcomeMsg({name:name,count:count});
        setTimeout(function(){onIdentified(guest)},1200);
      }else if(data.needsName||data.status==='not_found'){
        setNeedsName(true);
      }else{
        setError(data.error||'Something went wrong');
      }
    }).catch(function(){
      setBusy(false);
      anonEntry();
    });
  }

  if(welcomeMsg){
    return React.createElement('div',{className:'id-gate',style:{background:'var(--void)',color:'var(--light)'}},
      React.createElement('div',{className:'welcome'},
        React.createElement('h2',null,'Welcome back, '+welcomeMsg.name+'.'),
        React.createElement('p',null,'Show #'+welcomeMsg.count+'.')
      )
    );
  }

  return React.createElement('div',{className:'id-gate',style:{background:'var(--void)',color:'var(--light)'}},
    React.createElement('h2',null,'YOU\'RE IN'),
    React.createElement('p',null,'Enter your email to check in.'),
    React.createElement('form',{onSubmit:submit,style:{display:'flex',flexDirection:'column',alignItems:'center',gap:'var(--space-03)',width:'100%'}},
      React.createElement('input',{type:'email',placeholder:'you@email.com',value:email,onChange:function(e){setEmail(e.target.value)},autoFocus:true,required:true}),
      needsName&&React.createElement('div',{className:'name-reveal'},
        React.createElement('input',{type:'text',placeholder:'First name',value:firstName,onChange:function(e){setFirstName(e.target.value)},autoFocus:true,required:true})
      ),
      React.createElement('label',{style:{display:'flex',alignItems:'center',gap:8,cursor:'pointer',marginTop:4}},
        React.createElement('input',{type:'checkbox',checked:marketingConsent,onChange:function(e){setMarketingConsent(e.target.checked)},style:{accentColor:'#FF007F',width:16,height:16}}),
        React.createElement('span',{style:{fontFamily:"'Space Mono',monospace",fontSize:9,color:'rgba(255,255,255,0.35)',letterSpacing:'.06em',textTransform:'uppercase'}},'KEEP ME IN THE LOOP')
      ),
      React.createElement('button',{type:'submit',disabled:busy||!email.trim()||(needsName&&!firstName.trim())},busy?'CHECKING...':'LET\'S GO'),
      error&&React.createElement('div',{className:'status-line'},error),
      !eventId&&React.createElement('p',{style:{fontSize:'0.7rem',opacity:0.4,marginTop:'var(--space-03)'}},'No event code? Scan the QR at the venue.')
    )
  );
}

// ═══════════════════════════════════════
// PRE-SHOW RED FLAG SUBMISSION
// ═══════════════════════════════════════
function RedFlagPreShow(props) {
  var source = props.source || 'pre-show';
  var params = new URLSearchParams(window.location.search);
  var showId = params.get('show') || '';
  var [guestIdentity, setGuestIdentity] = useState(null);
  var [text, setText] = useState('');
  var [submitted, setSubmitted] = useState(false);
  var [busy, setBusy] = useState(false);
  var MAX_CHARS = 100;

  if (!guestIdentity) {
    return React.createElement(IdentityGate, { onIdentified: setGuestIdentity });
  }

  function handleSubmit(e) {
    if (e) e.preventDefault();
    var trimmed = text.trim();
    if (!trimmed || !showId || busy) return;
    setBusy(true);

    if (fbdb) {
      var ref = fbdb.ref('live/' + showId + '/redflags').push();
      ref.set({
        text: trimmed.slice(0, MAX_CHARS),
        guestName: guestIdentity.firstName || '',
        guestEmail: guestIdentity.email || '',
        source: source,
        submittedAt: firebase.database.ServerValue.TIMESTAMP
      }).then(function() {
        setSubmitted(true);
        setBusy(false);
      }).catch(function() {
        setBusy(false);
      });
    }
  }

  if (submitted) {
    return React.createElement('div', { className: 'rf-preshow' },
      React.createElement('div', { className: 'done' },
        React.createElement('h2', null, 'submitted.'),
        React.createElement('p', null, 'see you there.')
      )
    );
  }

  return React.createElement('div', { className: 'rf-preshow' },
    React.createElement('h2', null, 'WRITE YOUR RED FLAG'),
    React.createElement('p', null, 'we will use it against you.'),
    React.createElement('form', { onSubmit: handleSubmit, style: { display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' } },
      React.createElement('input', {
        type: 'text',
        value: text,
        onChange: function(e) { if (e.target.value.length <= MAX_CHARS) setText(e.target.value); },
        placeholder: "e.g. I still google my ex's new girlfriend",
        maxLength: MAX_CHARS,
        autoFocus: true
      }),
      React.createElement('div', { className: 'char-count' + (text.length > MAX_CHARS - 10 ? ' warn' : '') },
        text.length + ' / ' + MAX_CHARS
      ),
      React.createElement('button', { type: 'submit', disabled: busy || !text.trim() },
        busy ? 'SUBMITTING...' : 'DROP IT IN THE BOWL'
      )
    )
  );
}

// COMPANION VIEW (/play) — phone experience for audience members
// ═══════════════════════════════════════
function CompanionView(){
  const[guestIdentity,setGuestIdentity]=useState(null);
  if(!guestIdentity)return React.createElement(IdentityGate,{onIdentified:setGuestIdentity});
  return React.createElement(CompanionInner,{guestIdentity:guestIdentity});
}

function CompanionInner(props){
  var guestIdentity=props.guestIdentity;

  const Q_TYPES=['source_q','acronym_q','hotseat_prompt'];
  const END_TYPES=['endcard','last_line'];

  const[connected,setConnected]=useState(false);
  const[online,setOnline]=useState(true);
  // Firebase exposes .info/connected for the actual socket state. Reflect it so guests
  // see when the connection drops mid-show (their phone slept, network died, etc).
  useEffect(function(){
    if(!fbdb)return;
    var r=fbdb.ref('.info/connected');
    var h=function(snap){setOnline(!!snap.val())};
    r.on('value',h);
    return function(){r.off('value',h)};
  },[]);
  const[showId,setShowId]=useState(null);
  const[companion,setCompanion]=useState(null);
  const[slideIdx,setSlideIdx]=useState(-1);
  const[doaTopic,setDoaTopic]=useState(null);
  const[doaVoted,setDoaVoted]=useState(null);
  const[doaData,setDoaData]=useState({dead:0,alive:0});
  const[answered,setAnswered]=useState(null);
  const[showScorecard,setShowScorecard]=React.useState(false);
  const[roomAverage,setRoomAverage]=React.useState(null);
  const[teamScores,setTeamScores]=React.useState({cyan:0,pink:0});
  var canvasRef=React.useRef(null);
  var[shareVisible,setShareVisible]=React.useState(true);

  // Personal stats — persisted to localStorage, keyed by guestId
  const[stats,setStats]=useState(function(){
    try{var s=JSON.parse(localStorage.getItem('lineconic_companion'));if(s&&s.playerId)return s}catch(e){}
    return{playerId:guestIdentity.guestId,knewIt:0,noClue:0,roundsSeen:[],showId:null}
  });
  useEffect(function(){localStorage.setItem('lineconic_companion',JSON.stringify(stats))},[stats]);

  // Get active show ID + register presence
  useEffect(function(){
    if(!fbdb)return;
    var presRef=null;
    var ref=fbdb.ref('active_show');
    ref.on('value',function(snap){
      var id=snap.val();
      if(id){setShowId(id);setConnected(true);
        // Reset stats if show changed
        setStats(function(prev){if(prev.showId&&prev.showId!==id)return{playerId:prev.playerId,knewIt:0,noClue:0,roundsSeen:[],showId:id};return{...prev,showId:id}});
        // Register presence
        setStats(function(prev){
          if(presRef)presRef.off();
          presRef=fbdb.ref('live/'+id+'/companions/'+prev.playerId);
          presRef.set({ts:Date.now()});
          presRef.onDisconnect().remove();
          return prev;
        });
      }
    });
    return function(){ref.off();if(presRef){presRef.remove();presRef.off()}};
  },[]);

  // Listen to live state for companion metadata
  useEffect(function(){
    if(!fbdb||!showId)return;
    var ref=fbdb.ref('live/'+showId+'/state');
    ref.on('value',function(snap){
      var d=snap.val();if(!d)return;
      if(d.companion)setCompanion(d.companion);
      if(d.scores)setTeamScores({cyan:d.scores[0]||0,pink:d.scores[1]||0});
      if(d.showName)localStorage.setItem('lc_show_name',d.showName);
      if(d.showDate)localStorage.setItem('lc_show_date',d.showDate);
      if(d.slide!==undefined){
        setSlideIdx(d.slide);
        // Reset answered state when slide changes
        setAnswered(function(prev){return prev});
      }
    });
    return function(){ref.off()};
  },[showId]);

  // Listen for room average
  React.useEffect(function(){
    if(!showId) return;
    var ref = fbdb.ref('live/'+showId+'/roomAverage');
    var handler = ref.on('value', function(snap){
      var val = snap.val();
      if(val !== null) setRoomAverage(val);
    });
    return function(){ ref.off('value', handler); };
  }, [showId]);

  // Reset answered when slide changes
  const prevSlideRef=useRef(-1);
  useEffect(function(){
    if(slideIdx!==prevSlideRef.current){setAnswered(null);prevSlideRef.current=slideIdx}
  },[slideIdx]);

  // Track rounds seen
  useEffect(function(){
    if(companion&&companion.section&&stats.roundsSeen.indexOf(companion.section)===-1){
      setStats(function(prev){return{...prev,roundsSeen:[...prev.roundsSeen,companion.section]}})
    }
  },[companion]);

  // DOA topic listener
  useEffect(function(){
    if(!fbdb)return;
    var ref=fbdb.ref('currentTopic');
    ref.on('value',function(snap){var t=snap.val();setDoaTopic(t);setDoaVoted(null);setDoaData({dead:0,alive:0})});
    return function(){ref.off()};
  },[]);

  // DOA vote data listener
  useEffect(function(){
    if(!fbdb||!doaTopic)return;
    var key=doaTopic.replace(/[^a-zA-Z0-9]/g,'_');
    var ref=fbdb.ref('votes/'+key);
    ref.on('value',function(snap){var v=snap.val()||{};setDoaData({dead:v.dead||0,alive:v.alive||0})});
    return function(){ref.off()};
  },[doaTopic]);

  // Score Card: auto-hide share button after 5s
  React.useEffect(function(){
    if(!showScorecard) return;
    var t = setTimeout(function(){ setShareVisible(false); }, 5000);
    return function(){ clearTimeout(t); };
  }, [showScorecard]);

  // Score Card: redraw canvas when visible or roomAverage changes
  React.useEffect(function(){
    if(!showScorecard || !canvasRef.current) return;
    var showConfig = {
      scores: teamScores,
      showName: localStorage.getItem('lc_show_name') || '',
      date: localStorage.getItem('lc_show_date') || new Date().toISOString().split('T')[0]
    };
    drawScoreCard(canvasRef.current, stats, roomAverage, showConfig, guestIdentity);
  }, [showScorecard, roomAverage, teamScores]);

  function doDoaVote(side){
    if(doaVoted||!doaTopic)return;
    setDoaVoted(side);
    var key=doaTopic.replace(/[^a-zA-Z0-9]/g,'_');
    if(fbdb)fbdb.ref('votes/'+key+'/'+side).transaction(function(c){return(c||0)+1});
    if(navigator.vibrate)navigator.vibrate(30);
  }

  function handleAnswer(type){
    if(answered)return;
    setAnswered(type);
    setStats(function(prev){
      var next={...prev};
      if(type==='knew')next.knewIt=prev.knewIt+1;
      else next.noClue=prev.noClue+1;
      return next;
    });
    // Write response to Firebase for crowd temperature
    if(fbdb&&showId&&companion&&companion.slideId){
      var field=type==='knew'?'knewIt':'noClue';
      var respRef=fbdb.ref('live/'+showId+'/responses/'+companion.slideId+'/'+field);
      respRef.transaction(function(current){return(current||0)+1});
      // Per-guest response for Circuit
      var answer=type==='knew'?'knew_it':'no_clue';
      fbdb.ref('live/'+showId+'/guest_responses/'+guestIdentity.guestId+'/'+companion.slideId).set(answer);
    }
    if(navigator.vibrate)navigator.vibrate(20);
  }

  // Determine screen
  var screen='lobby';
  if(companion){
    if(END_TYPES.indexOf(companion.slideType)!==-1){
      screen='receipt';
      if(!showScorecard){
        setTimeout(function(){ setShowScorecard(true); },500);
      }
    }
    else if(Q_TYPES.indexOf(companion.slideType)!==-1)screen='question';
  }
  if(doaTopic&&companion&&(companion.slideType==='doa_vote'||companion.slideType==='doa_verdict_dead'||companion.slideType==='doa_verdict_alive'))screen='doa';

  // Shared styles
  var base={background:'#000',color:'#fff',fontFamily:"'Neue Haas Grotesk Display Pro','Impact',sans-serif",minHeight:'100vh',display:'flex',flexDirection:'column',alignItems:'center',position:'relative',overflow:'hidden'};
  var mono={fontFamily:"'Space Mono',monospace"};

  // Connection status dot — reflects active_show subscription AND the underlying
  // Firebase socket. Big text version used in lobby; small corner version for gameplay.
  var live=connected&&online;
  function StatusDot(){
    return React.createElement('div',{style:{display:'flex',alignItems:'center',gap:6,...mono,fontSize:10,color:'rgba(255,255,255,0.4)',letterSpacing:'.12em',textTransform:'uppercase',marginBottom:8}},
      React.createElement('div',{style:{width:6,height:6,borderRadius:'50%',background:live?'#00FF88':'#FF007F',boxShadow:live?'0 0 8px rgba(0,255,136,0.6)':'0 0 8px rgba(255,0,127,0.6)'}}),
      live?'CONNECTED':(online?'CONNECTING...':'OFFLINE')
    );
  }
  // Tiny corner indicator used on every gameplay screen so the guest sees if their
  // phone has dropped the connection mid-show.
  var cornerDot=React.createElement('div',{style:{position:'fixed',top:10,right:10,zIndex:50,width:8,height:8,borderRadius:'50%',background:live?'#00FF88':'#FF007F',boxShadow:live?'0 0 6px rgba(0,255,136,0.6)':'0 0 6px rgba(255,0,127,0.6)',pointerEvents:'none'},title:live?'CONNECTED':'OFFLINE'});

  // LOBBY SCREEN
  if(screen==='lobby'){
    return React.createElement('div',{style:base},
      React.createElement('div',{style:{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'40px 24px',textAlign:'center',width:'100%',maxWidth:420}},
        React.createElement('div',{style:{fontSize:80,color:'var(--signal)',textShadow:'0 0 20px rgba(255,0,127,.8),0 0 60px rgba(255,0,127,.3)',marginBottom:12,letterSpacing:'.08em'}},'L'),
        React.createElement(StatusDot),
        companion&&companion.section?
          React.createElement('div',{style:{...mono,fontSize:11,color:'rgba(255,255,255,0.5)',letterSpacing:'.1em',textTransform:'uppercase',marginBottom:16,padding:'6px 16px',border:'1px solid rgba(255,255,255,0.1)',borderRadius:4}},companion.section):
          React.createElement('div',{style:{...mono,fontSize:12,color:'rgba(255,255,255,0.25)',letterSpacing:'.08em',marginBottom:16}},'WAITING FOR SHOW...'),
        React.createElement('div',{style:{...mono,fontSize:10,color:'rgba(255,255,255,0.2)',letterSpacing:'.1em',marginTop:32}},'PLAY ALONG \u2022 SHARE'),
        React.createElement('a',{href:'https://lineconic.com?utm_source=live-app&utm_medium=web&utm_campaign=show&utm_content=receipt',target:'_blank',rel:'noopener',style:{...mono,fontSize:9,color:'rgba(255,255,255,0.12)',letterSpacing:'.1em',marginTop:16,textDecoration:'none',textTransform:'uppercase',transition:'color .15s'},onMouseOver:function(e){e.target.style.color='#FF007F'},onMouseOut:function(e){e.target.style.color='rgba(255,255,255,0.12)'}},'GET THE DECK \u2192 LINECONIC.COM')
      )
    );
  }

  // QUESTION SCREEN
  if(screen==='question'){
    var hasAnswer=companion&&companion.answer&&companion.answerRevealed;
    return React.createElement('div',{style:base},
      cornerDot,
      React.createElement('div',{style:{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'32px 24px',textAlign:'center',width:'100%',maxWidth:420}},
        companion.category&&React.createElement('div',{style:{...mono,fontSize:10,color:'var(--cyan)',letterSpacing:'.15em',textTransform:'uppercase',marginBottom:16,padding:'4px 12px',border:'1px solid rgba(0,255,255,0.2)',borderRadius:3}},companion.category),
        companion.points&&React.createElement('div',{style:{...mono,fontSize:10,color:'var(--gold)',letterSpacing:'.1em',marginBottom:12}},companion.points+' PTS'),
        React.createElement('div',{style:{fontSize:'clamp(24px,7vw,40px)',textTransform:'uppercase',letterSpacing:'.03em',lineHeight:1.15,marginBottom:32,color:'#fff',textShadow:'0 0 10px rgba(255,255,255,.3)'}},companion.question||'...'),
        !answered&&!hasAnswer&&React.createElement('div',{style:{display:'flex',gap:12,width:'100%',marginBottom:24}},
          React.createElement('button',{onClick:function(){handleAnswer('knew')},style:{flex:1,padding:'18px 12px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:18,letterSpacing:'.06em',cursor:'pointer',textTransform:'uppercase',background:'transparent',color:'var(--cyan)',border:'2px solid var(--cyan)',boxShadow:'0 0 12px rgba(0,255,255,.2)'}},'I KNEW IT'),
          React.createElement('button',{onClick:function(){handleAnswer('nope')},style:{flex:1,padding:'18px 12px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:18,letterSpacing:'.06em',cursor:'pointer',textTransform:'uppercase',background:'transparent',color:'var(--signal)',border:'2px solid var(--signal)',boxShadow:'0 0 12px rgba(255,0,127,.2)'}},'NO CLUE')
        ),
        answered&&!hasAnswer&&React.createElement('div',{style:{...mono,fontSize:12,color:'rgba(255,255,255,0.4)',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:24}},answered==='knew'?'LET\'S SEE...':'WAIT FOR IT...'),
        hasAnswer&&React.createElement('div',{style:{padding:'16px 24px',border:'2px solid var(--gold)',boxShadow:'0 0 20px rgba(255,215,0,.3)',marginBottom:16}},
          React.createElement('div',{style:{...mono,fontSize:9,color:'var(--gold)',letterSpacing:'.15em',textTransform:'uppercase',marginBottom:8}},'ANSWER'),
          React.createElement('div',{style:{fontSize:'clamp(20px,5vw,32px)',textTransform:'uppercase',letterSpacing:'.03em',color:'var(--gold)',textShadow:'0 0 10px rgba(255,215,0,.4)'}},companion.answer)
        ),
        hasAnswer&&answered&&React.createElement('div',{style:{...mono,fontSize:14,color:answered==='knew'?'var(--cyan)':'var(--signal)',letterSpacing:'.08em',textTransform:'uppercase',marginTop:8}},answered==='knew'?'\u2713 CALLED IT':'\u2717 NEXT TIME')
      )
    );
  }

  // DOA SCREEN
  if(screen==='doa'){
    var total=doaData.dead+doaData.alive;
    var deadPct=total?Math.round(doaData.dead/total*100):50;
    var alivePct=total?100-deadPct:50;
    return React.createElement('div',{style:base},
      cornerDot,
      React.createElement('div',{style:{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'32px 24px',textAlign:'center',width:'100%',maxWidth:420}},
        React.createElement('div',{style:{...mono,fontSize:10,color:'rgba(255,255,255,.4)',letterSpacing:'.15em',textTransform:'uppercase',marginBottom:16}},'IS THIS CULTURALLY...'),
        React.createElement('div',{style:{fontSize:'clamp(36px,10vw,56px)',textTransform:'uppercase',letterSpacing:'.04em',color:'#fff',textShadow:'0 0 10px rgba(255,255,255,.6),0 0 30px rgba(255,255,255,.3)',marginBottom:32,lineHeight:1.1}},doaTopic||'...'),
        React.createElement('div',{style:{display:'flex',gap:12,width:'100%',marginBottom:24}},
          React.createElement('button',{onClick:function(){doDoaVote('dead')},style:{flex:1,padding:'22px 16px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:26,letterSpacing:'.08em',cursor:doaVoted?'default':'pointer',textTransform:'uppercase',background:doaVoted==='dead'?'#FF007F':'transparent',color:doaVoted==='dead'?'#000':'#FF007F',border:'2px solid #FF007F',boxShadow:'0 0 12px rgba(255,0,127,.3)',opacity:doaVoted&&doaVoted!=='dead'?.15:1,pointerEvents:doaVoted?'none':'auto'}},'DEAD'),
          React.createElement('button',{onClick:function(){doDoaVote('alive')},style:{flex:1,padding:'22px 16px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:26,letterSpacing:'.08em',cursor:doaVoted?'default':'pointer',textTransform:'uppercase',background:doaVoted==='alive'?'#00FFFF':'transparent',color:doaVoted==='alive'?'#000':'#00FFFF',border:'2px solid #00FFFF',boxShadow:'0 0 12px rgba(0,255,255,.3)',opacity:doaVoted&&doaVoted!=='alive'?.15:1,pointerEvents:doaVoted?'none':'auto'}},'ALIVE')
        ),
        React.createElement('div',{style:{width:'100%',marginBottom:12}},
          React.createElement('div',{style:{display:'flex',justifyContent:'space-between',marginBottom:6}},
            React.createElement('span',{style:{...mono,fontSize:11,letterSpacing:'.08em',color:'#FF007F'}},doaData.dead+' DEAD'),
            React.createElement('span',{style:{...mono,fontSize:11,letterSpacing:'.08em',color:'#00FFFF'}},doaData.alive+' ALIVE')
          ),
          React.createElement('div',{style:{width:'100%',height:8,background:'rgba(255,255,255,.05)',position:'relative',overflow:'hidden'}},
            React.createElement('div',{style:{position:'absolute',left:0,top:0,bottom:0,width:deadPct+'%',background:'linear-gradient(90deg,#FF007F,rgba(255,0,127,.3))',transition:'width .4s ease'}}),
            React.createElement('div',{style:{position:'absolute',right:0,top:0,bottom:0,width:alivePct+'%',background:'linear-gradient(270deg,#00FFFF,rgba(0,255,255,.3))',transition:'width .4s ease'}})
          )
        ),
        doaVoted&&React.createElement('div',{style:{...mono,fontSize:11,color:'rgba(255,255,255,.3)',letterSpacing:'.08em',textTransform:'uppercase',marginTop:8}},'VOTE CAST \u2014 '+doaVoted.toUpperCase())
      )
    );
  }

  // RECEIPT SCREEN
  if(screen==='receipt'){
    var totalQ=stats.knewIt+stats.noClue;
    var pct=totalQ?Math.round(stats.knewIt/totalQ*100):0;
    function shareReceipt(){
      var c=document.createElement('canvas');c.width=390;c.height=520;
      var ctx=c.getContext('2d');
      ctx.fillStyle='#000';ctx.fillRect(0,0,390,520);
      // Border
      ctx.strokeStyle='#FF007F';ctx.lineWidth=2;ctx.setLineDash([4,4]);ctx.strokeRect(12,12,366,496);ctx.setLineDash([]);
      // Header
      ctx.fillStyle='#FF007F';ctx.font='bold 48px Neue Haas Grotesk Display Pro,Impact,sans-serif';ctx.textAlign='center';ctx.fillText('LINECONIC',195,65);
      ctx.fillStyle='rgba(255,255,255,0.4)';ctx.font='11px "Space Mono",monospace';ctx.fillText('YOUR SHOW RECEIPT',195,90);
      // Divider
      ctx.strokeStyle='rgba(255,255,255,0.15)';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(30,105);ctx.lineTo(360,105);ctx.stroke();
      // Stats
      ctx.textAlign='left';ctx.fillStyle='rgba(255,255,255,0.5)';ctx.font='11px "Space Mono",monospace';
      var y=135;
      ctx.fillText('QUESTIONS PLAYED',40,y);ctx.textAlign='right';ctx.fillStyle='#fff';ctx.fillText(String(totalQ),350,y);
      y+=36;ctx.textAlign='left';ctx.fillStyle='rgba(255,255,255,0.5)';ctx.fillText('KNEW IT',40,y);ctx.textAlign='right';ctx.fillStyle='#00FFFF';ctx.fillText(String(stats.knewIt),350,y);
      y+=36;ctx.textAlign='left';ctx.fillStyle='rgba(255,255,255,0.5)';ctx.fillText('NO CLUE',40,y);ctx.textAlign='right';ctx.fillStyle='#FF007F';ctx.fillText(String(stats.noClue),350,y);
      y+=36;ctx.textAlign='left';ctx.fillStyle='rgba(255,255,255,0.5)';ctx.fillText('ACCURACY',40,y);ctx.textAlign='right';ctx.fillStyle='#FFD700';ctx.fillText(pct+'%',350,y);
      y+=36;ctx.textAlign='left';ctx.fillStyle='rgba(255,255,255,0.5)';ctx.fillText('ROUNDS SEEN',40,y);ctx.textAlign='right';ctx.fillStyle='#fff';ctx.fillText(String(stats.roundsSeen.length),350,y);
      // Big accuracy
      ctx.textAlign='center';ctx.fillStyle='#FFD700';ctx.font='bold 72px Neue Haas Grotesk Display Pro,Impact,sans-serif';ctx.fillText(pct+'%',195,420);
      ctx.fillStyle='rgba(255,215,0,0.4)';ctx.font='11px "Space Mono",monospace';ctx.fillText('CULTURAL FLUENCY SCORE',195,445);
      // Footer
      ctx.fillStyle='rgba(255,255,255,0.2)';ctx.font='9px "Space Mono",monospace';ctx.fillText('lineconic.live',195,500);
      c.toBlob(function(blob){
        if(navigator.share&&navigator.canShare){
          var file=new File([blob],'lineconic-receipt.png',{type:'image/png'});
          if(navigator.canShare({files:[file]})){navigator.share({files:[file],title:'My LINECONIC Receipt'}).catch(function(){});}
          else{downloadBlob(blob)}
        }else{downloadBlob(blob)}
      });
    }
    function downloadBlob(blob){var a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='lineconic-receipt.png';a.click()}

    function drawScoreCard(canvas, stats, roomAvg, showConfig, guest){
      var W = 1080, H = 1920;
      canvas.width = W;
      canvas.height = H;
      var ctx = canvas.getContext('2d');
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      // Determine team color from winning team
      var cyan = (showConfig && showConfig.scores) ? (showConfig.scores.cyan || 0) : 0;
      var pink = (showConfig && showConfig.scores) ? (showConfig.scores.pink || 0) : 0;
      var teamColor = cyan >= pink ? '#00FFFF' : '#FF007F';
      var teamGlow = cyan >= pink ? 'rgba(0,255,255,0.6)' : 'rgba(255,0,127,0.6)';
      var teamName = cyan >= pink ? 'O.G.' : 'R.O.T.';

      // Tier calculation
      var score = stats.knewIt || 0;
      var total = (stats.knewIt || 0) + (stats.noClue || 0);
      var pct = total > 0 ? score / total : 0;
      var tier = 'CULTURALLY SOUND';
      if (pct >= 0.9) tier = 'ICON';
      else if (pct >= 0.7) tier = 'MAIN CHARACTER';
      else if (pct >= 0.4) tier = 'CULTURALLY SOUND';
      else if (pct >= 0.1) tier = 'ON THIN ICE';
      else tier = 'UNCULTURED';

      // Background — void black
      ctx.fillStyle = '#000000';
      ctx.fillRect(0, 0, W, H);

      // Border — 2px inset, team-colored with glow
      ctx.strokeStyle = teamColor;
      ctx.lineWidth = 4;
      ctx.shadowColor = teamGlow;
      ctx.shadowBlur = 8;
      ctx.strokeRect(8, 8, W - 16, H - 16);
      ctx.shadowBlur = 0;

      // ── HEADER ──

      // LINECONIC logo mark
      ctx.font = '900 36px "Neue Haas Grotesk Display Pro", "Arial Black", sans-serif';
      ctx.fillStyle = '#FFFFFF';
      ctx.fillText('LINECONIC', W/2, 80);

      // Show metadata (date + venue)
      var metaText = '';
      if (showConfig && showConfig.date) {
        var d = new Date(showConfig.date);
        var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
        metaText = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
      }
      if (showConfig && showConfig.showName) {
        metaText = metaText ? metaText + ' \u00b7 ' + showConfig.showName.toUpperCase() : showConfig.showName.toUpperCase();
      }
      if (metaText) {
        ctx.font = '700 20px "Space Mono", monospace';
        ctx.fillStyle = '#666666';
        ctx.fillText(metaText, W/2, 120);
      }

      // ── TEAM STRIP ──

      // Full-width team line
      ctx.fillStyle = teamColor;
      ctx.fillRect(40, 220, W - 80, 2);

      // Team name
      ctx.font = '700 24px "Space Mono", monospace';
      ctx.fillStyle = teamColor;
      ctx.fillText(teamName, W/2, 256);

      // ── GUEST NAME ──

      var displayName = (guest && guest.firstName) ? guest.firstName.toUpperCase() : '';
      if (displayName) {
        var nameSize = 80;
        ctx.font = '900 ' + nameSize + 'px "Neue Haas Grotesk Display Pro", "Arial Black", sans-serif';
        while (ctx.measureText(displayName).width > W - 120 && nameSize > 40) {
          nameSize -= 4;
          ctx.font = '900 ' + nameSize + 'px "Neue Haas Grotesk Display Pro", "Arial Black", sans-serif';
        }
        ctx.fillStyle = '#FFFFFF';
        ctx.fillText(displayName, W/2, 380);
      }

      // ── SCORE BLOCK ──

      // Individual score — hero, team-colored
      var scoreText = score + ' / ' + total;
      var scoreSize = 220;
      ctx.font = '900 ' + scoreSize + 'px "Neue Haas Grotesk Display Pro", "Arial Black", sans-serif';
      while (ctx.measureText(scoreText).width > W - 100 && scoreSize > 120) {
        scoreSize -= 10;
        ctx.font = '900 ' + scoreSize + 'px "Neue Haas Grotesk Display Pro", "Arial Black", sans-serif';
      }
      ctx.fillStyle = teamColor;
      ctx.shadowColor = teamGlow;
      ctx.shadowBlur = 12;
      ctx.fillText(scoreText, W/2, 700);
      ctx.shadowBlur = 0;

      // Room average
      if (roomAvg !== null) {
        ctx.font = '700 24px "Space Mono", monospace';
        ctx.fillStyle = '#666666';
        ctx.fillText('ROOM AVG: ' + roomAvg + ' / ' + total, W/2, 840);
      }

      // Tier label
      ctx.font = '700 32px "Space Mono", monospace';
      ctx.fillStyle = teamColor;
      ctx.fillText(tier, W/2, 900);

      // ── TEAM WINNER ──

      if (showConfig && showConfig.scores && (cyan > 0 || pink > 0)) {
        var winner = cyan >= pink ? 'O.G.' : 'R.O.T.';
        ctx.font = '700 28px "Space Mono", monospace';
        ctx.fillStyle = teamColor;
        ctx.shadowColor = teamGlow;
        ctx.shadowBlur = 12;
        ctx.fillText(winner + ' WINS ' + cyan + '\u2013' + pink, W/2, 1000);
        ctx.shadowBlur = 0;
      }

      // ── BOTTOM SECTION ──

      // Show stamp
      if (showConfig && showConfig.showNumber) {
        ctx.font = '700 20px "Space Mono", monospace';
        ctx.fillStyle = '#333333';
        ctx.fillText('SHOW ' + showConfig.showNumber, W/2, 1580);
      }

      // Sign-off
      ctx.font = '700 24px "Space Mono", monospace';
      ctx.fillStyle = '#FFFFFF';
      ctx.fillText("YOU'VE BEEN LINECONIC.", W/2, 1680);

      // Recognition link
      ctx.font = '700 18px "Space Mono", monospace';
      ctx.fillStyle = '#333333';
      ctx.fillText('lineconic.live', W/2, 1780);
    }

    function shareScoreCard(){
      if(!canvasRef.current) return;
      canvasRef.current.toBlob(function(blob){
        if(!blob) return;
        if(navigator.share && navigator.canShare){
          var file = new File([blob], 'lineconic-scorecard.png', {type:'image/png'});
          if(navigator.canShare({files:[file]})){
            navigator.share({files:[file], title:'LINECONIC'});
            return;
          }
        }
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'lineconic-scorecard.png';
        a.click();
        URL.revokeObjectURL(url);
      }, 'image/png');
    }

    // Score Card overlay
    var scorecardOverlay = null;
    if(showScorecard){
      scorecardOverlay = React.createElement('div', {
        className: 'scorecard-overlay',
        onClick: function(){ setShareVisible(!shareVisible); }
      },
        React.createElement('canvas', {ref: canvasRef}),
        React.createElement('button', {
          className: 'scorecard-share' + (shareVisible ? '' : ' hidden'),
          onClick: function(e){ e.stopPropagation(); shareScoreCard(); },
          'aria-label': 'Share score card'
        }, '\u2B06')
      );
    }

    return React.createElement('div',{style:base},
      cornerDot,
      React.createElement('div',{style:{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'32px 24px',textAlign:'center',width:'100%',maxWidth:420}},
        React.createElement('div',{style:{fontSize:48,color:'var(--signal)',textShadow:'0 0 20px rgba(255,0,127,.6)',marginBottom:8,letterSpacing:'.06em'}},'LINECONIC'),
        React.createElement('div',{style:{...mono,fontSize:10,color:'rgba(255,255,255,.4)',letterSpacing:'.15em',textTransform:'uppercase',marginBottom:24}},'YOUR SHOW RECEIPT'),
        React.createElement('div',{style:{width:'100%',border:'2px dashed rgba(255,255,255,.15)',padding:20,marginBottom:24}},
          [['QUESTIONS',totalQ,'#fff'],['KNEW IT',stats.knewIt,'#00FFFF'],['NO CLUE',stats.noClue,'#FF007F'],['ROUNDS',stats.roundsSeen.length,'#fff']].map(function(row){
            return React.createElement('div',{key:row[0],style:{display:'flex',justifyContent:'space-between',padding:'8px 0',borderBottom:'1px solid rgba(255,255,255,.06)'}},
              React.createElement('span',{style:{...mono,fontSize:11,color:'rgba(255,255,255,.5)',letterSpacing:'.08em'}},row[0]),
              React.createElement('span',{style:{...mono,fontSize:14,color:row[2],fontWeight:700}},row[1])
            );
          })
        ),
        React.createElement('div',{style:{fontSize:72,color:'var(--gold)',textShadow:'0 0 20px rgba(255,215,0,.5)',marginBottom:4}},pct+'%'),
        React.createElement('div',{style:{...mono,fontSize:10,color:'rgba(255,215,0,.5)',letterSpacing:'.12em',textTransform:'uppercase',marginBottom:32}},'CULTURAL FLUENCY SCORE'),
        React.createElement('button',{onClick:shareReceipt,style:{padding:'16px 40px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:20,letterSpacing:'.08em',cursor:'pointer',textTransform:'uppercase',background:'var(--signal)',color:'#000',border:'none',boxShadow:'0 0 20px rgba(255,0,127,.4)'}},'SHARE RECEIPT'),
        React.createElement('a',{href:'https://lineconic.com?utm_source=live-app&utm_medium=web&utm_campaign=show&utm_content=get-the-game',target:'_blank',rel:'noopener',style:{display:'inline-block',padding:'14px 36px',fontFamily:"'Neue Haas Grotesk Display Pro',sans-serif",fontSize:16,letterSpacing:'.08em',cursor:'pointer',textTransform:'uppercase',background:'transparent',color:'var(--gold)',border:'1px solid var(--gold)',marginTop:12,textDecoration:'none',transition:'all .15s'},onMouseOver:function(e){e.target.style.background='var(--gold)';e.target.style.color='#000'},onMouseOut:function(e){e.target.style.background='transparent';e.target.style.color='var(--gold)'}},'GET THE GAME')
      ),
      scorecardOverlay
    );
  }

  return React.createElement('div',{style:base},React.createElement('div',{style:{...mono,color:'rgba(255,255,255,.3)',padding:40}},'LOADING...'));
}
