function LauncherStatusCard({onHasShow}){
  const[connected,setConnected]=useState(false);
  const[activeId,setActiveId]=useState(null);
  const[showIndex,setShowIndex]=useState(null);
  const[dropOpen,setDropOpen]=useState(false);

  useEffect(function(){
    if(!fbdb)return;
    const connRef=fbdb.ref('.info/connected');
    const connHandler=function(snap){setConnected(!!snap.val())};
    connRef.on('value',connHandler);
    const activeRef=fbdb.ref('active_show');
    const activeHandler=function(snap){setActiveId(snap.val()||null)};
    activeRef.on('value',activeHandler);
    const indexRef=fbdb.ref('show_index');
    const indexHandler=function(snap){setShowIndex(snap.val()||null)};
    indexRef.on('value',indexHandler);
    return function(){connRef.off('value',connHandler);activeRef.off('value',activeHandler);indexRef.off('value',indexHandler)};
  },[]);

  const shows=useMemo(function(){
    if(!showIndex)return[];
    return Object.keys(showIndex).map(function(id){
      return Object.assign({id:id},showIndex[id]);
    }).sort(function(a,b){return(b.created||0)-(a.created||0)});
  },[showIndex]);

  const showInfo=activeId&&showIndex&&showIndex[activeId]?showIndex[activeId]:null;

  // Fall back to localStorage cache
  const[cachedInfo,setCachedInfo]=useState(null);
  useEffect(function(){
    if(showInfo||!fbdb)return;
    try{
      const cached=JSON.parse(localStorage.getItem('lineconic_show'));
      if(cached&&cached.name){setCachedInfo({name:cached.name,duration:cached.duration||null,mediaFilter:cached.mediaFilter||[]})}
    }catch(e){}
  },[showInfo]);

  const displayInfo=showInfo||cachedInfo;

  // Notify parent of show status
  useEffect(function(){
    if(onHasShow)onHasShow(!!displayInfo);
  },[displayInfo,onHasShow]);

  function selectShow(id){
    setDropOpen(false);
    if(!fbdb)return;
    fbdb.ref('active_show').set(id);
  }

  const filterLabel=function(mf){
    if(!mf||!mf.length)return'ALL CONTENT';
    const sorted=mf.slice().sort().join(',');
    const map={'internet':'INTERNET ONLY','movie':'MOVIES ONLY','movie,tv':'SCREEN','music':'MUSIC ONLY','tv':'TV ONLY'};
    return map[sorted]||mf.join(' + ').toUpperCase();
  };

  if(!displayInfo&&shows.length===0){
    return(
      <div className="launcher-status">
        <div className="launcher-status-empty">NO SHOW LOADED</div>
        <div className="launcher-status-meta" style={{justifyContent:'center',marginTop:'var(--space-02)'}}>
          <span className="launcher-conn">
            <span className={'launcher-conn-dot '+(connected?'on':'off')}/>
            {connected?'CONNECTED':'OFFLINE'}
          </span>
        </div>
      </div>
    );
  }

  const dur=displayInfo&&displayInfo.duration?(String(displayInfo.duration).replace(/\s*min$/i,'').trim()+' MIN'):'';
  const filt=displayInfo?filterLabel(displayInfo.mediaFilter):'';

  return(
    <div className="launcher-status" style={{position:'relative'}}>
      <div onClick={function(){if(shows.length>1)setDropOpen(function(v){return!v})}} style={{cursor:shows.length>1?'pointer':'default'}}>
        <div className="launcher-status-name" style={{display:'flex',alignItems:'center',gap:6}}>
          {displayInfo?displayInfo.name:'SELECT A SHOW'}
          {shows.length>1&&<span style={{fontSize:10,color:'var(--text-dim)',transition:'transform .2s',transform:dropOpen?'rotate(180deg)':'rotate(0)'}}>{'\u25BC'}</span>}
        </div>
        <div className="launcher-status-meta">
          {dur&&<span>{dur}</span>}
          {dur&&filt&&<span style={{color:'var(--border-subtle)'}}>·</span>}
          {filt&&<span>{filt}</span>}
          {filt&&<span style={{color:'var(--border-subtle)'}}>·</span>}
          <span className="launcher-conn">
            <span className={'launcher-conn-dot '+(connected?'on':'off')}/>
            {connected?'CONNECTED':'OFFLINE'}
          </span>
        </div>
      </div>
      {dropOpen&&<div style={{position:'absolute',top:'100%',left:0,right:0,zIndex:10,background:'#111',border:'1px solid var(--border-subtle)',maxHeight:200,overflowY:'auto',marginTop:4}}>
        {shows.map(function(s){
          const isActive=s.id===activeId;
          const sDur=s.duration?(String(s.duration).replace(/\s*min$/i,'').trim()+' MIN'):'';
          return(
            <div key={s.id} onClick={function(e){e.stopPropagation();selectShow(s.id)}} style={{padding:'10px 14px',cursor:'pointer',borderBottom:'1px solid #1a1a1a',background:isActive?'rgba(0,255,255,.06)':'transparent'}}>
              <div style={{fontSize:13,fontFamily:'var(--display)',letterSpacing:'.04em',color:isActive?'var(--cyan)':'#fff',textTransform:'uppercase'}}>{s.name||s.id}</div>
              <div style={{fontSize:10,fontFamily:'var(--mono)',letterSpacing:'.06em',color:'var(--text-dim)',marginTop:2}}>
                {sDur}{sDur&&' · '}{filterLabel(s.mediaFilter)}
                {s.created&&<span> · {new Date(s.created).toLocaleDateString('en-GB',{day:'numeric',month:'short'}).toUpperCase()}</span>}
              </div>
            </div>
          );
        })}
      </div>}
    </div>
  );
}

// ═══════════════════════════════════════
// CREW LOGIN FORM (inline in host door)
// ═══════════════════════════════════════
function CrewLoginForm({onLogin}){
  const[email,setEmail]=useState('');
  const[password,setPassword]=useState('');
  const[error,setError]=useState(null);
  const[loading,setLoading]=useState(false);

  function handleSubmit(e){
    e.preventDefault();
    if(!fbauth||loading)return;
    setError(null);
    setLoading(true);
    fbauth.signInWithEmailAndPassword(email,password)
      .then(function(cred){onLogin(cred.user)})
      .catch(function(err){
        setLoading(false);
        switch(err.code){
          case'auth/invalid-email':setError('INVALID EMAIL FORMAT');break;
          case'auth/user-not-found':case'auth/wrong-password':setError('INVALID CREDENTIALS');break;
          case'auth/invalid-credential':setError('INVALID CREDENTIALS');break;
          case'auth/too-many-requests':setError('TOO MANY ATTEMPTS. TRY LATER.');break;
          default:setError('AUTH FAILED: '+err.code);
        }
      });
  }

  return(
    <form onSubmit={handleSubmit} style={{
      display:'flex',flexDirection:'column',
      gap:'var(--space-03)',
      width:'100%',maxWidth:360
    }}>
      <div style={{
        fontFamily:'var(--display)',
        fontSize:'var(--type-label)',
        letterSpacing:'.1em',
        color:'var(--text-secondary)',
        textTransform:'uppercase',
        textAlign:'center',
        marginBottom:'var(--space-02)'
      }}>CREW LOGIN</div>
      <input
        type="email"
        value={email}
        onChange={function(e){setEmail(e.target.value)}}
        placeholder="EMAIL"
        autoComplete="email"
        required
        style={{
          background:'var(--surface-02)',
          border:'1px solid var(--border-subtle)',
          color:'var(--text-primary)',
          fontFamily:"'Space Mono',monospace",
          fontSize:'var(--type-label)',
          letterSpacing:'.05em',
          padding:'12px 16px',
          outline:'none',
          width:'100%',
          textTransform:'none'
        }}
        onFocus={function(e){e.target.style.borderColor='var(--signal)';e.target.style.boxShadow='0 0 12px rgba(255,0,127,.3)'}}
        onBlur={function(e){e.target.style.borderColor='var(--border-subtle)';e.target.style.boxShadow='none'}}
      />
      <input
        type="password"
        value={password}
        onChange={function(e){setPassword(e.target.value)}}
        placeholder="PASSWORD"
        autoComplete="current-password"
        required
        style={{
          background:'var(--surface-02)',
          border:'1px solid var(--border-subtle)',
          color:'var(--text-primary)',
          fontFamily:"'Space Mono',monospace",
          fontSize:'var(--type-label)',
          letterSpacing:'.05em',
          padding:'12px 16px',
          outline:'none',
          width:'100%'
        }}
        onFocus={function(e){e.target.style.borderColor='var(--signal)';e.target.style.boxShadow='0 0 12px rgba(255,0,127,.3)'}}
        onBlur={function(e){e.target.style.borderColor='var(--border-subtle)';e.target.style.boxShadow='none'}}
      />
      <button type="submit" disabled={loading} className="launcher-launch" style={{
        marginTop:'var(--space-02)',
        cursor:loading?'wait':'pointer',
        opacity:loading?.6:1
      }}>
        {loading?'SIGNING IN...':'SIGN IN'}
      </button>
      {error&&<div style={{
        color:'var(--signal)',
        fontSize:'var(--type-meta)',
        letterSpacing:'.06em',
        textAlign:'center',
        textShadow:'0 0 8px rgba(255,0,127,.5)'
      }}>{error}</div>}
    </form>
  );
}

// ═══════════════════════════════════════
// LAUNCHER VIEW (Homepage)
// ═══════════════════════════════════════
function LauncherView(){
  const[hostOpen,setHostOpen]=useState(false);
  const[hasShow,setHasShow]=useState(false);
  const[popupWarning,setPopupWarning]=useState(false);
  const[hostUser,setHostUser]=useState(null);
  const[hostAuthLoading,setHostAuthLoading]=useState(true);

  useEffect(function(){
    if(!fbauth){setHostAuthLoading(false);return}
    var unsub=fbauth.onAuthStateChanged(function(user){
      setHostUser(user);
      setHostAuthLoading(false);
    });
    return function(){unsub()};
  },[]);

  function handleLaunch(){
    localStorage.removeItem('lineconic_show');
    localStorage.removeItem('lineconic_show_ts');
    try{const s=JSON.parse(localStorage.getItem('lineconic_state')||'{}');s.currentSlide=0;s.scores=[0,0];s.guests=0;s.revealState={};s.showScoreboard=false;localStorage.setItem('lineconic_state',JSON.stringify(s))}catch(e){}
    const w1=window.open('/audience','lineconic-audience');
    if(!w1){setPopupWarning(true);setTimeout(function(){setPopupWarning(false)},5000);return}
    window.location.href='/operator';
  }

  return(
    <div className="launcher-view">
      <div className="launcher-inner">
        {/* HERO */}
        <div className="launcher-hero">
          <a href="/" style={{textDecoration:'none'}}>
            <div className="launcher-title">LINECONIC</div>
            <div className="launcher-subtitle">LIVE</div>
          </a>
        </div>

        {/* TWO DOORS */}
        <div className="launcher-doors">
          {/* AUDIENCE DOOR — Cyan */}
          <a href="/play" className="launcher-door launcher-door-audience">
            <div className="launcher-door-label">I'M IN THE<br/>AUDIENCE</div>
            <div className="launcher-door-sub">PLAY ALONG &bull; REACT &bull; VOTE</div>
            <div className="launcher-door-icon">ENTER &rarr;</div>
          </a>

          {/* HOST DOOR — Pink */}
          <div className="launcher-door launcher-door-host" onClick={function(){setHostOpen(function(v){return!v})}} role="button" tabIndex={0} onKeyDown={function(e){if(e.key==='Enter'||e.key===' ')setHostOpen(function(v){return!v})}}>
            <div className="launcher-door-label">I'M RUNNING<br/>THE SHOW</div>
            <div className="launcher-door-sub">{hostOpen?'CONTROLS BELOW':'TAP TO OPEN'}</div>
            <div className="launcher-door-icon">{hostOpen?'CLOSE \u2715':'OPEN \u25B8'}</div>

            {/* Expandable host controls */}
            <div className={'launcher-host-expand'+(hostOpen?' open':'')}>
              <div className="launcher-host-inner" onClick={function(e){e.stopPropagation()}}>
                {hostAuthLoading
                  ?<div style={{
                    fontFamily:"'Space Mono',monospace",
                    fontSize:'var(--type-label)',
                    color:'var(--text-secondary)',
                    letterSpacing:'.1em',
                    textAlign:'center',
                    padding:'var(--space-04) 0'
                  }}>AUTHENTICATING...</div>
                  :!hostUser
                    ?<CrewLoginForm onLogin={setHostUser}/>
                    :<>
                      <LauncherStatusCard onHasShow={setHasShow}/>
                      <button className="launcher-launch" onClick={handleLaunch}>
                        {hasShow?'LAUNCH SHOW':'LAUNCH (DEFAULT SHOW)'}
                      </button>
                      {popupWarning
                        ?<div className="launcher-hint" style={{color:'var(--signal)'}}>POP-UPS BLOCKED — ALLOW POP-UPS AND TRY AGAIN</div>
                        :<div className="launcher-hint">ALLOW POP-UPS FOR BEST EXPERIENCE</div>
                      }
                      <div className="launcher-links">
                        <a className="launcher-link" href="/operator">OPERATOR</a>
                        <a className="launcher-link" href="/remote">REMOTE</a>
                        <a className="launcher-link" href="/audience" target="_blank" rel="noopener">AUDIENCE</a>
                        <a className="launcher-link" href="/answers" target="_blank" rel="noopener">ANSWERS</a>
                        <a className="launcher-link" href="/admin">ADMIN</a>
                      </div>
                      <button onClick={function(){fbauth.signOut()}} style={{
                        background:'transparent',
                        border:'1px solid var(--border-subtle)',
                        color:'var(--text-secondary)',
                        fontFamily:"'Space Mono',monospace",
                        fontSize:'var(--type-meta)',
                        letterSpacing:'.08em',
                        padding:'8px 16px',
                        cursor:'pointer',
                        marginTop:'var(--space-03)',
                        textTransform:'uppercase',
                        width:'100%'
                      }}>SIGN OUT</button>
                    </>
                }
              </div>
            </div>
          </div>
        </div>

        {/* PLAY — Standalone games */}
        <div className="launcher-play" style={{animation:'fadeIn .6s ease-out .35s both'}}>
          <div className="launcher-play-label">PLAY ANYWHERE</div>
          <a href="/hotseat" className="launcher-play-card">
            <div className="launcher-play-title">THE HOT SEAT</div>
            <div className="launcher-play-desc">HOLD TO FOREHEAD. FRIENDS SCREAM. YOU GUESS.</div>
            <div className="launcher-play-cta">PLAY &rarr;</div>
          </a>
        </div>

        {/* FOOTER */}
        <div className="launcher-footer">
          <a className="launcher-footer-deck" href="/timer">GOT THE DECK? &rarr;</a>
          <a className="launcher-footer-credit" href="https://lineconic.com?utm_source=live-app&utm_medium=web&utm_campaign=show&utm_content=footer" target="_blank" rel="noopener">LINECONIC.COM</a>
        </div>
      </div>
    </div>
  );
}
