/* Curio — object scanner & AR layer. window.ObjectScanScreen, ObjectResultScreen */
const {useState:useObjState,useEffect:useObjEffect,useRef:useObjRef} = React;

function playMarch(){
  try{
    const Ctx=window.AudioContext||window.webkitAudioContext; if(!Ctx) return ()=>{};
    const ac=new Ctx();
    const notes=[392,392,440,392,523,494, 392,392,440,392,587,523, 392,392,784,659,523,494,440, 698,698,659,523,587,523];
    const dur=0.26; const t0=ac.currentTime+0.05;
    notes.forEach((f,i)=>{
      const o=ac.createOscillator(), g=ac.createGain();
      o.type='triangle'; o.frequency.value=f;
      const s=t0+i*dur;
      g.gain.setValueAtTime(0,s); g.gain.linearRampToValueAtTime(0.18,s+0.03);
      g.gain.exponentialRampToValueAtTime(0.001,s+dur*0.9);
      o.connect(g); g.connect(ac.destination); o.start(s); o.stop(s+dur);
    });
    return ()=>{ try{ac.close();}catch(e){} };
  }catch(e){ return ()=>{}; }
}

function ObjectScanScreen(){
  const{t,lang,nav,route}=useApp();
  const L=(v)=>pick(v,lang);
  const target=route.p.objectId ? window.DATA.objectById(route.p.objectId) : null;
  const quest=route.p.questId ? window.DATA.questById(route.p.questId) : null;
  const stop=quest ? (route.p.stopIndex!=null ? quest.stops[route.p.stopIndex] : quest.stops.find(s=>s.id===route.p.objectId)) : null;
  const obj=target || (stop ? {id:stop.id, img:stop.img, name:stop, where:stop.where, blurb:stop.story, xp:40} : window.DATA.OBJECTS[0]);
  const objImg=obj.img || (obj.id && window.DATA.objectById(obj.id)?.img) || window.DATA.QUESTS[0]?.img;
  const[found,setFound]=useObjState(false);
  const[showHintImg,setShowHintImg]=useObjState(false);

  function handleFound(){
    setFound(true);
    showToast(t('niceFind'),{icon:<Ic k="check" size={15} color="#34C759"/>});
  }

  return <div data-screen-label="Scan" style={{flex:1,position:'relative',overflow:'hidden',background:'#0B0814'}}>
    <CameraView fallback={objImg}/>
    <div aria-hidden="true" style={{position:'absolute',inset:0,background:'linear-gradient(180deg,rgba(11,8,20,.45),rgba(11,8,20,.18) 38%,rgba(11,8,20,.8))'}}></div>
    
    <div style={{position:'absolute',top:'calc(12px + var(--cu-safe-top))',left:14,right:14,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
      <IconBtn k="arrowL" onDark onClick={nav.pop} ariaLabel={t('back')}/>
      <Chip label={t('scanObject')} kind="onDark"/>
      <span style={{width:40}}></span>
    </div>
    <div style={{position:'absolute',top:'42%',left:'50%',transform:'translate(-50%,-50%)'}}><ScanCorners size={244} sweep={!found}/></div>
    <div style={{position:'absolute',left:0,right:0,bottom:found?180:140,textAlign:'center',padding:'0 36px'}}>
      <p style={{color:'#fff',fontSize:fz(16),fontWeight:700,fontFamily:F,margin:'0 0 6px'}}>{found?t('objectFound'):t('pointAtArtifact')}</p>
      {!found&&<p style={{color:'rgba(255,255,255,.7)',fontSize:fz(14),fontFamily:F,margin:0}}>{t('holdSteady')}</p>}
    </div>
    <div style={{position:'absolute',left:16,right:16,bottom:34}}>
      <div style={{background:'rgba(255,255,255,.62)',backdropFilter:GLASS,WebkitBackdropFilter:GLASS,border:'1px solid rgba(255,255,255,.55)',borderRadius:20,padding:'16px',boxShadow:SHlg}}>
        <div style={{display:'flex',gap:12,alignItems:'center',marginBottom:14}}>
          <button type="button" onClick={()=>setShowHintImg(true)} className="cu-press" style={{border:'none',padding:0,cursor:'pointer',flexShrink:0}}>
            <Thumb src={objImg} alt="" size={64} radius={14}/>
          </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')}</div>
            <div style={{color:T.text,fontSize:fz(15),fontWeight:700,fontFamily:F,lineHeight:1.25,overflow:'hidden',textOverflow:'ellipsis',display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical'}}>{L(obj.name||obj)}</div>
            {obj.where&&<div style={{color:T.muted,fontSize:fz(13),fontFamily:F,marginTop:4,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{L(obj.where)}</div>}
          </div>
        </div>
        {!found
          ?<Btn label={t('iFoundIt')} icon={<Ic k="check" size={18}/>} onClick={handleFound}/>
          :<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.replace('object-result',{objectId:obj.id,questId:quest&&quest.id,stopIndex:route.p.stopIndex})}/>}
      </div>
    </div>
    {showHintImg&&<ImageViewer src={objImg} alt={L(obj.name||obj)} onClose={()=>setShowHintImg(false)}/>}
  </div>;
}

function ObjectResultScreen(){
  const{t,lang,state,nav,route,actions}=useApp();
  const L=(v)=>pick(v,lang);
  const o=window.DATA.objectById(route.p.objectId)
    || (route.p.questId && route.p.stopIndex!=null ? (()=>{const q=window.DATA.questById(route.p.questId); const s=q&&q.stops[route.p.stopIndex]; return s?{id:s.id,img:s.img,name:s,where:s.where,blurb:s.story,xp:40,year:'',maker:{en:'',de:''},kind:'ar-zoom',action:{en:'View details',de:'Details ansehen'}}:null;})() : null)
    || (route.p.questId && route.p.objectId ? (()=>{const q=window.DATA.questById(route.p.questId); const s=q&&q.stops.find(x=>x.id===route.p.objectId); return s?{id:s.id,img:s.img,name:s,where:s.where,blurb:s.story,xp:40,year:'',maker:{en:'',de:''},kind:'ar-zoom',action:{en:'View details',de:'Details ansehen'}}:null;})() : null)
    || window.DATA.OBJECTS[0];
  const objImg=o.img||'img/clue.jpg';
  const[ar,setAr]=useObjState(false);
  const[playing,setPlaying]=useObjState(false);
  const[rot,setRot]=useObjState(0);
  const[zoom,setZoom]=useObjState(1);
  const stopRef=useObjRef(null);
  const saved=(state.savedObjects||[]).includes(o.id);
  useObjEffect(()=>()=>{ if(stopRef.current) stopRef.current(); },[]);
  function startAr(){
    setAr(true);
    if(o.kind==='ar-music'){ setPlaying(true); stopRef.current=playMarch(); setTimeout(()=>setPlaying(false),6500); }
  }
  function handleSave(){
    actions.saveObject(o.id);
    showToast(`${t('savedToast')} · +${o.xp} ${t('xp')}`,{icon:<Ic k="check" size={15} color="#34C759"/>});
  }
  return <div data-screen-label="Object Result" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg}}>
    <Photo src={objImg} alt={L(o.name)} h={260} radius={0} overlay="linear-gradient(180deg,rgba(16,12,28,.1),rgba(16,12,28,.8))">
      
      <div style={{position:'absolute',top:'calc(12px + var(--cu-safe-top))',left:14}}><IconBtn k="arrowL" onDark onClick={nav.pop} ariaLabel={t('back')}/></div>
      <div style={{position:'absolute',left:20,right:20,bottom:20}}>
        <Chip label={`✓ ${t('objectFound')}`} kind="green" dot/>
        <h1 style={{display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden',color:'#fff',fontSize:fz(26),fontWeight:700,fontFamily:FD,letterSpacing:'-0.5px',margin:'12px 0 6px',lineHeight:1.18}}>{L(o.name)}</h1>
        <p style={{color:'rgba(255,255,255,.88)',fontSize:fz(14),fontFamily:F,margin:0,display:'flex',alignItems:'center',gap:5,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}><Ic k="location" size={14} style={{flexShrink:0}}/><span style={{overflow:'hidden',textOverflow:'ellipsis'}}>{L(o.where)}</span></p>
      </div>
    </Photo>
    <div style={{padding:`20px ${SP.safe}px 0`}}>
      <div style={{display:'flex',gap:10,marginBottom:20}}>
        {[{l:lang==='de'?'Jahr':'Year',v:o.year},{l:lang==='de'?'Urheber':'Maker',v:L(o.maker)}].map((s,i)=>
          <div key={i} style={{flex:1,padding:'14px 16px',borderRadius:14,background:T.card,border:`0.5px solid ${T.line}`,boxShadow:SH}}>
            <div style={{color:T.muted,fontSize:fz(12),fontFamily:F,marginBottom:4}}>{s.l}</div>
            <div style={{color:T.text,fontSize:fz(14),fontWeight:700,fontFamily:F,lineHeight:1.25}}>{s.v}</div>
          </div>)}
      </div>
      {!ar
        ?<button type="button" onClick={startAr} className="cu-press" style={{display:'block',width:'100%',textAlign:'left',padding:18,borderRadius:20,background:GRAD,border:'none',cursor:'pointer',boxShadow:SHmd,marginBottom:24,position:'relative',overflow:'hidden'}}>
          <span style={{position:'relative',display:'flex',gap:13,alignItems:'center'}}>
            <span style={{width:50,height:50,borderRadius:15,background:'rgba(255,255,255,.22)',display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',flexShrink:0}}><Ic k={o.kind==='ar-music'?'bolt':o.kind==='ar-zoom'?'search':'sparkle'} size={26} fill/></span>
            <span style={{flex:1}}>
              <span style={{display:'block',color:'rgba(255,255,255,.85)',fontSize:fz(11.5),fontWeight:700,fontFamily:F,textTransform:'uppercase',letterSpacing:'.5px'}}>{t('arExperience')}</span>
              <span style={{display:'block',color:'#fff',fontSize:fz(16),fontWeight:700,fontFamily:FD,marginTop:4}}>{L(o.action)}</span>
            </span>
            <Ic k="arrowR" size={22} color="#fff"/>
          </span>
        </button>
        :<div className="cu-rise" style={{borderRadius:20,overflow:'hidden',boxShadow:SHmd,marginBottom:24,border:`0.5px solid ${T.line}`}}>
          <div style={{position:'relative',height:200,background:'#15101F',display:'flex',alignItems:'center',justifyContent:'center',overflow:'hidden'}}>
            <img src={objImg} alt="" style={{position:'absolute',inset:0,width:'100%',height:'100%',objectFit:'cover',opacity:.32,transform:o.kind==='ar-zoom'?`scale(${zoom})`:'none',transition:'transform .15s'}}/>
            {o.kind==='ar-music'&&<div style={{position:'relative',textAlign:'center'}}>
              <div className={playing?'cu-pulse':''} style={{width:96,height:96,borderRadius:'50%',background:GRAD,display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 10px',boxShadow:'0 8px 30px rgba(0,0,0,.4)'}}><span style={{fontSize:44}}>{o.emoji}</span></div>
              <span style={{color:'#fff',fontSize:fz(13),fontWeight:700,fontFamily:F}}>{playing?`♪ ${t('nowPlaying')}: ${o.track}`:t('tapToReplay')}</span>
            </div>}
            {o.kind==='ar-3d'&&<div style={{position:'relative',transform:`rotateY(${rot}deg)`,transition:'transform .1s',fontSize:88,filter:'drop-shadow(0 10px 24px rgba(0,0,0,.5))'}}>{o.emoji}</div>}
            {o.kind==='ar-zoom'&&<span style={{position:'relative',fontSize:72,filter:'drop-shadow(0 10px 24px rgba(0,0,0,.5))'}}>{o.emoji}</span>}
          </div>
          <div style={{padding:'14px 16px',background:T.card}}>
            {o.kind==='ar-music'&&<button type="button" onClick={()=>{ if(stopRef.current)stopRef.current(); setPlaying(true); stopRef.current=playMarch(); setTimeout(()=>setPlaying(false),6500); }} className="cu-press" style={{width:'100%',minHeight:46,borderRadius:13,border:'none',background:tint(10),color:'var(--ink-deep)',fontSize:fz(14),fontWeight:700,fontFamily:F,cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',gap:8}}><Ic k="bolt" size={17} fill/>{t('tapToReplay')}</button>}
            {o.kind==='ar-3d'&&<><div style={{color:T.muted,fontSize:fz(12),fontFamily:F,textAlign:'center',marginBottom:8}}>{t('dragToRotate')}</div>
              <input type="range" min="0" max="360" value={rot} onChange={e=>setRot(+e.target.value)} aria-label={t('dragToRotate')} style={{width:'100%',accentColor:'var(--ink)'}}/></>}
            {o.kind==='ar-zoom'&&<><div style={{color:T.muted,fontSize:fz(12),fontFamily:F,textAlign:'center',marginBottom:8}}>{t('pinchToZoom')} · {Math.round(zoom*100)}%</div>
              <input type="range" min="100" max="320" value={zoom*100} onChange={e=>setZoom(+e.target.value/100)} aria-label={t('gigapixel')} style={{width:'100%',accentColor:'var(--ink)'}}/></>}
          </div>
        </div>}
      <h2 style={{color:T.text,fontSize:fz(17),fontWeight:700,fontFamily:FD,margin:'0 0 12px'}}>{t('aboutThis')}</h2>
      <p style={{color:T.sub,fontSize:fz(15),fontFamily:F,lineHeight:1.65,margin:'0 0 28px'}}>{L(o.blurb)}</p>
    </div>
    <div style={{padding:`0 ${SP.safe}px 32px`,display:'flex',flexDirection:'column',gap:10}}>
      {saved
        ?<div className="cu-rise" style={{display:'flex',alignItems:'center',justifyContent:'center',gap:8,minHeight:52,borderRadius:14,background:T.greenBg,border:`0.5px solid ${T.greenLine}`,color:T.green,fontSize:fz(15),fontWeight:700,fontFamily:F}}><span className="cu-pop" style={{display:'flex'}}><Ic k="check" size={18} stroke={3}/></span>{t('saved')} · +{o.xp} {t('xp')} {t('earnedXP')}</div>
        :<Btn label={`${t('saveToCollection')} · +${o.xp} ${t('xp')}`} icon={<Ic k="bolt" size={18} fill/>} onClick={handleSave}/>}
      <Btn label={t('scanObject')} variant="secondary" icon={<Ic k="scan" size={18}/>} onClick={()=>nav.replace('object-scan',{objectId:o.id})}/>
    </div>
  </div>;
}

Object.assign(window,{ObjectScanScreen,ObjectResultScreen});
