/* Curio — quest play, board, complete, leaderboard, prizes, create */
const {useState:useQState,useEffect:useQEffect} = React;

/* ── QUEST BRIEF ── */
function QuestBriefScreen(){
  const{t,lang,state,nav,route}=useApp();
  const L=(v)=>pick(v,lang);
  const q=window.DATA.questById(route.p.questId)||window.DATA.QUESTS[0];
  const prog=state.questProgress[q.id]||{stop:0,total:q.stops.length};
  const crew=state.crews.find(c=>c.questId===q.id);
  const roles=window.DATA.rolesFor(q.id);
  const role=crew?.role||roles[0].id;
  const roleObj=roles.find(r=>r.id===role)||roles[0];
  return <div data-screen-label="Quest Brief" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg}}>
    <BackRow title={t('questBrief')}/>
    <div style={{padding:'12px 20px'}}>
      <div style={{padding:'14px 16px',borderRadius:16,background:tint(8),border:`1.5px solid ${tint(24)}`,display:'flex',gap:12,alignItems:'center',marginBottom:18}}>
        <span style={{width:46,height:46,borderRadius:13,background:tint(16),display:'inline-flex',alignItems:'center',justifyContent:'center',fontSize:22,flexShrink:0}}>{roleObj.icon}</span>
        <div><div style={{color:T.muted,fontSize:fz(11.5),fontWeight:700,fontFamily:F,textTransform:'uppercase',letterSpacing:'.5px'}}>{t('yourRoleIs')}</div>
        <div style={{color:T.text,fontSize:fz(15.5),fontWeight:800,fontFamily:F}}>{pick(roleObj.name,lang)}</div>
        <div style={{color:T.sub,fontSize:fz(12.5),fontFamily:F,marginTop:1}}>{pick(roleObj.desc,lang)}</div></div>
      </div>
      <h2 style={{color:T.text,fontSize:fz(23),fontWeight:800,fontFamily:FD,letterSpacing:'-0.5px',margin:'0 0 6px'}}>{L(q.title)}</h2>
      <p style={{color:T.sub,fontSize:fz(14),fontFamily:F,lineHeight:1.6,margin:'0 0 22px'}}>{L(q.blurb)}</p>
      <h3 style={{color:T.text,fontSize:fz(15),fontWeight:800,fontFamily:F,margin:'0 0 14px'}}>{t('yourStops')}</h3>
      <Stops stops={q.stops.map(L)} activeIndex={prog.stop}/>
      <Gap n={18}/>
      <div style={{padding:'13px 15px',borderRadius:14,background:T.goldBg,border:`1px solid ${T.goldLine}`,marginBottom:20,display:'flex',gap:10}}>
        <span style={{fontSize:18}}>💡</span>
        <p style={{color:T.gold,fontSize:fz(12.5),fontFamily:F,lineHeight:1.55,margin:0}}><strong>{pick(roleObj.name,lang)} {lang==='de'?'Tipp':'tip'}:</strong> {lang==='de'?'Achte auf Marken, Daten oder Symbole, die fehl am Platz wirken.':'Look for marks, dates or symbols that feel out of place. Your team needs your findings to decode the full story.'}</p>
      </div>
      <Btn label={t('beginQuest')} icon={<Ic k="scan" size={19}/>} onClick={()=>nav.push('ar-scan',{questId:q.id})}/>
    </div>
    <Gap n={28}/>
  </div>;
}

/* ── AR SCAN (artifact) ── same camera + snap-point sheet system as the Scan tab */
function ARScanScreen(){
  const{t,lang,state,nav,route}=useApp();
  window.__curioLang=lang;
  const L=(v)=>pick(v,lang);
  const de=lang==='de';
  const q=window.DATA.questById(route.p.questId)||window.DATA.QUESTS[0];
  const prog=state.questProgress[q.id]||{stop:0,total:q.stops.length};
  const stopObj=q.stops[Math.min(prog.stop,q.stops.length-1)];
  const stopName=L(stopObj);
  const lookText=stopObj.look?L(stopObj.look):'';
  const whereText=stopObj.where?L(stopObj.where):'';
  const[found,setFound]=useQState(false);
  const[showHint,setShowHint]=useQState(false);
  const[showHintImg,setShowHintImg]=useQState(false);
  const[detent,setDetent]=useQState('peek');
  function handleFound(){
    setFound(true);
    showToast(t('niceFind'),{icon:<Ic k="check" size={15} color="#34C759"/>});
  }

  const header=(
    <div style={{background:'rgba(255,255,255,.5)',border:'1px solid rgba(255,255,255,.55)',borderRadius:16,padding:'12px'}}>
      <div style={{display:'flex',gap:12,alignItems:'flex-start'}}>
        <button type="button" onClick={()=>setShowHintImg(true)} className="cu-press" style={{border:'none',padding:0,cursor:'pointer',flexShrink:0}}>
          <Thumb src={stopObj.img} alt="" size={62} radius={13}/>
        </button>
        <div style={{flex:1,minWidth:0}}>
          <div style={{color:T.muted,fontSize:fz(11),fontWeight:700,fontFamily:F,textTransform:'uppercase',letterSpacing:'.4px',marginBottom:4}}>{t('lookForLabel')} · {prog.stop+1}/{prog.total}</div>
          <div style={{color:T.text,fontSize:fz(15.5),fontWeight:700,fontFamily:F,lineHeight:1.25,marginBottom:4,overflow:'hidden',textOverflow:'ellipsis',display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical'}}>{stopName}</div>
          {whereText&&<button type="button" onClick={()=>setDetent(d=>d==='peek'?'half':d)} style={{display:'flex',gap:4,alignItems:'center',maxWidth:'100%',border:'none',background:'transparent',padding:0,cursor:'pointer',color:'var(--ink-deep)',fontSize:fz(12.5),fontWeight:600,fontFamily:F}}>
            <Ic k="location" size={13} color="var(--ink-deep)" style={{flexShrink:0}}/><span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',textDecoration:'underline',textUnderlineOffset:2}}>{whereText}</span>
          </button>}
        </div>
        <button type="button" onClick={()=>setShowHint(true)} aria-label={t('hint')} className="cu-press" style={{width:40,height:40,borderRadius:12,border:`1px solid ${tintGlass(30)}`,background:tintGlass(18),cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}><Ic k="sparkle" size={18} color="var(--ink-deep)"/></button>
      </div>
    </div>
  );

  const footer=!found
    ?<Btn label={t('iFoundIt')} icon={<Ic k="check" size={18}/>} onClick={handleFound}/>
    :<div className="cu-rise">
      <div style={{display:'flex',justifyContent:'center',marginBottom:10}}><Chip label={t('artifactDetected')} kind="green" dot/></div>
      <Btn label={t('revealClue')} variant="gold" icon={<span key="found" className="cu-pop" style={{display:'flex'}}><Ic k="sparkle" size={18} fill/></span>} onClick={()=>nav.push('clue-found',{questId:q.id})}/>
    </div>;

  return <div data-screen-label="AR Scan" style={{flex:1,position:'relative',overflow:'hidden',background:'#0B0814'}}>
    <CameraView fallback={stopObj.img||q.img}/>
    <div aria-hidden="true" style={{position:'absolute',inset:0,background:'linear-gradient(180deg,rgba(11,8,20,.5),rgba(11,8,20,.2) 40%,rgba(11,8,20,.65))'}}></div>

    <div style={{position:'absolute',top:'calc(12px + var(--cu-safe-top))',left:14,right:14,display:'flex',justifyContent:'space-between',alignItems:'center',zIndex:6}}>
      <IconBtn k="arrowL" onDark onClick={nav.pop} ariaLabel={t('back')}/>
      <Chip label={`${prog.stop+1}/${prog.total}`} kind="goldOnDark"/>
    </div>
    <div aria-hidden={detent!=='peek'} style={{position:'absolute',top:'38%',left:'50%',transform:'translate(-50%,-50%)',opacity:detent==='peek'?1:0,transition:`opacity .25s ${EASE}`,pointerEvents:'none',zIndex:4}}>
      <ScanCorners size={214} sweep={!found && detent==='peek'}/>
      {lookText&&<p style={{color:'rgba(255,255,255,.9)',fontSize:fz(13.5),fontFamily:F,lineHeight:1.5,margin:'22px 0 0',textAlign:'center',maxWidth:250,textShadow:'0 1px 8px rgba(11,8,20,.6)'}}>{lookText}</p>}
    </div>

    <ScanSheet detent={detent} onDetentChange={setDetent} navBelow={false}
      header={header} footer={footer}
      mapSection={<MuseumMapContent q={q} prog={prog} lang={lang} nav={nav} hideStops compact hideNext/>}
      fabLabel={de?'Karte':'Map'} mapTitle={de?'Standort im Museum':'Where you are'}/>

    {showHint&&<Sheet onClose={()=>setShowHint(false)}>
      <div style={{display:'flex',gap:12,alignItems:'center',margin:'0 0 16px'}}>
        <Thumb src={stopObj.img} alt="" size={72} radius={14}/>
        <div style={{minWidth:0,flex:1}}><div style={{color:T.muted,fontSize:fz(11),fontWeight:700,fontFamily:F,textTransform:'uppercase',letterSpacing:'.5px'}}>{t('hint')} · {prog.stop+1}/{prog.total}</div>
        <h3 style={{color:T.text,fontSize:fz(18),fontWeight:700,fontFamily:FD,margin:'4px 0 0',overflow:'hidden',textOverflow:'ellipsis',display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical'}}>{stopName}</h3></div>
      </div>
      {lookText&&<p style={{color:T.text,fontSize:fz(15),fontFamily:F,lineHeight:1.55,margin:'0 0 12px'}}>{lookText}</p>}
      {whereText&&<p style={{color:T.muted,fontSize:fz(14),fontFamily:F,margin:'0 0 18px',display:'flex',gap:6,alignItems:'center'}}><Ic k="location" size={14} style={{flexShrink:0}}/>{whereText}</p>}
      <Btn label={t('gotIt')} onClick={()=>setShowHint(false)}/>
    </Sheet>}
    {showHintImg&&<ImageViewer src={stopObj.img} alt={stopName} onClose={()=>setShowHintImg(false)}/>}
  </div>;
}

/* ── CLUE FOUND ── */
function ClueFoundScreen(){
  const{t,lang,state,nav,route,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const q=window.DATA.questById(route.p.questId)||window.DATA.QUESTS[0];
  const prog=state.questProgress[q.id]||{stop:0,total:q.stops.length};
  const last=prog.stop+1>=prog.total;
  const stopObj=q.stops[Math.min(prog.stop,q.stops.length-1)];
  const clueText=stopObj.story||{en:'Combine your findings with your team to unlock the full story.',de:'Kombiniere deine Funde mit dem Team, um die ganze Geschichte zu enthüllen.'};
  return <div data-screen-label="Clue Found" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg,position:'relative'}}>
    <Gap n={16}/>
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'0 24px',textAlign:'center'}}>
      <div className="cu-pop" style={{width:88,height:88,borderRadius:26,marginBottom:18,background:GRAD,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',boxShadow:SHmd}}><Ic k="sparkle" size={42} fill/></div>
      <Chip label={`+150 ${t('xp')}`} kind="gold"/>
      <h1 style={{color:T.text,fontSize:fz(26),fontWeight:800,fontFamily:FD,letterSpacing:'-0.6px',lineHeight:1.2,margin:'14px 0 8px'}}>{t('clueFound')}</h1>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,lineHeight:1.6,maxWidth:300,margin:0}}>{L(q.stops[Math.min(prog.stop,q.stops.length-1)])}</p>
    </div>
    <Gap n={22}/>
    <div style={{padding:'0 20px'}}>
      <Card style={{marginBottom:14}} padding="0">
        <Photo src={q.stops[Math.min(prog.stop,q.stops.length-1)].img||'img/clue.jpg'} alt="" h={140} radius={0}/>
        <div style={{padding:16}}>
          <p style={{color:T.sub,fontSize:fz(14),lineHeight:1.65,fontFamily:F,margin:'0 0 12px'}}>"{L(clueText)}"</p>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <Chip label={`+150 ${t('xp')}`} kind="gold"/>
            <span style={{color:T.muted,fontSize:fz(12),fontFamily:F}}>{prog.stop+1} / {prog.total} {t('stops')}</span>
          </div>
        </div>
      </Card>
      {!last&&<Btn label={t('nextStop')} icon={<Ic k="arrowR" size={18}/>} onClick={()=>{actions.advanceStop(q.id);nav.replace('ar-scan',{questId:q.id});}}/>}
      {last&&<Btn label={t('completeFinal')} variant="gold" onClick={()=>{actions.advanceStop(q.id);nav.replace('group-board',{questId:q.id});}}/>}
      {!last&&<><Gap n={10}/><Btn label={t('crewBoard')} variant="ghost" icon={<Ic k="users" size={17}/>} onClick={()=>{actions.advanceStop(q.id);nav.replace('group-board',{questId:q.id});}}/></>}
    </div>
    <Gap n={28}/>
  </div>;
}

/* ── QUEST HUB (in-progress) ── tabbed: scan · map · clues · board */
function GroupBoardScreen(){
  const{t,lang,state,nav,route,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const de=lang==='de';
  const[confirmExit,setConfirmExit]=useQState(false);
  const q=window.DATA.questById(route.p.questId||state.activeQuestId)||window.DATA.QUESTS[0];
  const prog=state.questProgress[q.id]||{stop:0,total:q.stops.length};
  const crew=state.crews.find(c=>c.questId===q.id);
  const last=prog.stop>=prog.total;
  const activeIdx=prog.stop;
  const activeStop=!last?q.stops[Math.min(activeIdx,q.stops.length-1)]:null;
  const doneStops=q.stops.slice(0,activeIdx);
  const xp=prog.stop*150;
  const myPct=prog.total?Math.round(prog.stop/prog.total*100):0;
  const race=[
    {n:'Desert Foxes',p:Math.min(100,myPct+12)},
    {n:crew?.name||t('yourCrew'),p:myPct,you:true},
    {n:'Kunstareal Squad',p:Math.max(0,myPct-8)},
  ].sort((a,b)=>b.p-a.p);
  const myRank=race.findIndex(r=>r.you)+1;
  const [tab,setTab]=useQState('scan');

  const HUB_TABS=[
    {id:'scan',label:t('questHubScan'),icon:'scan'},
    {id:'map',label:t('questHubMap'),icon:'map'},
    {id:'clues',label:t('questHubClues'),icon:'sparkle'},
    {id:'board',label:t('questHubBoard'),icon:'trophy'},
  ];

  return (
    <div data-screen-label="Quest Hub" className="cu-step-shell">
      <div style={{flexShrink:0,padding:`calc(8px + var(--cu-safe-top)) 20px 14px`,background:T.bg,borderBottom:`1px solid ${T.line}`}}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:14}}>
          <IconBtn k="arrowL" onClick={nav.pop} ariaLabel={t('back')}/>
          <div style={{flex:1,minWidth:0}}>
            <div style={{color:T.text,fontSize:fz(17),fontWeight:800,fontFamily:FD,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{L(q.title)}</div>
            <div style={{color:T.muted,fontSize:fz(12.5),fontFamily:F,marginTop:2}}>{de?'Stop':'Stop'} {prog.stop}/{prog.total} · #{myRank} · +{xp} XP</div>
          </div>
          {!last&&<IconBtn k="scan" onClick={()=>nav.push('ar-scan',{questId:q.id})} ariaLabel={t('openScanner')}/>}
          <IconBtn k="settings" onClick={()=>setConfirmExit(true)} ariaLabel={t('sessionSettings')}/>
        </div>
        <PBar val={myPct} grad label={t('yourProgress')}/>
      </div>

      <div style={{flexShrink:0,display:'flex',gap:6,padding:'10px 20px',background:T.bg,borderBottom:`1px solid ${T.line}`}}>
        {HUB_TABS.map(tb=><button key={tb.id} type="button" onClick={()=>setTab(tb.id)} className="cu-press" style={{flex:1,minHeight:44,borderRadius:12,border:'none',cursor:'pointer',background:tab===tb.id?tint(12):T.cardAlt,color:tab===tb.id?'var(--ink-deep)':T.muted,fontSize:fz(11.5),fontWeight:700,fontFamily:F,boxShadow:tab===tb.id?`inset 0 0 0 1.5px ${tint(32)}`:'none',display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:4}}>
          <Ic k={tb.icon} size={16} color={tab===tb.id?'var(--ink-deep)':T.muted}/>
          {tb.label}
        </button>)}
      </div>

      <div className="cu-step-body" style={{background:T.bg}}>
        <div style={{padding:'20px'}}>
          {tab==='scan'&&(
            last
              ? <Card padding="20px"><div style={{textAlign:'center'}}><span style={{fontSize:36,display:'block',marginBottom:10}}>🏆</span><h3 style={{color:T.text,fontSize:fz(18),fontWeight:800,fontFamily:FD,margin:'0 0 8px'}}>{de?'Alle Stops geschafft!':'All stops complete!'}</h3><p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,margin:0,lineHeight:1.55}}>{de?'Schließe die Quest ab und sieh dir die Belohnungen an.':'Finish the quest and claim your rewards.'}</p></div></Card>
              : activeStop&&<Card padding="0" style={{overflow:'hidden'}}>
                  <Photo src={activeStop.img||q.img} alt="" h={160} radius={0}/>
                  <div style={{padding:18}}>
                    <Chip label={`${de?'Stop':'Stop'} ${activeIdx+1}/${prog.total}`} kind="ink"/>
                    <h2 style={{color:T.text,fontSize:fz(20),fontWeight:800,fontFamily:FD,margin:'12px 0 8px',lineHeight:1.25}}>{L(activeStop)}</h2>
                    {activeStop.where&&<p style={{color:T.muted,fontSize:fz(13),fontFamily:F,margin:'0 0 12px',display:'flex',gap:6,alignItems:'center'}}><Ic k="location" size={14}/>{L(activeStop.where)}</p>}
                    {activeStop.look&&<p style={{color:T.sub,fontSize:fz(14),fontFamily:F,lineHeight:1.6,margin:'0 0 16px'}}>{L(activeStop.look)}</p>}
                    <Btn label={t('openScanner')} icon={<Ic k="scan" size={18}/>} onClick={()=>nav.push('ar-scan',{questId:q.id})}/>
                  </div>
                </Card>
          )}

          {tab==='map'&&(
            <div style={{margin:'0 -20px'}}>
              <MuseumMapContent q={q} prog={prog} lang={lang} nav={nav} hideStops showObjects nextLabel={t('nextStop')}/>
            </div>
          )}

          {tab==='clues'&&(
            doneStops.length
              ? <div style={{display:'flex',flexDirection:'column',gap:12}}>
                  {doneStops.map((stop,i)=><Card key={i} padding="0" style={{overflow:'hidden',cursor:'pointer'}} onClick={()=>nav.push('object-detail',{questId:q.id,stopIndex:i})}>
                    <div style={{display:'flex',gap:12,padding:14,alignItems:'center',borderBottom:`1px solid ${T.line}`}}>
                      <span style={{width:28,height:28,borderRadius:'50%',background:T.greenBg,border:`1.5px solid ${T.greenLine}`,display:'inline-flex',alignItems:'center',justifyContent:'center',flexShrink:0}}><Ic k="check" size={14} color={T.green} stroke={2.5}/></span>
                      <div style={{flex:1,minWidth:0}}><div style={{color:T.text,fontSize:fz(15),fontWeight:700,fontFamily:F}}>{L(stop)}</div>{stop.where&&<div style={{color:T.muted,fontSize:fz(12.5),fontFamily:F,marginTop:2}}>{L(stop.where)}</div>}</div>
                      <Chip label="+150 XP" kind="green"/>
                    </div>
                    {stop.story&&<div style={{padding:'14px 16px'}}><p style={{color:T.sub,fontSize:fz(13.5),fontFamily:F,lineHeight:1.6,margin:0}}>{L(stop.story)}</p></div>}
                  </Card>)}
                </div>
              : <EmptyState emoji="🔍" title={de?'Noch keine Hinweise':'No clues yet'} message={de?'Scanne den ersten Stop, um Hinweise zu sammeln.':'Scan the first stop to collect clues.'}/>
          )}

          {tab==='board'&&(
            <div>
              <div style={{display:'flex',gap:8,marginBottom:16}}>
                {[{l:'XP',v:xp.toLocaleString(),hl:true},{l:de?'Rang':'Rank',v:`#${myRank}`},{l:de?'Stops':'Stops',v:`${prog.stop}/${prog.total}`}].map(s=><div key={s.l} style={{flex:1,padding:'14px 10px',borderRadius:14,background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH,textAlign:'center'}}><div style={{color:s.hl?'var(--ink-deep)':T.text,fontSize:fz(17),fontWeight:800,fontFamily:FD}}>{s.v}</div><div style={{color:T.muted,fontSize:fz(11),fontFamily:F,marginTop:4}}>{s.l}</div></div>)}
              </div>
              <SecTitle c={t('leaderboard')}/>
              <Gap n={8}/>
              <div style={{display:'flex',flexDirection:'column',gap:10}}>
                {race.map((r,i)=><div key={i} style={{padding:'14px 16px',borderRadius:14,background:r.you?tint(8):T.card,border:`1.5px solid ${r.you?tint(32):T.line}`,boxShadow:SH}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10,gap:10}}>
                    <span style={{color:T.text,fontSize:fz(15),fontWeight:r.you?800:600,fontFamily:F}}>{i===0?'🥇 ':i===1?'🥈 ':i===2?'🥉 ':''}{r.n}{r.you?` (${de?'Du':'you'})`:''}</span>
                    <span style={{color:'var(--ink-deep)',fontSize:fz(14),fontWeight:700,fontFamily:F}}>{Math.round(r.p)}%</span>
                  </div>
                  <PBar val={r.p} grad={r.you}/>
                </div>)}
              </div>
              <Gap n={12}/>
              <Btn label={t('leaderboard')} variant="secondary" onClick={()=>nav.push('leaderboard',{questId:q.id})}/>
            </div>
          )}
        </div>
        <Gap n={8}/>
      </div>

      {last && (
        <div className="cu-step-footer">
          <Btn label={t('completeFinal')} variant="gold" onClick={()=>nav.push('quest-complete',{questId:q.id})}/>
        </div>
      )}

      {confirmExit&&<Sheet onClose={()=>setConfirmExit(false)}>
        <h2 style={{color:T.text,fontSize:fz(20),fontWeight:800,fontFamily:FD,margin:'0 0 8px'}}>{de?'Quest verlassen?':'Exit this quest?'}</h2>
        <p style={{color:T.muted,fontSize:fz(14),fontFamily:F,lineHeight:1.55,margin:'0 0 20px'}}>{de?'Dein Fortschritt bleibt gespeichert — du kannst jederzeit weitermachen.':'Your progress is saved — you can pick it up again anytime from the quest page.'}</p>
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          <Btn label={de?'Quest verlassen':'Exit quest'} variant="secondary" onClick={()=>{actions.update({activeQuestId:null}); setConfirmExit(false); showToast(de?'Quest pausiert':'Quest exited — progress saved'); nav.goTab('home');}}/>
          <Btn label={de?'Fortschritt löschen & beenden':'Delete progress & exit'} variant="secondary" style={{color:'#C0392B'}} onClick={()=>{actions.update(s=>{const qp={...s.questProgress}; delete qp[q.id]; return {...s,questProgress:qp,activeQuestId:null};}); setConfirmExit(false); showToast(de?'Quest gelöscht':'Quest progress deleted'); nav.goTab('home');}}/>
          {crew&&<Btn label={t('deleteTeam')} variant="secondary" style={{color:'#C0392B'}} onClick={()=>{actions.deleteCrew(crew.code); actions.update({activeQuestId:null}); setConfirmExit(false); showToast(t('teamDeleted')); nav.goTab('home');}}/>}
          <Btn label={t('cancel')} variant="tonal" onClick={()=>setConfirmExit(false)}/>
        </div>
      </Sheet>}
    </div>
  );
}


/* ── QUEST COMPLETE ── */
function QuestCompleteScreen(){
  const{t,lang,state,nav,route,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const q=window.DATA.questById(route.p.questId||state.activeQuestId)||window.DATA.QUESTS[0];
  const prog=state.questProgress[q.id]||{stop:q.stops.length,total:q.stops.length};
  const crew=state.crews.find(c=>c.questId===q.id);
  const myPct=prog.total?Math.round(prog.stop/prog.total*100):100;
  const race=[{p:Math.min(100,myPct+12)},{p:myPct,you:true},{p:Math.max(0,myPct-8)}].sort((a,b)=>b.p-a.p);
  const myRank=race.findIndex(r=>r.you)+1;
  const isDate=crew?.mode==='date';
  const[meet,setMeet]=useQState(false);
  useQEffect(()=>{ actions.completeQuest(q.id); },[]);
  const total=(q.stops.length*150+500);
  return <div data-screen-label="Quest Complete" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg,position:'relative'}}>
    <Confetti/>
    <Gap n={14}/>
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'0 24px',textAlign:'center'}}>
      <div className="cu-pop" style={{width:96,height:96,borderRadius:30,marginBottom:18,background:'linear-gradient(135deg,#FFC247,#FF8A3D)',display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',boxShadow:'0 12px 30px rgba(255,150,40,.4)'}}><Ic k="trophy" size={48}/></div>
      <Chip label={t('questComplete')} kind="green" dot/>
      <h1 style={{color:T.text,fontSize:fz(28),fontWeight:800,fontFamily:FD,letterSpacing:'-0.7px',lineHeight:1.15,margin:'14px 0 6px'}}>{L(q.title)} ✓</h1>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,lineHeight:1.6,margin:0}}>{t('teamFinishedQuest').replace('{rank}',myRank).replace('{total}',race.length)}</p>
    </div>
    <Gap n={22}/>
    <div style={{padding:'0 20px'}}>
      <div style={{display:'flex',gap:8,marginBottom:20}}>
        {[{l:t('totalXP'),v:`+${total.toLocaleString()}`},{l:t('rank'),v:`#${myRank}/${race.length}`},{l:t('clues'),v:`${q.stops.length}/${q.stops.length}`}].map(s=>
          <div key={s.l} style={{flex:1,padding:'14px 4px',borderRadius:14,background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH,textAlign:'center'}}>
            <div style={{color:'var(--ink-deep)',fontSize:fz(18),fontWeight:800,fontFamily:FD}}>{s.v}</div>
            <div style={{color:T.muted,fontSize:fz(11),fontFamily:F,marginTop:2}}>{s.l}</div>
          </div>)}
      </div>
      <h2 style={{color:T.text,fontSize:fz(17),fontWeight:800,fontFamily:FD,margin:'0 0 12px'}}>{t('rewardsUnlocked')}</h2>
      <div style={{display:'flex',flexDirection:'column',gap:10,marginBottom:18}}>
        <ListRow iconKind="gold" emoji="🏆" title={L(q.prizes[0].p)} sub={L(q.prizes[0].r)} trailing={<Chip label={t('claimReward')} kind="gold"/>}/>
        <ListRow emoji="🎖️" title={lang==='de'?'Neues Abzeichen':'New badge'} sub={L(q.title)}/>
        <ListRow emoji="⚡" title={`+${total.toLocaleString()} ${t('xp')}`} sub={t('level')+' '+window.CurioStore.levelInfo(state.xp).level}/>
      </div>
      {isDate&&<div style={{padding:16,borderRadius:18,background:GRAD_WARM,boxShadow:SHmd,marginBottom:16}}>
        <p style={{color:'#fff',fontSize:fz(15.5),fontWeight:800,fontFamily:FD,margin:'0 0 3px'}}>☕ {t('meetForCoffee')}</p>
        <p style={{color:'rgba(255,255,255,.9)',fontSize:fz(13),fontFamily:F,margin:'0 0 12px',lineHeight:1.5}}>{t('meetForCoffeeD')}</p>
        <div style={{display:'flex',gap:8}}>
          <Btn label={t('planMeetup')} variant="onGradient" sm onClick={()=>setMeet(true)} style={{flex:1}}/>
          <Btn label={t('planLater')} variant="ghost" sm onClick={()=>{}} style={{flex:1,color:'#fff',border:'1.5px solid rgba(255,255,255,.4)'}}/>
        </div>
      </div>}
      <Btn label={t('viewPrizes')} onClick={()=>nav.push('prizes')}/><Gap n={10}/>
      <Btn label={t('backHome')} variant="secondary" onClick={()=>nav.goTab('home')}/>
    </div>
    <Gap n={28}/>
    {meet&&<Sheet onClose={()=>setMeet(false)}>
      <h3 style={{color:T.text,fontSize:fz(18),fontWeight:800,fontFamily:FD,margin:'0 0 14px'}}>☕ {t('planMeetup')}</h3>
      <div style={{display:'flex',flexDirection:'column',gap:9}}>
        {['Café Frischhut · 4 min walk','Museum Café Pinakothek','Coffee Fellows, Karlsplatz'].map((c,i)=><ListRow key={i} emoji="📍" title={c} onClick={()=>setMeet(false)} trailing={<Ic k="chevR" size={18} color={T.muted}/>}/>)}
      </div>
    </Sheet>}
  </div>;
}

/* ── PRIZES ── */
function PrizesScreen(){
  const{t,lang,state,nav,route}=useApp();
  const L=(v)=>pick(v,lang);
  const q=window.DATA.questById(route.p.questId||state.activeQuestId)||window.DATA.QUESTS[0];
  const topPrize=q.prizes&&q.prizes[0];
  return <div data-screen-label="Prizes" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg}}>
    <BackRow title={t('prizes')}/>
    <div style={{padding:'12px 20px'}}>
      <div style={{padding:20,borderRadius:20,background:GRAD,boxShadow:SHmd,marginBottom:20,position:'relative',overflow:'hidden'}}>
        <div aria-hidden="true" style={{position:'absolute',top:-30,right:-20,width:120,height:120,borderRadius:'50%',background:'rgba(255,255,255,.14)'}}></div>
        <div style={{position:'relative'}}>
          <Chip label="🏆 Top prize" kind="onDark"/>
          <h2 style={{color:'#fff',fontSize:fz(19),fontWeight:800,fontFamily:FD,margin:'12px 0 4px'}}>{topPrize?L(topPrize.p):L(q.prize)}</h2>
          <p style={{color:'rgba(255,255,255,.9)',fontSize:fz(13),fontFamily:F,lineHeight:1.55,margin:'0 0 14px'}}>{q.venue} · {L(q.title)}</p>
          <Btn label={t('leaderboard')} variant="onGradient" sm full={false} onClick={()=>nav.push('leaderboard',{questId:q.id})}/>
        </div>
      </div>
      <h2 style={{color:T.text,fontSize:fz(17),fontWeight:800,fontFamily:FD,margin:'0 0 12px'}}>{t('suggestedPrizes')}</h2>
      <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:20}}>
        {(q.prizes||[]).map((p,i)=><ListRow key={i} emoji={i===0?'🏆':'🎖️'} title={L(p.p)} sub={L(p.r)}/>)}
      </div>
      <h2 style={{color:T.text,fontSize:fz(17),fontWeight:800,fontFamily:FD,margin:'0 0 12px'}}>{t('badges')}</h2>
      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        {window.DATA.BADGES.map(b=><ListRow key={b.id} iconKind={state.badges.includes(b.id)?'gold':'neutral'} emoji={b.icon} title={L(b.name)} sub={L(b.desc)} trailing={state.badges.includes(b.id)?<Chip label="✓" kind="green"/>:<Chip label="🔒" kind="neutral"/>}/>)}
      </div>
    </div>
    <Gap n={28}/>
  </div>;
}

/* ── LEADERBOARD ── */
function LeaderboardScreen(){
  const{t,nav}=useApp();
  const board=window.DATA.LEADERBOARD;
  const podium=[board[1],board[0],board[2]];
  const hs=[110,134,92];
  return <div data-screen-label="Leaderboard" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg}}>
    <BackRow title={t('leaderboard')}/>
    <div style={{padding:'12px 20px'}}>
      <div style={{display:'flex',gap:8,marginBottom:20,alignItems:'flex-end'}}>
        {podium.map((b,i)=><div key={b.rank} style={{flex:1,borderRadius:16,background:b.you?tint(9):T.card,border:`1.5px solid ${b.you?tint(36):T.line}`,boxShadow:SH,padding:'12px 8px',height:hs[i],display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'flex-end',gap:5}}>
          <span style={{fontSize:i===1?26:20}}>{['🥈','🥇','🥉'][i]}</span>
          <span style={{color:T.text,fontSize:fz(11.5),fontWeight:800,fontFamily:F,textAlign:'center',lineHeight:1.2}}>{b.name}</span>
          <span style={{color:'var(--ink-deep)',fontSize:fz(11),fontWeight:700,fontFamily:F}}>{b.xp.toLocaleString()}</span>
        </div>)}
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {board.map((b,i)=><div key={i} style={{padding:'12px 14px',borderRadius:14,background:b.you?tint(8):T.card,border:`1.5px solid ${b.you?tint(36):T.line}`,boxShadow:SH,display:'flex',gap:12,alignItems:'center'}}>
          <span style={{width:28,height:28,borderRadius:9,background:b.rank<=3?T.goldBg:T.cardAlt,border:`1px solid ${b.rank<=3?T.goldLine:T.line}`,display:'inline-flex',alignItems:'center',justifyContent:'center',color:b.rank<=3?T.gold:T.muted,fontSize:fz(12),fontWeight:800,fontFamily:F,flexShrink:0}}>{b.rank}</span>
          <AvStack names={b.ms} sz={24}/>
          <span style={{flex:1,color:T.text,fontSize:fz(14),fontWeight:b.you?800:500,fontFamily:F}}>{b.name}</span>
          <span style={{color:b.you?'var(--ink-deep)':T.muted,fontSize:fz(13),fontWeight:800,fontFamily:F}}>{b.xp.toLocaleString()}</span>
        </div>)}
      </div>
    </div>
    <Gap n={28}/>
  </div>;
}

const DEFAULT_CREATE_DRAFT={
  title:'Palace Explorers',
  blurb:'A 90-minute family hunt through 5 highlights at Golestan Palace. Each role reveals a different layer.',
  questId:'golestan',
  stops:['Shams-ol-Emareh','Mirror Hall','Marble Throne','Ivory Hall','Salam Hall'],
  prizes:[
    {rank:{en:'1st place',de:'1. Platz'},prize:{en:'Private courtyard tour with guide',de:'Private Hof-Tour mit Guide'},top:true},
    {rank:{en:'Top 10',de:'Top 10'},prize:{en:'+500 XP + Palace Scholar badge',de:'+500 XP + Palast-Gelehrter-Abzeichen'}},
    {rank:{en:'All finishers',de:'Alle'},prize:{en:'+150 XP + Rose Garden badge',de:'+150 XP + Rosengarten-Abzeichen'}},
  ],
  invites:[],
};

function CreateChooseScreen(){
  const{t,nav,actions}=useApp();
  function startTemplate(){ actions.updateCreateDraft({...DEFAULT_CREATE_DRAFT}); nav.push('create-ai-result'); }
  return <StepShell label="Create"
    header={<BackRow title={t('createQuest')}/>}
    footer={<Btn label={t('genAI')} icon={<Ic k="sparkle" size={18} fill/>} onClick={()=>nav.push('create-ai')}/>}>
    <div style={{padding:'12px 20px'}}>
      <p style={{color:T.muted,fontSize:fz(14),fontFamily:F,margin:'0 0 18px',lineHeight:1.55}}>{t('createSub')}</p>
      <button type="button" onClick={()=>nav.push('create-ai')} className="cu-press" style={{display:'block',width:'100%',textAlign:'left',padding:20,borderRadius:20,background:GRAD,border:'none',cursor:'pointer',boxShadow:SHmd,marginBottom:18,position:'relative',overflow:'hidden'}}>
        <span aria-hidden="true" style={{position:'absolute',top:-26,right:-16,width:110,height:110,borderRadius:'50%',background:'rgba(255,255,255,.15)'}}></span>
        <span style={{position:'relative'}}>
          <span style={{display:'flex',gap:10,alignItems:'center',marginBottom:10}}>
            <span style={{fontSize:26}}>✨</span>
            <span style={{flex:1}}><span style={{display:'block',color:'#fff',fontSize:fz(18),fontWeight:800,fontFamily:FD}}>{t('genAI')}</span>
            <span style={{display:'block',color:'rgba(255,255,255,.85)',fontSize:fz(12.5),fontFamily:F}}>{t('genAISub')}</span></span>
            <Chip label="AI" kind="onDark"/>
          </span>
        </span>
      </button>
      <h2 style={{color:T.text,fontSize:fz(16),fontWeight:800,fontFamily:FD,margin:'0 0 12px'}}>{t('templates')}</h2>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginBottom:14}}>
        {[{n:'Museum hunt',e:'🏛️'},{n:'City trail',e:'🗺️'},{n:'Art quest',e:'🎨'},{n:'Family hunt',e:'👨‍👩‍👧'}].map((tp,i)=>
          <Card key={i} onClick={startTemplate} padding="15px">
            <span style={{fontSize:26,display:'block',marginBottom:8}}>{tp.e}</span>
            <span style={{display:'block',color:T.text,fontSize:fz(14.5),fontWeight:800,fontFamily:F}}>{tp.n}</span>
          </Card>)}
      </div>
      <ListRow emoji="✏️" iconKind="neutral" title={t('fromScratch')} onClick={startTemplate} trailing={<Ic k="chevR" size={18} color={T.muted}/>}/>
    </div>
  </StepShell>;
}

function CreateAIScreen(){
  const{t,nav,actions}=useApp();
  const[prompt,setPrompt]=useQState('');
  const[loading,setLoading]=useQState(false);
  const sugg=['A family hunt at Golestan Palace for kids 8–12','A science quest at the Deutsches Museum for 4 friends','A 90-minute palace tour with photo challenges'];
  function generate(){
    setLoading(true);
    const isScience=/science|deutsches|museum/i.test(prompt);
    setTimeout(()=>{
      actions.updateCreateDraft({
        ...DEFAULT_CREATE_DRAFT,
        title:isScience?'Machines & Marvels Hunt':'Palace Explorers',
        blurb:prompt||DEFAULT_CREATE_DRAFT.blurb,
        questId:isScience?'deutsches':'golestan',
        stops:isScience?['Diesel Engine','Lightning Hall','U-Boat U1','Aviation Gallery','Astronomy']:DEFAULT_CREATE_DRAFT.stops,
      });
      nav.push('create-ai-result');
    }, 1400);
  }
  return <StepShell label="Create AI"
    header={<BackRow title={t('genAI')}/>}
    footer={loading
      ? <div style={{flex:1,padding:16,borderRadius:16,background:tint(8),border:`1px solid ${tint(22)}`,display:'flex',gap:12,alignItems:'center'}}>
          <span className="cu-spin" style={{width:22,height:22,borderRadius:'50%',border:`3px solid ${tint(28)}`,borderTopColor:'var(--ink)',display:'block'}}></span>
          <span style={{color:'var(--ink-deep)',fontSize:fz(13.5),fontWeight:700,fontFamily:F}}>{t('generating')}</span>
        </div>
      : <Btn label={t('generate')} icon={<Ic k="sparkle" size={18} fill/>} disabled={!prompt} onClick={generate}/>}>
    <div style={{padding:'12px 20px'}}>
      <h2 style={{color:T.text,fontSize:fz(22),fontWeight:800,fontFamily:FD,letterSpacing:'-0.5px',margin:'0 0 6px'}}>{t('describeQuest')}</h2>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,margin:'0 0 16px',lineHeight:1.5}}>{t('genAISub')}: venue, audience, vibe, prizes.</p>
      <textarea value={prompt} onChange={e=>setPrompt(e.target.value)} aria-label={t('describeQuest')} placeholder="e.g. A family hunt at Golestan Palace…" style={{width:'100%',minHeight:120,padding:16,borderRadius:16,background:T.card,border:`1.5px solid ${prompt?tint(40):T.lineMd}`,color:T.text,fontSize:fz(14.5),fontFamily:F,lineHeight:1.6,resize:'none',outline:'none',marginBottom:16,boxSizing:'border-box',boxShadow:SH}}></textarea>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {sugg.map((s,i)=><button key={i} type="button" onClick={()=>setPrompt(s)} className="cu-press" style={{textAlign:'left',padding:'12px 14px',minHeight:44,borderRadius:14,background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH,cursor:'pointer',color:T.sub,fontSize:fz(13),fontFamily:F,lineHeight:1.45}}>"{s}"</button>)}
      </div>
    </div>
  </StepShell>;
}

function CreateAIResultScreen(){
  const{t,lang,state,nav,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const draft=state.createDraft||DEFAULT_CREATE_DRAFT;
  return <StepShell label="Create Result"
    header={<BackRow title={t('reviewQuest')}/>}
    footer={<Btn label={t('editPrizes')} icon={<Ic k="chevR" size={18}/>} onClick={()=>nav.push('create-prizes')}/>}>
    <div style={{padding:'12px 20px'}}>
      <div style={{padding:18,borderRadius:18,background:tint(8),border:`1.5px solid ${tint(24)}`,marginBottom:20}}>
        <h2 style={{color:T.text,fontSize:fz(21),fontWeight:800,fontFamily:FD,letterSpacing:'-0.4px',margin:'0 0 6px'}}>{draft.title}</h2>
        <p style={{color:T.sub,fontSize:fz(13.5),fontFamily:F,lineHeight:1.55,margin:'0 0 14px'}}>{draft.blurb}</p>
        <div style={{display:'flex',gap:8,flexWrap:'wrap'}}><Chip label={`${draft.stops.length} stops`}/><Chip label="90 min"/><Chip label="3 roles"/></div>
      </div>
      <h3 style={{color:T.text,fontSize:fz(15),fontWeight:800,fontFamily:F,margin:'0 0 12px'}}>Generated stops</h3>
      <Stops stops={draft.stops} activeIndex={-1}/>
      <Gap n={20}/>
      <h3 style={{color:T.text,fontSize:fz(15),fontWeight:800,fontFamily:F,margin:'0 0 10px'}}>{t('suggestedPrizes')}</h3>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {(draft.prizes||[]).map((p,i)=><div key={i} style={{display:'flex',gap:10,alignItems:'center',padding:'12px 14px',borderRadius:14,background:T.goldBg,border:`1px solid ${T.goldLine}`}}><span style={{fontSize:16}}>🏆</span><span style={{color:T.gold,fontSize:fz(13),fontFamily:F,fontWeight:600}}>{L(p.prize)}</span></div>)}
      </div>
    </div>
  </StepShell>;
}

function CreatePrizesScreen(){
  const{t,lang,state,nav,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const draft=state.createDraft||DEFAULT_CREATE_DRAFT;
  const prizes=draft.prizes||DEFAULT_CREATE_DRAFT.prizes;
  function setPrize(i, field, val){
    const next=prizes.map((p,idx)=>idx===i?{...p,[field]:{...p[field],en:val,de:val}}:p);
    actions.updateCreateDraft({prizes:next});
  }
  const labels=[t('prizeFirst'),t('prizeTop'),t('prizeAll')];
  return <StepShell label="Create Prizes"
    header={<BackRow title={t('editPrizes')}/>}
    footer={<Btn label={t('continueToInvite')} icon={<Ic k="chevR" size={18}/>} onClick={()=>nav.push('create-invite')}/>}>
    <div style={{padding:'12px 20px'}}>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,margin:'0 0 18px',lineHeight:1.55}}>{t('addPrizes')}</p>
      {prizes.map((p,i)=><div key={i} style={{marginBottom:16}}>
        <label style={{display:'block',color:T.text,fontSize:fz(13),fontWeight:800,fontFamily:F,marginBottom:8}}>{labels[i]||L(p.rank)}</label>
        <input value={L(p.prize)} onChange={e=>setPrize(i,'prize',e.target.value)} style={{width:'100%',boxSizing:'border-box',padding:'14px 16px',borderRadius:14,border:`1.5px solid ${T.lineMd}`,background:T.card,color:T.text,fontSize:fz(15),fontWeight:600,fontFamily:F,outline:'none'}}/>
      </div>)}
    </div>
  </StepShell>;
}

function CreateInviteScreen(){
  const{t,lang,state,nav,actions}=useApp();
  const[contact,setContact]=useQState('');
  const draft=state.createDraft||DEFAULT_CREATE_DRAFT;
  const invites=draft.invites||[];
  function addInvite(){
    if(!contact.trim()) return;
    actions.addCreateInvite(contact.trim());
    setContact('');
  }
  function publish(){
    const crew=actions.publishCreatedQuest();
    if(crew) nav.replace('create-published',{code:crew.code});
  }
  return <StepShell label="Create Invite"
    header={<BackRow title={t('invitePeople')}/>}
    footer={<Btn label={t('publish')} icon={<Ic k="share" size={18}/>} onClick={publish}/>}>
    <div style={{padding:'12px 20px'}}>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,margin:'0 0 16px',lineHeight:1.55}}>{t('invitePeopleSub')}</p>
      <div style={{display:'flex',gap:8,marginBottom:16}}>
        <input value={contact} onChange={e=>setContact(e.target.value)} placeholder={t('inviteContactPh')} aria-label={t('inviteContactPh')} style={{flex:1,minWidth:0,padding:'14px 16px',borderRadius:14,border:`1.5px solid ${T.lineMd}`,background:T.card,color:T.text,fontSize:fz(15),fontFamily:F,outline:'none'}}/>
        <button type="button" onClick={addInvite} disabled={!contact.trim()} className="cu-press" style={{minHeight:48,padding:'0 16px',borderRadius:14,border:'none',background:contact.trim()?'var(--ink)':T.cardAlt,color:contact.trim()?'#fff':T.muted,fontSize:fz(13),fontWeight:800,fontFamily:F,cursor:contact.trim()?'pointer':'default'}}>{t('addInvite')}</button>
      </div>
      {invites.length>0&&<>
        <h3 style={{color:T.text,fontSize:fz(14),fontWeight:800,fontFamily:F,margin:'0 0 10px'}}>{t('pendingInvites')}</h3>
        <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:16}}>
          {invites.map(inv=><div key={inv.id} style={{display:'flex',alignItems:'center',gap:10,padding:'12px 14px',borderRadius:14,background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH}}>
            <Ic k={inv.type==='email'?'globe':'user'} size={18} color="var(--ink-deep)"/>
            <div style={{flex:1,minWidth:0}}><div style={{color:T.text,fontSize:fz(14),fontWeight:700,fontFamily:F,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{inv.value}</div>
            <div style={{color:T.muted,fontSize:fz(12),fontFamily:F}}>{t('invitePending')}</div></div>
            <button type="button" onClick={()=>actions.removeCreateInvite(inv.id)} aria-label={t('close')} className="cu-press" style={{width:32,height:32,borderRadius:16,border:'none',background:T.cardAlt,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center'}}><Ic k="x" size={16}/></button>
          </div>)}
        </div>
      </>}
      <Card style={{background:tint(6),border:`1px solid ${tint(20)}`}}>
        <p style={{color:T.sub,fontSize:fz(13),fontFamily:F,margin:0,lineHeight:1.55}}>{t('publishTeamSub')}</p>
      </Card>
    </div>
  </StepShell>;
}

function CreatePublishedScreen(){
  const{t,lang,nav,route,state,actions}=useApp();
  const de=lang==='de';
  const code=route.p.code||state.crews[state.crews.length-1]?.code;
  useQEffect(()=>{
    if(!code) return;
    const tmr=setTimeout(()=>actions.acceptPendingInvites(code), 2200);
    return ()=>clearTimeout(tmr);
  },[code]);
  return <StepShell label="Published" footerStack
    header={<Gap n={18}/>}
    footer={<div style={{display:'flex',flexDirection:'column',gap:10,width:'100%'}}>
      <Btn label={t('viewLobby')} onClick={()=>nav.replace('group-lobby',{code})}/>
      <Btn label={t('viewOnHome')} variant="secondary" onClick={()=>nav.goTab('home')}/>
    </div>}>
    <Confetti/>
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'0 24px',textAlign:'center'}}>
      <div className="cu-pop" style={{width:88,height:88,borderRadius:28,marginBottom:18,background:GRAD,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',boxShadow:SHmd}}><Ic k="check" size={44} stroke={3}/></div>
      <Chip label={t('published')} kind="green" dot/>
      <h1 style={{color:T.text,fontSize:fz(25),fontWeight:800,fontFamily:FD,letterSpacing:'-0.6px',lineHeight:1.2,margin:'14px 0 8px'}}>{(state.createdQuests[state.createdQuests.length-1]||{}).title||'Your quest'}</h1>
      <p style={{color:T.muted,fontSize:fz(13.5),fontFamily:F,lineHeight:1.6,maxWidth:300,margin:0}}>{t('teamLobbySub')}</p>
    </div>
    <Gap n={24}/>
    <div style={{padding:'0 20px',display:'flex',flexDirection:'column',alignItems:'center'}}>
      <div style={{padding:16,borderRadius:20,background:'#fff',boxShadow:SHmd,border:`1.5px solid ${T.line}`,marginBottom:14}}><QR text={joinUrl(code)} size={150}/></div>
      <p style={{color:T.muted,fontSize:fz(12.5),fontFamily:F,marginBottom:4}}>{code}</p>
      <p style={{color:T.muted,fontSize:fz(12.5),fontFamily:F,marginBottom:8}}>{t('shareLink')}: {prettyUrl(code)}</p>
    </div>
  </StepShell>;
}

Object.assign(window,{QuestBriefScreen,ARScanScreen,ClueFoundScreen,GroupBoardScreen,QuestCompleteScreen,PrizesScreen,LeaderboardScreen,CreateChooseScreen,CreateAIScreen,CreateAIResultScreen,CreatePrizesScreen,CreateInviteScreen,CreatePublishedScreen});
