// Wander — Location permission screen
// A dedicated, on-brand gate that explains *why* the tour wants your position,
// then asks for it. Because this prototype usually runs far from Singapore,
// it gracefully falls back to a simulated walk and says so plainly.

function LocationScreen({ onDone, onSkip, brand }) {
  // status: ask | locating | real | sim | denied | unsupported
  const [status, setStatus] = React.useState('ask');
  const geo = window.WanderGeo;
  const supported = geo && geo.supported();

  // A gentle marina-loop route the sim can stroll while you're on the map.
  const marinaRoute = React.useMemo(() => {
    const N = (window.WANDER_DATA && window.WANDER_DATA.NEARBY) || [];
    return N.filter(p => p.lat != null).map(p => ({ lat: p.lat, lng: p.lng }));
  }, []);

  const enable = async () => {
    if (!geo) { onDone && onDone(); return; }
    setStatus('locating');
    const mode = await geo.start({ route: marinaRoute, loop: true, speed: 16 });
    const snap = geo.get();
    if (mode === 'real') setStatus('real');
    else if (snap.status === 'denied') setStatus('denied');
    else if (snap.status === 'unsupported') setStatus('unsupported');
    else setStatus('sim');
  };

  // Once we have a position (real or simulated), give the user a beat to read
  // the result, then continue into the map.
  React.useEffect(() => {
    if (status === 'real' || status === 'sim' || status === 'denied' || status === 'unsupported') {
      const t = setTimeout(() => onDone && onDone(), 1400);
      return () => clearTimeout(t);
    }
  }, [status]);

  const result = {
    real:        { icon:'📍', tone:'var(--w-mint)',   head:"You're located.",            sub:"Live position locked — your dot will follow you on the map." },
    sim:         { icon:'🧭', tone:'var(--w-yellow)',  head:'Demo mode — simulated walk.', sub:"We can't reach you in Singapore from here, so we'll stroll the route for you." },
    denied:      { icon:'🛰️', tone:'var(--w-coral)',   head:'Location blocked.',          sub:"No problem — we'll simulate the walk so you can still see it work." },
    unsupported: { icon:'🧭', tone:'var(--w-yellow)',  head:'No GPS here.',               sub:"This browser can't share location, so we'll simulate the walk instead." },
  }[status];

  return (
    <div style={{ height:'100%', background:'var(--w-cream)', display:'flex', flexDirection:'column', paddingTop:60, paddingBottom:40 }}>
      <div style={{ display:'flex', justifyContent:'flex-end', padding:'0 22px' }}>
        <button onClick={onSkip} style={{ background:'none', border:'none', color:'var(--w-mute)', fontFamily:'inherit', fontSize:15, fontWeight:600, cursor:'pointer', padding:8 }}>Not now</button>
      </div>

      <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', padding:'10px 32px' }}>
        <LocationRadar active={status==='locating'} done={!!result} icon={result?result.icon:'📍'} brand={brand}/>
      </div>

      <div style={{ padding:'0 32px' }}>
        {!result ? (
          <React.Fragment>
            <h1 className="t-display" style={{ fontSize:34, lineHeight:1.15, margin:0, marginBottom:18, color:'var(--w-ink)' }}>
              Follow the tour, hands-free.
            </h1>
            <p style={{ fontSize:16, lineHeight:1.5, color:'var(--w-slate)', margin:0 }}>
              With your location on, Wander shows your live position, tells you how far each stop is, and starts the story automatically the moment you arrive.
            </p>
            <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:18 }}>
              {[
                ['🔵','A live dot that moves as you walk'],
                ['📏','Real-time distance & walking time to every stop'],
                ['🎧','Narration that auto-plays when you reach a landmark'],
              ].map(([e,t]) => (
                <div key={t} style={{ display:'flex', gap:12, alignItems:'center', fontSize:14.5, color:'var(--w-ink)' }}>
                  <span style={{ fontSize:18, width:24, textAlign:'center' }}>{e}</span>{t}
                </div>
              ))}
            </div>
            <div style={{ fontSize:12.5, color:'var(--w-mute)', marginTop:16, lineHeight:1.4 }}>
              We only use location while a tour is open, and never share it. {supported ? '' : 'This browser has no GPS, so a simulated walk is used.'}
            </div>
          </React.Fragment>
        ) : (
          <div key={status} style={{ animation:'wFadeUp .4s ease-out both' }}>
            <h1 className="t-display" style={{ fontSize:32, lineHeight:1.15, margin:0, marginBottom:12, color:'var(--w-ink)' }}>{result.head}</h1>
            <p style={{ fontSize:16, lineHeight:1.5, color:'var(--w-slate)', margin:0 }}>{result.sub}</p>
          </div>
        )}
      </div>

      <div style={{ padding:'28px 22px 0' }}>
        {!result && (
          <button className="w-btn" onClick={enable} disabled={status==='locating'} style={{ width:'100%', height:56, opacity:status==='locating'?0.7:1 }}>
            {status==='locating'
              ? <React.Fragment><Spinner/> Locating…</React.Fragment>
              : <React.Fragment><Icon.loc size={18} color="var(--w-yellow-ink)"/> Enable location</React.Fragment>}
          </button>
        )}
        {result && (
          <button className="w-btn" onClick={()=>onDone && onDone()} style={{ width:'100%', height:56 }}>
            Continue to map <Icon.arrow size={18}/>
          </button>
        )}
      </div>
    </div>
  );
}

function LocationRadar({ active, done, icon, brand }) {
  const accent = brand || '#FFC93C';
  return (
    <div style={{ width:260, height:260, position:'relative' }}>
      {[0,1,2,3].map(i => (
        <div key={i} style={{ position:'absolute', inset:i*26+'px', borderRadius:'50%',
          border:`1.5px dashed rgba(255,201,60,${0.8-i*0.16})`,
          animation:(active||done)?`wPulse 2.6s ${i*0.35}s ease-in-out infinite`:'none' }}/>
      ))}
      {/* sweeping radar line while locating */}
      {active && (
        <div style={{ position:'absolute', inset:6, borderRadius:'50%', overflow:'hidden' }}>
          <div style={{ position:'absolute', left:'50%', top:'50%', width:'50%', height:2, transformOrigin:'left center',
            background:`linear-gradient(90deg,${accent},transparent)`, animation:'wSpin 1.4s linear infinite' }}/>
        </div>
      )}
      <div style={{ position:'absolute', left:'50%', top:'50%', transform:'translate(-50%,-50%)', width:88, height:88,
        borderRadius:28, background:done?'linear-gradient(135deg,#2DD4A7,#4FB7E8)':'linear-gradient(135deg,#FFC93C,#F5A623)',
        boxShadow:'0 12px 28px rgba(255,201,60,0.5)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:44,
        transition:'background .4s' }}>{icon}</div>
    </div>
  );
}

function Spinner() {
  return <span style={{ display:'inline-block', width:16, height:16, borderRadius:'50%', border:'2.5px solid rgba(0,0,0,0.25)', borderTopColor:'var(--w-yellow-ink)', animation:'wSpin .8s linear infinite', marginRight:2 }}/>;
}

Object.assign(window, { LocationScreen });
