// Wander — Browse, Search, Saved, Profile, Paywall (Stripe), Completion, Offline

// ─── BROWSE ───────────────────────────────────────────────────────────────────
function BrowseScreen({ onOpenTour, onTab, onSearch, dense }) {
  const { TOURS } = window.WANDER_DATA;
  const [cat, setCat] = React.useState('All');
  const cats = ['All','Free','Food','History','Architecture','Nature','After dark'];
  const featured = TOURS[1];
  const list = cat==='Free' ? TOURS.filter(t=>t.tier==='free') : TOURS;

  return (
    <div style={{ height:'100%', overflowY:'auto', background:'var(--w-cream)', paddingBottom:100 }} className="no-scroll app-scroll">
      <div style={{ padding:'60px 22px 16px' }}>
        <div style={{ fontSize:13, color:'var(--w-mute)', fontWeight:600 }}>Tours · Singapore</div>
        <h1 className="t-display" style={{ fontSize:36, fontWeight:600, lineHeight:1, margin:'4px 0 0' }}>Where to next?</h1>
      </div>
      <div style={{ padding:'0 22px 16px' }}>
        <button onClick={onSearch} style={{ width:'100%', height:50, borderRadius:25, background:'var(--w-paper)', border:'none', boxShadow:'inset 0 0 0 1px var(--w-line)', display:'flex', alignItems:'center', gap:10, padding:'0 18px', fontFamily:'inherit', cursor:'pointer', textAlign:'left' }}>
          <Icon.search size={18} color="var(--w-mute)"/>
          <span style={{ color:'var(--w-mute)', fontSize:15 }}>Search neighbourhoods, vibes…</span>
        </button>
      </div>
      <div style={{ display:'flex', gap:8, padding:'0 22px 18px', overflowX:'auto' }} className="no-scroll">
        {cats.map(c => (
          <button key={c} onClick={()=>setCat(c)} style={{ padding:'10px 16px', borderRadius:999, border:'none', cursor:'pointer', background:cat===c?'var(--w-ink)':'var(--w-paper)', color:cat===c?'var(--w-yellow)':'var(--w-ink)', fontWeight:700, fontSize:13, fontFamily:'inherit', flexShrink:0, boxShadow:cat===c?'none':'inset 0 0 0 1px var(--w-line)' }}>{c}</button>
        ))}
      </div>
      <div style={{ padding:'0 22px 22px' }}>
        <button onClick={()=>onOpenTour(featured.id)} style={{ width:'100%', border:'none', padding:0, background:'transparent', cursor:'pointer', textAlign:'left', fontFamily:'inherit', position:'relative' }}>
          <TourArt tour={featured} h={220} rounded={24}/>
          <div style={{ position:'absolute', bottom:14, left:14, right:14, background:'rgba(26,24,18,0.6)', backdropFilter:'blur(20px)', borderRadius:18, padding:14, color:'#fff' }}>
            <div style={{ fontSize:11, color:'var(--w-yellow)', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase', display:'flex', alignItems:'center', gap:6 }}><Icon.sparkle size={11} color="var(--w-yellow)"/> Editor's pick</div>
            <div className="t-display" style={{ fontSize:22, fontWeight:600, marginTop:4 }}>{featured.title}</div>
            <div style={{ fontSize:12, opacity:0.8, marginTop:2 }}>{featured.duration} · {featured.stops} stops · ★ {featured.rating}</div>
          </div>
        </button>
      </div>
      <div style={{ padding:'0 22px' }}>
        <div className="t-display" style={{ fontSize:22, fontWeight:600, marginBottom:12 }}>All tours</div>
        <div style={{ display:'grid', gap:dense?10:14 }}>
          {list.map(t => (
            <button key={t.id} onClick={()=>onOpenTour(t.id)} style={{ display:'flex', gap:12, padding:dense?8:10, background:'var(--w-paper)', borderRadius:20, border:'none', boxShadow:'var(--sh-card)', cursor:'pointer', textAlign:'left', fontFamily:'inherit', alignItems:'center' }}>
              <div style={{ width:dense?76:92, height:dense?76:92, flexShrink:0 }}><TourArt tour={t} h={dense?76:92} rounded={14}/></div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ display:'flex', gap:6, marginBottom:4 }}>
                  {t.tier==='pro' ? <span className="w-chip w-chip--pro" style={{ padding:'3px 8px', fontSize:10 }}>PRO</span> : <span className="w-chip w-chip--free" style={{ padding:'3px 8px', fontSize:10 }}>FREE</span>}
                </div>
                <div style={{ fontWeight:700, fontSize:15, lineHeight:1.2, color:'var(--w-ink)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{t.title}</div>
                <div style={{ fontSize:12, color:'var(--w-mute)', marginTop:4 }}>{t.duration} · {t.stops} stops · ★ {t.rating}</div>
              </div>
              <Icon.arrow size={16} color="var(--w-mute)"/>
            </button>
          ))}
        </div>
      </div>
      <TabBar active="browse" onChange={onTab}/>
    </div>
  );
}

// ─── SEARCH ───────────────────────────────────────────────────────────────────
function SearchScreen({ onClose, onOpenTour }) {
  const { TOURS } = window.WANDER_DATA;
  const [q, setQ] = React.useState('');
  const recent = ['Hawker','Sunset spots','Free tours','Architecture','Family-friendly'];
  const matches = q ? TOURS.filter(t => t.title.toLowerCase().includes(q.toLowerCase()) || t.subtitle.toLowerCase().includes(q.toLowerCase())) : [];

  return (
    <div style={{ height:'100%', background:'var(--w-cream)', overflowY:'auto' }} className="no-scroll app-scroll">
      <div style={{ padding:'56px 16px 14px', display:'flex', gap:10, alignItems:'center' }}>
        <div style={{ flex:1, height:50, borderRadius:25, background:'var(--w-paper)', boxShadow:'inset 0 0 0 1.5px var(--w-yellow)', display:'flex', alignItems:'center', gap:10, padding:'0 16px' }}>
          <Icon.search size={18} color="var(--w-slate)"/>
          <input autoFocus value={q} onChange={e=>setQ(e.target.value)} placeholder="Search tours…" style={{ flex:1, border:'none', outline:'none', background:'transparent', fontFamily:'inherit', fontSize:15, color:'var(--w-ink)' }}/>
        </div>
        <button onClick={onClose} style={{ background:'none', border:'none', fontFamily:'inherit', fontSize:15, fontWeight:600, color:'var(--w-ink)', cursor:'pointer' }}>Cancel</button>
      </div>
      {!q ? (
        <div style={{ padding:'8px 22px' }}>
          <div style={{ fontSize:11, color:'var(--w-mute)', fontWeight:700, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>Recent</div>
          {recent.map(r => (
            <div key={r} onClick={()=>setQ(r)} style={{ display:'flex', alignItems:'center', gap:12, padding:'14px 0', borderBottom:'1px solid var(--w-line)', cursor:'pointer' }}>
              <Icon.search size={16} color="var(--w-mute)"/><span style={{ flex:1, fontSize:15 }}>{r}</span><Icon.arrow size={14} color="var(--w-mute)"/>
            </div>
          ))}
          <div style={{ marginTop:28, fontSize:11, color:'var(--w-mute)', fontWeight:700, letterSpacing:0.5, textTransform:'uppercase', marginBottom:12 }}>Trending in Singapore</div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {['Chinatown food','Sunset Marina','Hidden gardens','Heritage shophouses','Peranakan Joo Chiat'].map(t => (
              <button key={t} onClick={()=>setQ(t)} style={{ padding:'10px 14px', borderRadius:999, border:'none', background:'var(--w-yellow-soft)', color:'var(--w-yellow-ink)', fontWeight:700, fontSize:13, fontFamily:'inherit', cursor:'pointer' }}>{t}</button>
            ))}
          </div>
        </div>
      ) : (
        <div style={{ padding:'8px 22px' }}>
          <div style={{ fontSize:13, color:'var(--w-mute)', marginBottom:10 }}>{matches.length} {matches.length===1?'result':'results'}</div>
          {matches.map(t => (
            <div key={t.id} onClick={()=>onOpenTour(t.id)} style={{ display:'flex', gap:12, padding:'12px 0', cursor:'pointer', borderBottom:'1px solid var(--w-line)', alignItems:'center' }}>
              <div style={{ width:56, height:56 }}><TourArt tour={t} h={56} rounded={12}/></div>
              <div style={{ flex:1 }}><div style={{ fontWeight:700, fontSize:15 }}>{t.title}</div><div style={{ fontSize:12, color:'var(--w-mute)' }}>{t.subtitle}</div></div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── SAVED ────────────────────────────────────────────────────────────────────
function SavedScreen({ onTab, onOpenTour, onOpenOffline, dense }) {
  const { TOURS } = window.WANDER_DATA;
  const saved = TOURS.slice(0,4);
  return (
    <div style={{ height:'100%', overflowY:'auto', background:'var(--w-cream)', paddingBottom:120 }} className="no-scroll app-scroll">
      <div style={{ padding:'60px 22px 14px' }}>
        <div style={{ fontSize:13, color:'var(--w-mute)', fontWeight:600 }}>Saved</div>
        <h1 className="t-display" style={{ fontSize:36, fontWeight:600, lineHeight:1, margin:'4px 0 0' }}>Your library</h1>
      </div>
      <div style={{ display:'flex', gap:6, padding:'4px 22px 18px' }}>
        {['Wishlist','Downloaded','Completed'].map((t,i) => (
          <button key={t} onClick={()=>i===1&&onOpenOffline()} style={{ flex:1, height:38, borderRadius:19, border:'none', cursor:'pointer', background:i===0?'var(--w-ink)':'transparent', color:i===0?'var(--w-yellow)':'var(--w-slate)', fontWeight:700, fontSize:13, fontFamily:'inherit', boxShadow:i===0?'none':'inset 0 0 0 1px var(--w-line)' }}>{t}</button>
        ))}
      </div>
      <div style={{ padding:'0 22px', display:'grid', gap:dense?10:14 }}>
        {saved.map(t => (
          <div key={t.id} onClick={()=>onOpenTour(t.id)} style={{ background:'var(--w-paper)', borderRadius:22, padding:12, display:'flex', gap:14, alignItems:'center', boxShadow:'var(--sh-card)', cursor:'pointer' }}>
            <div style={{ width:80, height:80 }}><TourArt tour={t} h={80} rounded={14}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:700, fontSize:15 }}>{t.title}</div>
              <div style={{ fontSize:12, color:'var(--w-mute)', marginTop:4 }}>{t.duration} · {t.stops} stops</div>
              <div style={{ display:'flex', gap:4, marginTop:6 }}>{t.formats.slice(0,3).map(f=>formatIcon(f,13,'var(--w-mute)'))}</div>
            </div>
            <Icon.heart size={20} color="var(--w-coral)" filled/>
          </div>
        ))}
      </div>
      <TabBar active="saved" onChange={onTab}/>
    </div>
  );
}

// ─── PROFILE ──────────────────────────────────────────────────────────────────
function ProfileScreen({ onTab, dense, authUser, authToken, onGoAuth, onGoCreator, onLogout }) {
  const [showPassForm, setShowPassForm] = React.useState(false);
  const [passForm, setPassForm]         = React.useState({ current:'', next:'', confirm:'' });
  const [passErr, setPassErr]           = React.useState('');
  const [passOk, setPassOk]             = React.useState('');
  const [savingPass, setSavingPass]     = React.useState(false);

  const handleChangePass = async e => {
    e.preventDefault();
    if (passForm.next !== passForm.confirm) { setPassErr('Passwords do not match'); return; }
    setSavingPass(true); setPassErr(''); setPassOk('');
    try {
      const r = await fetch('/api/auth/me', {
        method:'PUT',
        headers:{ 'Content-Type':'application/json', Authorization:`Bearer ${authToken}` },
        body: JSON.stringify({ currentPassword: passForm.current, newPassword: passForm.next }),
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error);
      setPassOk('Password updated ✓');
      setPassForm({ current:'', next:'', confirm:'' });
      setShowPassForm(false);
    } catch(e) { setPassErr(e.message); }
    finally { setSavingPass(false); }
  };

  const badges = ['🦁 Singapore explorer','🌅 Sunrise walker','🍜 Hawker hunter','📜 History buff'];
  const memberSince = authUser ? new Date(authUser.created_at).toLocaleDateString('en-SG',{month:'long',year:'numeric'}) : null;

  const inputSty = { width:'100%', padding:'12px 14px', borderRadius:12, border:'1.5px solid var(--w-line)', fontSize:14, fontFamily:'inherit', color:'var(--w-ink)', background:'#fff', boxSizing:'border-box', outline:'none' };

  // ── GUEST VIEW ─────────────────────────────────────────────────────────────
  if (!authUser) {
    const perks = [
      ['🎙️','Upload audio narrations','Record stories and guide travelers by voice'],
      ['📹','Add video content','Show beautiful footage along your route'],
      ['💰','Earn from Pro tours','Set your own price and keep 100% of earnings'],
      ['📍','Build interactive routes','Add stops, facts, and rich descriptions'],
    ];
    return (
      <div style={{ height:'100%', overflowY:'auto', background:'var(--w-cream)', paddingBottom:120 }} className="no-scroll app-scroll">
        <IOSStatusBar/>
        {/* Hero band */}
        <div style={{ background:'var(--w-yellow)', padding:'52px 22px 70px', position:'relative', overflow:'hidden', textAlign:'center' }}>
          <div style={{ position:'absolute', top:-40, right:-40, width:200, height:200, borderRadius:'50%', background:'rgba(255,255,255,0.22)' }}/>
          <div style={{ position:'absolute', bottom:-50, left:-30, width:160, height:160, borderRadius:'50%', background:'rgba(245,166,35,0.3)' }}/>
          <div style={{ position:'relative' }}>
            <div style={{ fontSize:52, marginBottom:10 }}>🧭</div>
            <h1 className="t-display" style={{ fontSize:26, fontWeight:600, margin:'0 0 6px', color:'var(--w-yellow-ink)' }}>Become a Creator</h1>
            <p style={{ fontSize:13, color:'rgba(58,42,6,0.75)', margin:0, lineHeight:1.5 }}>Share your local knowledge with<br/>travelers who want the real story.</p>
          </div>
        </div>

        <div style={{ padding:'0 20px', marginTop:-32, position:'relative' }}>
          {/* Perks */}
          <div style={{ background:'var(--w-paper)', borderRadius:24, padding:18, boxShadow:'var(--sh-pop)', marginBottom:14 }}>
            {perks.map(([icon,title,desc],i,a)=>(
              <div key={title} style={{ display:'flex', gap:14, alignItems:'flex-start', padding:'14px 0', borderBottom:i<a.length-1?'1px solid var(--w-line)':'none' }}>
                <div style={{ width:40, height:40, borderRadius:12, background:'var(--w-yellow-soft)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:20, flexShrink:0 }}>{icon}</div>
                <div>
                  <div style={{ fontWeight:700, fontSize:14, color:'var(--w-ink)', marginBottom:2 }}>{title}</div>
                  <div style={{ fontSize:12, color:'var(--w-mute)', lineHeight:1.4 }}>{desc}</div>
                </div>
              </div>
            ))}
          </div>

          {/* CTAs */}
          <button className="w-btn" style={{ width:'100%', height:52, marginBottom:10 }} onClick={()=>onGoAuth('register')}>
            Create free account
          </button>
          <button style={{ width:'100%', height:48, borderRadius:9999, border:'1.5px solid var(--w-line)', background:'transparent', fontFamily:'inherit', fontWeight:700, fontSize:15, color:'var(--w-mute)', cursor:'pointer' }} onClick={()=>onGoAuth('login')}>
            Sign in
          </button>

          {/* Static settings */}
          <div className="t-display" style={{ fontSize:20, fontWeight:600, marginTop:28, marginBottom:12 }}>Settings</div>
          <div style={{ background:'var(--w-paper)', borderRadius:18, overflow:'hidden' }}>
            {['Language · English','Voice · Mei Ling','Notifications','Help & Feedback'].map((s,i,a)=>(
              <div key={s} style={{ padding:'16px 18px', display:'flex', alignItems:'center', borderBottom:i<a.length-1?'1px solid var(--w-line)':'none' }}>
                <span style={{ flex:1, fontSize:15 }}>{s}</span><Icon.arrow size={14} color="var(--w-mute)"/>
              </div>
            ))}
          </div>
        </div>
        <TabBar active="profile" onChange={onTab}/>
      </div>
    );
  }

  // ── LOGGED-IN VIEW ─────────────────────────────────────────────────────────
  return (
    <div style={{ height:'100%', overflowY:'auto', background:'var(--w-cream)', paddingBottom:120 }} className="no-scroll app-scroll">
      <IOSStatusBar/>
      {/* Yellow header band */}
      <div style={{ background:'var(--w-yellow)', padding:'52px 22px 80px', position:'relative', overflow:'hidden' }}>
        <div style={{ position:'absolute', top:-40, right:-40, width:200, height:200, borderRadius:'50%', background:'rgba(255,255,255,0.22)' }}/>
        <div style={{ position:'absolute', bottom:-60, left:-30, width:160, height:160, borderRadius:'50%', background:'rgba(245,166,35,0.3)' }}/>
        <div style={{ position:'relative', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div style={{ fontSize:13, fontWeight:700, color:'var(--w-yellow-ink)' }}>You</div>
        </div>
      </div>

      <div style={{ padding:'0 22px', marginTop:-56, position:'relative' }}>
        {/* User card */}
        <div style={{ background:'var(--w-paper)', borderRadius:28, padding:22, boxShadow:'var(--sh-pop)' }}>
          <div style={{ display:'flex', gap:16, alignItems:'center', marginBottom:16 }}>
            <div style={{ width:72, height:72, borderRadius:36, background:'linear-gradient(135deg,#FF6B5A,#FFC93C)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:36, boxShadow:'0 8px 20px rgba(255,107,90,0.3)', flexShrink:0 }}>
              {authUser.avatar_emoji || '🧭'}
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <div className="t-display" style={{ fontSize:22, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{authUser.name}</div>
              <div style={{ fontSize:13, color:'var(--w-mute)' }}>{authUser.email}</div>
              {memberSince && <div style={{ fontSize:11, color:'var(--w-mute)', marginTop:2 }}>Creator since {memberSince}</div>}
            </div>
          </div>
          {authUser.bio && (
            <div style={{ fontSize:13, color:'var(--w-slate)', lineHeight:1.5, padding:'12px 14px', background:'var(--w-cream)', borderRadius:12 }}>{authUser.bio}</div>
          )}
        </div>

        {/* Creator Studio CTA */}
        <div style={{ marginTop:14, padding:'18px 20px', borderRadius:22, background:'var(--w-ink)', color:'#fff', display:'flex', gap:14, alignItems:'center' }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:11, color:'var(--w-yellow)', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Creator Studio</div>
            <div className="t-display" style={{ fontSize:18, fontWeight:600, marginTop:3 }}>Manage your tours</div>
            <div style={{ fontSize:12, opacity:0.65, marginTop:3 }}>Upload audio · video · set pricing</div>
          </div>
          <button onClick={onGoCreator} className="w-btn" style={{ height:40, padding:'0 16px', fontSize:13, flexShrink:0 }}>Open →</button>
        </div>

        {/* Pro upsell */}
        <div style={{ marginTop:14, padding:'16px 18px', borderRadius:20, background:'var(--w-yellow-soft)', display:'flex', gap:14, alignItems:'center' }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:11, color:'var(--w-yellow-ink)', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Wander Pro</div>
            <div className="t-display" style={{ fontSize:17, fontWeight:600, color:'var(--w-yellow-ink)', marginTop:3 }}>All tours, every city</div>
            <div style={{ fontSize:12, color:'var(--w-yellow-ink)', opacity:0.7, marginTop:3 }}>$4.99/month after trial</div>
          </div>
          <button className="w-btn" style={{ height:38, padding:'0 14px', fontSize:13, flexShrink:0 }}>Try free</button>
        </div>

        {/* Badges */}
        <div className="t-display" style={{ fontSize:22, fontWeight:600, marginTop:26, marginBottom:12 }}>Badges</div>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {badges.map(b=><span key={b} style={{ padding:'8px 12px', borderRadius:999, background:'var(--w-paper)', fontSize:13, fontWeight:600, boxShadow:'inset 0 0 0 1px var(--w-line)' }}>{b}</span>)}
        </div>

        {/* Account settings */}
        <div className="t-display" style={{ fontSize:22, fontWeight:600, marginTop:26, marginBottom:12 }}>Account</div>
        <div style={{ background:'var(--w-paper)', borderRadius:18, overflow:'hidden' }}>
          <div style={{ padding:'16px 18px', display:'flex', alignItems:'center', borderBottom:'1px solid var(--w-line)', cursor:'pointer' }} onClick={()=>setShowPassForm(v=>!v)}>
            <span style={{ flex:1, fontSize:15 }}>Change password</span>
            <span style={{ fontSize:13, color:'var(--w-mute)', marginRight:6 }}>{showPassForm?'▲':'▼'}</span>
          </div>
          {showPassForm && (
            <form onSubmit={handleChangePass} style={{ padding:'14px 18px', borderBottom:'1px solid var(--w-line)', display:'flex', flexDirection:'column', gap:10 }}>
              {[['current','Current password','current-password'],['next','New password','new-password'],['confirm','Confirm new password','new-password']].map(([k,label,ac])=>(
                <div key={k}>
                  <div style={{ fontSize:11, color:'var(--w-mute)', fontWeight:600, marginBottom:4 }}>{label}</div>
                  <input type="password" style={inputSty} value={passForm[k]} onChange={e=>setPassForm(f=>({...f,[k]:e.target.value}))} autoComplete={ac} required/>
                </div>
              ))}
              {passErr && <div style={{ padding:'8px 12px', borderRadius:10, background:'#FFE9E9', color:'#C0392B', fontSize:13 }}>{passErr}</div>}
              {passOk  && <div style={{ padding:'8px 12px', borderRadius:10, background:'#E6FBF0', color:'#1A7A4A', fontSize:13 }}>{passOk}</div>}
              <button type="submit" className="w-btn" style={{ height:44 }} disabled={savingPass}>{savingPass?'Saving…':'Update password'}</button>
            </form>
          )}
          {['Language · English','Voice · Mei Ling','Notifications','Help & Feedback'].map((s,i,a)=>(
            <div key={s} style={{ padding:'16px 18px', display:'flex', alignItems:'center', borderBottom:i<a.length-1?'1px solid var(--w-line)':'none' }}>
              <span style={{ flex:1, fontSize:15 }}>{s}</span><Icon.arrow size={14} color="var(--w-mute)"/>
            </div>
          ))}
        </div>

        {/* Sign out */}
        <button onClick={onLogout} style={{ marginTop:16, width:'100%', padding:'14px', borderRadius:9999, border:'1.5px solid #FFD9D9', background:'transparent', fontFamily:'inherit', fontWeight:700, fontSize:15, color:'#C0392B', cursor:'pointer' }}>
          Sign out
        </button>
      </div>
      <TabBar active="profile" onChange={onTab}/>
    </div>
  );
}

// ─── PAYWALL (with Stripe) ────────────────────────────────────────────────────
function PaywallScreen({ tourId, onClose, onSuccess }) {
  const { TOURS } = window.WANDER_DATA;
  const tour = TOURS.find(t => t.id===tourId) || TOURS[1];
  const [plan, setPlan] = React.useState('pro');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const plans = [
    { id:'tour',  label:'Just this tour', price:'$'+tour.price,   sub:'one-time',                       highlight:false },
    { id:'pro',   label:'Wander Pro',     price:'$4.99',          sub:'per month · 7-day free trial',   highlight:true  },
  ];

  // Listen for payment success from popup window
  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type==='WANDER_PAYMENT_SUCCESS') onSuccess();
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, [onSuccess]);

  // Check if we landed back from Stripe redirect with ?unlocked=1
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get('unlocked')==='1') {
      window.history.replaceState({}, '', '/');
      onSuccess();
    }
  }, []);

  const handlePay = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/stripe/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ tourId, plan }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Payment failed');
      // Open Stripe Checkout in a small popup (stays inside the prototype view)
      const popup = window.open(data.url, 'stripe_checkout', 'width=480,height=700,left=200,top=100');
      if (!popup) {
        // Fallback: redirect current tab
        window.location.href = data.url;
      }
    } catch (e) {
      if (e.message.includes('not configured')) {
        // Demo mode — simulate success
        setTimeout(() => onSuccess(), 1200);
      } else {
        setError(e.message);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ height:'100%', background:'var(--w-ink)', color:'#fff', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', top:-100, left:-50, right:-50, height:360, background:'radial-gradient(circle at center,rgba(255,201,60,0.4),transparent 70%)' }}/>
      <button onClick={onClose} style={{ position:'absolute', top:56, right:16, zIndex:10, width:38, height:38, borderRadius:19, border:'none', background:'rgba(255,255,255,0.1)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.close size={18} color="#fff"/></button>

      <div style={{ position:'relative', padding:'70px 24px 0', textAlign:'center' }}>
        <div style={{ fontSize:60, animation:'wFloat 3s ease-in-out infinite' }}>{tour.emoji}</div>
        <div style={{ fontSize:11, color:'var(--w-yellow)', fontWeight:700, letterSpacing:0.6, textTransform:'uppercase', marginTop:12 }}>Unlock pro tour</div>
        <h1 className="t-display" style={{ fontSize:30, fontWeight:600, lineHeight:1.1, margin:'8px 0 0' }}>{tour.title}</h1>
        <p style={{ fontSize:14, color:'rgba(255,255,255,0.65)', marginTop:10, maxWidth:300, marginLeft:'auto', marginRight:'auto' }}>{tour.blurb}</p>
      </div>

      <div style={{ padding:'24px 22px 30px', position:'relative' }}>
        <div style={{ display:'grid', gap:10 }}>
          {plans.map(p => (
            <button key={p.id} onClick={()=>setPlan(p.id)} style={{ width:'100%', padding:18, borderRadius:20, background:plan===p.id?'var(--w-yellow)':'rgba(255,255,255,0.06)', color:plan===p.id?'var(--w-yellow-ink)':'#fff', border:'none', cursor:'pointer', textAlign:'left', display:'flex', alignItems:'center', gap:14, fontFamily:'inherit', boxShadow:plan===p.id?'0 8px 24px rgba(255,201,60,0.35)':'inset 0 0 0 1px rgba(255,255,255,0.1)', position:'relative' }}>
              <div style={{ width:22, height:22, borderRadius:11, flexShrink:0, border:plan===p.id?'6px solid var(--w-yellow-ink)':'2px solid rgba(255,255,255,0.4)', background:plan===p.id?'#fff':'transparent' }}/>
              <div style={{ flex:1 }}>
                <div style={{ fontWeight:700, fontSize:15 }}>{p.label}</div>
                <div style={{ fontSize:12, opacity:0.75, marginTop:2 }}>{p.sub}</div>
              </div>
              <div className="t-display" style={{ fontSize:22, fontWeight:600 }}>{p.price}</div>
              {p.highlight && plan!==p.id && <div style={{ position:'absolute', top:-8, right:16, background:'var(--w-coral)', color:'#fff', padding:'3px 10px', borderRadius:999, fontSize:10, fontWeight:700, letterSpacing:0.4 }}>BEST VALUE</div>}
            </button>
          ))}
        </div>

        <ul style={{ margin:'20px 0 0', padding:0, listStyle:'none', display:'grid', gap:10 }}>
          {['Unlimited tours in 47 cities','Offline downloads & maps','AR overlays + bonus stops','Cancel anytime'].map(t => (
            <li key={t} style={{ display:'flex', gap:10, alignItems:'center', fontSize:14, color:'rgba(255,255,255,0.85)' }}>
              <div style={{ width:22, height:22, borderRadius:11, background:'var(--w-yellow)', color:'var(--w-yellow-ink)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon.check size={12} color="var(--w-yellow-ink)"/></div>
              {t}
            </li>
          ))}
        </ul>

        {error && <div style={{ marginTop:14, padding:'10px 14px', borderRadius:12, background:'rgba(255,107,90,0.2)', color:'var(--w-coral)', fontSize:13 }}>{error}</div>}

        <button onClick={handlePay} disabled={loading} className="w-btn" style={{ width:'100%', height:56, marginTop:20, opacity:loading?0.7:1 }}>
          {loading ? 'Opening payment…' : plan==='pro' ? 'Start free trial' : 'Unlock for $'+tour.price}
        </button>
        <div style={{ textAlign:'center', fontSize:11, color:'rgba(255,255,255,0.4)', marginTop:12 }}>Charged after 7 days. Cancel anytime in Settings.</div>
      </div>
    </div>
  );
}

// ─── COMPLETION ───────────────────────────────────────────────────────────────
function CompletionScreen({ tourId, onDone }) {
  const { TOURS, stopsForTour } = window.WANDER_DATA;
  const tour = TOURS.find(t=>t.id===tourId) || TOURS[0];
  const STOPS = stopsForTour(tour.id);
  const [stars, setStars] = React.useState(5);
  return (
    <div style={{ height:'100%', overflowY:'auto', position:'relative', background:`linear-gradient(180deg,${tour.hero[0]} 0%,var(--w-cream) 60%)` }} className="no-scroll app-scroll">
      <div style={{ position:'absolute', inset:'0 0 60% 0', pointerEvents:'none', overflow:'hidden' }}>
        {Array.from({length:20}).map((_,i) => {
          const colors=['#FFC93C','#FF6B5A','#2DD4A7','#9B7EDC','#4FB7E8'];
          return <div key={i} style={{ position:'absolute', left:(i*47)%100+'%', top:(i*23)%80+'%', width:8, height:14, borderRadius:2, background:colors[i%colors.length], transform:`rotate(${i*31}deg)`, animation:`wFloat ${2+(i%4)*0.5}s ${i*0.1}s ease-in-out infinite` }}/>;
        })}
      </div>
      <div style={{ padding:'90px 24px 24px', position:'relative', textAlign:'center' }}>
        <div style={{ width:100, height:100, borderRadius:50, margin:'0 auto', background:'var(--w-paper)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 12px 32px rgba(0,0,0,0.18)', fontSize:56 }}>🏆</div>
        <div style={{ fontSize:11, color:'var(--w-yellow-ink)', fontWeight:700, letterSpacing:0.6, textTransform:'uppercase', marginTop:18 }}>Tour complete</div>
        <h1 className="t-display" style={{ fontSize:34, fontWeight:600, lineHeight:1.05, margin:'8px 0 0' }}>You wandered like a local.</h1>
        <p style={{ fontSize:15, color:'var(--w-slate)', marginTop:10 }}>{tour.title} · all {STOPS.length} stops · {tour.distance} on foot</p>
      </div>
      <div style={{ padding:'0 22px 30px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, background:'var(--w-paper)', borderRadius:22, padding:16, boxShadow:'var(--sh-card)' }}>
          {[{l:'Time',v:'47 min'},{l:'Steps',v:'2,840'},{l:'Discoveries',v:'7'}].map(s => (
            <div key={s.l} style={{ textAlign:'center' }}>
              <div className="t-display" style={{ fontSize:22, fontWeight:600 }}>{s.v}</div>
              <div style={{ fontSize:11, color:'var(--w-mute)', textTransform:'uppercase', letterSpacing:0.4, fontWeight:600 }}>{s.l}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop:14, padding:16, borderRadius:20, background:'var(--w-yellow)', color:'var(--w-yellow-ink)', display:'flex', alignItems:'center', gap:14 }}>
          <div style={{ fontSize:36 }}>🦁</div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:11, fontWeight:700, letterSpacing:0.5, textTransform:'uppercase' }}>Badge unlocked</div>
            <div className="t-display" style={{ fontSize:18, fontWeight:600 }}>Marina Bay Master</div>
          </div>
          <Icon.sparkle size={20} color="var(--w-yellow-ink)"/>
        </div>
        <div style={{ marginTop:22, padding:18, background:'var(--w-paper)', borderRadius:22, boxShadow:'var(--sh-card)' }}>
          <div className="t-display" style={{ fontSize:18, fontWeight:600 }}>Rate this tour</div>
          <div style={{ display:'flex', gap:8, marginTop:12, justifyContent:'center' }}>
            {[1,2,3,4,5].map(n => <button key={n} onClick={()=>setStars(n)} style={{ background:'none', border:'none', cursor:'pointer', padding:4 }}><Icon.star size={36} color={n<=stars?'var(--w-yellow)':'var(--w-line)'}/></button>)}
          </div>
          <textarea placeholder="What stuck with you? (optional)" style={{ width:'100%', marginTop:14, padding:14, borderRadius:14, border:'1.5px solid var(--w-line)', resize:'none', fontFamily:'inherit', fontSize:14, minHeight:70, outline:'none', background:'var(--w-cream)' }}/>
        </div>
        <button onClick={onDone} className="w-btn" style={{ width:'100%', height:54, marginTop:18 }}>Done · find next tour</button>
        <button onClick={onDone} className="w-btn w-btn--ghost" style={{ width:'100%', height:50, marginTop:8 }}>Share my walk</button>
      </div>
    </div>
  );
}

// ─── OFFLINE ──────────────────────────────────────────────────────────────────
function OfflineScreen({ onClose }) {
  const { TOURS } = window.WANDER_DATA;
  const off = window.WanderOffline;
  const [ids, setIds] = React.useState(() => (off && off.supported()) ? off.list() : []);
  const [used, setUsed] = React.useState(null);

  const refresh = React.useCallback(() => {
    if (!off || !off.supported()) return;
    setIds(off.list());
    off.estimate().then(setUsed);
  }, [off]);
  React.useEffect(() => { refresh(); }, [refresh]);

  const removeTour = async (id) => { await off.remove(id); refresh(); };

  const downloads = ids
    .map(id => TOURS.find(t => t.id === id))
    .filter(Boolean)
    .map(tour => ({ tour }));

  const usedMB  = used ? Math.round(used.usageMB) : 0;
  const quotaMB = used ? Math.round(used.quotaMB) : 0;
  const usedPct = used ? Math.min(100, Math.max(2, used.pct * 100)) : 0;

  return (
    <div style={{ height:'100%', overflowY:'auto', background:'var(--w-cream)' }} className="no-scroll app-scroll">
      <div style={{ padding:'56px 16px 14px', display:'flex', alignItems:'center', gap:12 }}>
        <button onClick={onClose} style={{ width:38, height:38, borderRadius:19, border:'none', background:'var(--w-paper)', boxShadow:'inset 0 0 0 1px var(--w-line)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.back size={18}/></button>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:12, color:'var(--w-mute)', fontWeight:600 }}>Library</div>
          <div className="t-display" style={{ fontSize:22, fontWeight:600 }}>Offline tours</div>
        </div>
      </div>
      <div style={{ margin:'0 22px 20px', padding:18, background:'var(--w-ink)', borderRadius:22, color:'#fff' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
          <span style={{ fontSize:13, opacity:0.7 }}>Device storage used</span>
          <span>{used
            ? <><span className="t-display" style={{ fontSize:22, fontWeight:600, color:'var(--w-yellow)' }}>{usedMB} MB</span><span style={{ fontSize:12, opacity:0.5 }}> / {quotaMB >= 1024 ? (quotaMB/1024).toFixed(1)+' GB' : quotaMB+' MB'}</span></>
            : <span style={{ fontSize:13, opacity:0.6 }}>Not available</span>
          }</span>
        </div>
        <div style={{ height:6, borderRadius:3, background:'rgba(255,255,255,0.15)', marginTop:12, overflow:'hidden' }}>
          <div style={{ width:usedPct+'%', height:'100%', background:'var(--w-yellow)' }}/>
        </div>
      </div>
      <div style={{ padding:'0 22px', display:'grid', gap:12 }}>
        {downloads.length === 0 && (
          <div style={{ padding:'28px 18px', background:'var(--w-paper)', borderRadius:20, textAlign:'center', boxShadow:'var(--sh-card)' }}>
            <div style={{ fontSize:30 }}>📥</div>
            <div style={{ fontWeight:700, fontSize:15, marginTop:8 }}>No offline tours yet</div>
            <div style={{ fontSize:13, color:'var(--w-mute)', marginTop:4, lineHeight:1.45 }}>Open any tour and tap <b>Download for offline</b> to save it here.</div>
          </div>
        )}
        {downloads.map(d => (
          <div key={d.tour.id} style={{ display:'flex', gap:12, padding:12, background:'var(--w-paper)', borderRadius:20, alignItems:'center', boxShadow:'var(--sh-card)' }}>
            <div style={{ width:60, height:60 }}><TourArt tour={d.tour} h={60} rounded={12}/></div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontWeight:700, fontSize:14, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{d.tour.title}</div>
              <div style={{ fontSize:12, color:'var(--w-mute)', marginTop:4, display:'flex', alignItems:'center', gap:6 }}><Icon.check size={12} color="var(--w-mint)"/> Available offline · narrated on-device</div>
            </div>
            <button onClick={()=>removeTour(d.tour.id)} title="Remove download" style={{ width:36, height:36, borderRadius:18, border:'none', background:'var(--w-cream)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon.close size={14}/>
            </button>
          </div>
        ))}
      </div>
      <div style={{ margin:'24px 22px', padding:18, borderRadius:20, background:'var(--w-yellow-soft)', display:'flex', gap:12, alignItems:'flex-start' }}>
        <div style={{ fontSize:28, lineHeight:1 }}>🎙️</div>
        <div style={{ flex:1, fontSize:12.5, color:'var(--w-yellow-ink)', lineHeight:1.5 }}>
          <div style={{ fontWeight:700, marginBottom:3 }}>Tip — download over Wi-Fi before you go.</div>
          Narration is read aloud by your phone's built-in voice, so it works fully offline. One catch: if your device is set to a <b>cloud-based</b> voice, it may still need signal — pick an on-device voice in your system settings for guaranteed offline playback.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BrowseScreen, SearchScreen, SavedScreen, ProfileScreen, PaywallScreen, CompletionScreen, OfflineScreen });
