// Wander — Active tour player with real audio support

function PlayerScreen({ tourId, onBack, onComplete, dense }) {
  const { TOURS, STOPS } = window.WANDER_DATA;
  const tour = TOURS.find(t => t.id===tourId) || TOURS[0];
  const [playing, setPlaying] = React.useState(false);
  const [stopIdx, setStopIdx] = React.useState(2);
  const stop = STOPS[stopIdx];
  const [progress, setProgress] = React.useState(0.34);
  const [tab, setTab] = React.useState('story');
  const audioRef = React.useRef(null);

  // Sync simulated progress when no real audio
  React.useEffect(() => {
    if (tour.audio_url) return; // real audio handles progress
    if (!playing) return;
    const id = setInterval(() => setProgress(p => p>=1 ? 0 : Math.min(1, p+0.004)), 100);
    return () => clearInterval(id);
  }, [playing, tour.audio_url]);

  // Sync real audio
  React.useEffect(() => {
    const el = audioRef.current;
    if (!el) return;
    if (playing) el.play().catch(()=>{});
    else el.pause();
  }, [playing]);

  const handleAudioTimeUpdate = (e) => {
    const el = e.target;
    if (el.duration) setProgress(el.currentTime / el.duration);
  };

  return (
    <div style={{ height:'100%', overflow:'hidden', position:'relative', background:`linear-gradient(180deg,${tour.hero[0]} 0%,${tour.hero[1]} 50%,var(--w-ink) 100%)` }}>
      {/* Hidden real audio element */}
      {tour.audio_url && (
        <audio ref={audioRef} src={tour.audio_url} onTimeUpdate={handleAudioTimeUpdate} onEnded={()=>setPlaying(false)} style={{ display:'none' }}/>
      )}

      {/* Top bar */}
      <div style={{ position:'absolute', top:56, left:16, right:16, zIndex:30, display:'flex', alignItems:'center', gap:12 }}>
        <button onClick={onBack} style={{ width:42, height:42, borderRadius:21, background:'rgba(0,0,0,0.25)', backdropFilter:'blur(10px)', border:'none', cursor:'pointer', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.back size={18} color="#fff"/></button>
        <div style={{ flex:1, textAlign:'center', color:'#fff' }}>
          <div style={{ fontSize:11, opacity:0.85, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>Now Playing</div>
          <div style={{ fontWeight:700, fontSize:14, marginTop:1 }}>{tour.title}</div>
        </div>
        <button onClick={onComplete} style={{ height:42, padding:'0 14px', borderRadius:21, background:'rgba(0,0,0,0.25)', backdropFilter:'blur(10px)', border:'none', cursor:'pointer', color:'#fff', fontWeight:700, fontSize:13, fontFamily:'inherit' }}>End</button>
      </div>

      {/* Stop progress dots */}
      <div style={{ position:'absolute', top:110, left:22, right:22, zIndex:20, display:'flex', gap:4 }}>
        {STOPS.map((s,i) => (
          <div key={s.id} style={{ flex:1, height:4, borderRadius:2, background:i<stopIdx?'#fff':i===stopIdx?'rgba(255,255,255,0.8)':'rgba(255,255,255,0.25)', position:'relative', overflow:'hidden' }}>
            {i===stopIdx && <div style={{ position:'absolute', inset:0, width:progress*100+'%', background:'#fff' }}/>}
          </div>
        ))}
      </div>

      {/* Album art */}
      <div style={{ position:'absolute', top:140, left:0, right:0, height:280, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <div style={{ width:240, height:240, borderRadius:40, background:`linear-gradient(135deg,${tour.hero[0]},${tour.hero[1]})`, boxShadow:'0 24px 60px rgba(0,0,0,0.35),inset 0 0 0 6px rgba(255,255,255,0.18)', display:'flex', alignItems:'center', justifyContent:'center', position:'relative', overflow:'hidden', animation:playing?'wFloat 4s ease-in-out infinite':'none' }}>
          <div style={{ position:'absolute', top:-30, right:-40, width:160, height:160, borderRadius:'50%', background:'rgba(255,255,255,0.18)' }}/>
          <div style={{ position:'absolute', bottom:-40, left:-30, width:130, height:130, borderRadius:'50%', background:'rgba(0,0,0,0.12)' }}/>
          <div style={{ fontSize:110, filter:'drop-shadow(0 8px 20px rgba(0,0,0,0.25))', position:'relative', zIndex:1 }}>{tour.emoji}</div>
        </div>
      </div>

      {/* Glass control sheet */}
      <div style={{ position:'absolute', bottom:0, left:0, right:0, background:'rgba(26,24,18,0.55)', backdropFilter:'blur(24px) saturate(180%)', WebkitBackdropFilter:'blur(24px) saturate(180%)', borderRadius:'32px 32px 0 0', padding:'20px 22px 30px', color:'#fff', boxShadow:'0 -10px 40px rgba(0,0,0,0.25)' }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:4 }}>
          <span style={{ fontSize:11, color:'var(--w-yellow)', fontWeight:700, letterSpacing:0.5, textTransform:'uppercase' }}>Stop {stopIdx+1} of {STOPS.length}</span>
          <span style={{ fontSize:11, opacity:0.7, fontWeight:600 }}>{Math.round(progress*7)}:{String(Math.round(progress*60)%60).padStart(2,'0')} / 7:00</span>
        </div>
        <div className="t-display" style={{ fontSize:26, fontWeight:600, lineHeight:1.1 }}>{stop.name}</div>
        <div style={{ fontSize:13, opacity:0.75, marginTop:4, fontStyle:'italic', fontFamily:'var(--w-display)' }}>"{stop.blurb}"</div>

        <Waveform progress={progress} playing={playing}/>

        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:18 }}>
          <button style={ctrlBtn(40)}><Icon.back15 size={22} color="#fff"/></button>
          <button onClick={()=>setStopIdx(Math.max(0,stopIdx-1))} style={ctrlBtn(48)}>
            <svg viewBox="0 0 24 24" width="20" height="20" fill="#fff"><path d="M19 5v14l-9-7zM5 5h3v14H5z"/></svg>
          </button>
          <button onClick={()=>setPlaying(!playing)} style={{ width:72, height:72, borderRadius:36, border:'none', cursor:'pointer', background:'var(--w-yellow)', color:'var(--w-yellow-ink)', boxShadow:'0 8px 24px rgba(255,201,60,0.5)', display:'flex', alignItems:'center', justifyContent:'center' }}>
            {playing ? <Icon.pause size={26} color="var(--w-yellow-ink)"/> : <Icon.play size={28} color="var(--w-yellow-ink)"/>}
          </button>
          <button onClick={()=>setStopIdx(Math.min(STOPS.length-1,stopIdx+1))} style={ctrlBtn(48)}><Icon.skip size={20} color="#fff"/></button>
          <button style={ctrlBtn(40)}><Icon.fwd15 size={22} color="#fff"/></button>
        </div>

        <div style={{ display:'flex', gap:8, marginTop:18 }}>
          {[{id:'story',label:'Story',i:<Icon.text size={14} color="currentColor"/>},{id:'ar',label:'AR',i:<Icon.ar size={14} color="currentColor"/>},{id:'quiz',label:'Quiz',i:<Icon.quiz size={14} color="currentColor"/>}].map(t => (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{ flex:1, height:44, borderRadius:14, border:'none', cursor:'pointer', background:tab===t.id?'rgba(255,201,60,0.18)':'rgba(255,255,255,0.08)', color:tab===t.id?'var(--w-yellow)':'#fff', fontWeight:700, fontSize:13, fontFamily:'inherit', display:'flex', alignItems:'center', justifyContent:'center', gap:6, transition:'all .2s' }}>{t.i} {t.label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

const ctrlBtn = (size) => ({ width:size, height:size, borderRadius:size/2, background:'rgba(255,255,255,0.1)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' });

function Waveform({ progress, playing }) {
  const bars = 56;
  return (
    <div style={{ display:'flex', gap:2.5, alignItems:'center', height:36, marginTop:14 }}>
      {Array.from({length:bars}).map((_,i) => {
        const passed = i/bars < progress;
        const h = 8 + Math.sin(i*0.7)*6 + Math.sin(i*1.3)*8 + 14;
        return <div key={i} style={{ flex:1, height:Math.max(4,h), borderRadius:1.5, background:passed?'var(--w-yellow)':'rgba(255,255,255,0.3)', animation:playing&&passed?`wWave 1s ${i*0.04}s ease-in-out infinite`:'none', transformOrigin:'center' }}/>;
      })}
    </div>
  );
}

Object.assign(window, { PlayerScreen });
