// Rewards, Marketplace, Community
const RewardsScreen = () => {
  const r = window.MOCK.rewards;
  const I = window.Icons;
  const toast = window.useToast();
  const [tab, setTab] = useState('Daily');
  const [daily, setDaily] = useState(r.daily);
  const claimAll = () => { setDaily(d => d.map(x => ({...x, claimed: true}))); toast.push('All rewards claimed — +30 SLEEP'); };

  return (
    <div className="col" style={{ gap: 22 }}>
      <div className="pillar-hero">
        <Mascot score={95} size={120} mood="celebrate" />
        <div className="pillar-hero-text">
          <span className="pillar-tag">{r.stats.streak}-day streak 🔥</span>
          <h2 className="pillar-verdict">Your Dino's on a roll</h2>
          <p className="pillar-body">You've earned <b>{r.available.toLocaleString()} SLEEP</b> and reached <b>{r.membership.tier}</b>. Keep the streak alive to level up faster.</p>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.2fr 1.2fr 1fr', gap: 16 }}>
        <div className="card">
          <div className="card-head"><h3>My Rewards</h3><button className="btn primary sm" onClick={claimAll}>Claim All</button></div>
          <div className="mono" style={{ fontSize: 32, fontWeight: 600 }}>{r.available.toLocaleString()} <span style={{fontSize:14, color:'var(--primary)'}}>SLEEP</span></div>
          <div className="muted" style={{ fontSize: 12 }}>Available Balance</div>

          <div className="tabs" style={{ marginTop: 14 }}>
            {['Daily','Challenges','Achievements','Referrals'].map(t => <button key={t} className={`tab ${tab===t?'active':''}`} onClick={()=>setTab(t)}>{t}</button>)}
          </div>

          <div className="col" style={{ marginTop: 14, gap: 8 }}>
            {tab === 'Daily' && daily.map(d => (
              <div key={d.id} className="row" style={{ padding: 10, borderRadius: 10, background: 'var(--surface-2)', gap: 10 }}>
                <span style={{fontSize:18}}>{d.icon}</span>
                <div style={{flex:1}}>
                  <div style={{fontWeight:500, fontSize:13}}>{d.title}</div>
                  {d.sub && <div className="muted" style={{fontSize:11}}>{d.sub}</div>}
                </div>
                <span className="mono" style={{fontWeight:600, color:'var(--primary)'}}>+{d.amount}</span>
                {d.claimed
                  ? <span className="tag good"><I.Check size={10}/> Claimed</span>
                  : <button className="btn primary xs" onClick={() => { setDaily(ds=>ds.map(x=>x.id===d.id?{...x,claimed:true}:x)); toast.push(`+${d.amount} SLEEP`); }}>Claim</button>}
              </div>
            ))}
            {tab === 'Challenges' && r.challenges.map(c => (
              <div key={c.id} style={{ padding: 12, borderRadius: 10, background: 'var(--surface-2)' }}>
                <div className="row" style={{justifyContent:'space-between', marginBottom:8}}>
                  <div style={{fontWeight:600}}>{c.title}</div>
                  <span className="mono" style={{color:'var(--primary)'}}>+{c.reward}</span>
                </div>
                <ProgressBar value={c.progress} max={c.target} />
                <div className="muted" style={{fontSize:11, marginTop:6}}>{c.progress}/{c.target} days</div>
              </div>
            ))}
            {tab === 'Achievements' && r.achievements.map(a => (
              <div key={a.id} className="row" style={{ padding: 12, borderRadius: 10, background: 'var(--surface-2)', gap: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: a.unlocked?'rgba(252,211,77,0.2)':'var(--surface-3)', display:'grid', placeItems:'center', color: a.unlocked?'var(--accent-amber)':'var(--text-3)' }}>
                  {a.unlocked ? <I.Trophy size={18}/> : <I.Lock size={16}/>}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontWeight:600, fontSize:13}}>{a.title}</div>
                  <div className="muted" style={{fontSize:11}}>{a.desc}</div>
                  {!a.unlocked && a.progress!=null && <div style={{marginTop:6}}><ProgressBar value={a.progress} max={a.target} color="var(--accent-amber)"/></div>}
                </div>
              </div>
            ))}
            {tab === 'Referrals' && (
              <div className="card flat" style={{padding:16, background:'var(--surface-2)', textAlign:'center'}}>
                <I.Users size={28} className="muted" style={{margin:'4px auto 8px', display:'block'}}/>
                <div style={{fontWeight:600}}>Earn 250 SLEEP per referral</div>
                <div className="muted" style={{fontSize:12, marginTop:4}}>Your code · <span className="mono">DREAMER-2845</span></div>
                <button className="btn primary sm" style={{marginTop:12}}>Copy invite link</button>
              </div>
            )}
          </div>
        </div>

        <div className="card">
          <h3 style={{margin:'0 0 12px', fontSize:15}}>Staking & Benefits</h3>
          <div className="mono" style={{ fontSize: 28, fontWeight: 600 }}>{r.staked.toLocaleString()} <span style={{fontSize:14, color:'var(--primary)'}}>SLEEP</span></div>
          <div className="muted" style={{ fontSize: 12 }}>Staked Balance</div>
          <div className="row" style={{ marginTop: 6, gap: 8 }}>
            <span className="tag violet">Unlocks in {r.unlockDays} days</span>
            <button className="btn ghost xs">Manage Stake</button>
          </div>
          <div className="divider"></div>
          <div className="section-title">Your Benefits</div>
          <div className="col" style={{gap:8}}>
            {r.benefits.map(b => (
              <div key={b.label} className="row" style={{justifyContent:'space-between', fontSize:13, padding:'6px 0'}}>
                <span className="muted">{b.label}</span>
                <span className="mono" style={{fontWeight:600, color:b.value==='Exclusive'?'var(--accent-amber)':'var(--good)'}}>{b.value}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{ background: 'radial-gradient(circle at 50% 0%, rgba(252,211,77,0.18), transparent 60%), var(--surface)' }}>
          <h3 style={{margin:'0 0 12px', fontSize:15}}>My Membership</h3>
          <div style={{display:'grid', placeItems:'center', padding:'8px 0'}}>
            <div style={{ position: 'relative', width: 160, height: 160 }}>
              <Ring value={r.membership.xp} max={r.membership.xpMax} size={160} stroke={6} color="var(--accent-amber)" track="rgba(252,211,77,0.15)" />
              <div style={{ position:'absolute', inset:0, display:'grid', placeItems:'center', textAlign:'center', pointerEvents:'none' }}>
                <div>
                  <div className="serif" style={{ fontSize: 30, lineHeight:1 }}>{r.membership.tier}</div>
                  <div className="muted" style={{ fontSize: 12, marginTop:4 }}>Level {r.membership.level}</div>
                </div>
              </div>
            </div>
          </div>
          <div className="mono" style={{textAlign:'center', fontSize:13, color:'var(--text-2)', marginTop:8}}>{r.membership.xp.toLocaleString()} / {r.membership.xpMax.toLocaleString()} XP</div>
          <div className="col" style={{ marginTop: 12, gap: 6, fontSize: 13 }}>
            {['Priority Support','Early Access','Exclusive Rewards'].map(b => <div key={b} className="row" style={{gap:8}}><I.Check size={12} style={{color:'var(--good)'}}/>{b}</div>)}
          </div>
          <button className="btn primary sm" style={{marginTop:14, width:'100%', justifyContent:'center'}}>View All Levels</button>
        </div>
      </div>

      <div className="grid grid-3">
        {[{l:'Total Rewards Earned', v:`${r.stats.total.toLocaleString()} SLEEP`},
          {l:'Days Active', v:r.stats.daysActive},
          {l:'Current Streak', v:`${r.stats.streak} Days 🔥`}].map(s => (
          <div key={s.l} className="card">
            <div className="muted" style={{fontSize:12}}>{s.l}</div>
            <div className="mono" style={{fontSize:24, fontWeight:600, marginTop:4}}>{s.v}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const MarketplaceScreen = () => {
  const items = window.MOCK.marketplace;
  const I = window.Icons;
  const toast = window.useToast();
  const cats = ['All','Sleep','Nutrition','Fitness','Mindfulness','Recovery','Wearables','Supplements'];
  const [cat, setCat] = useState('All');
  const filtered = cat==='All'?items:items.filter(i=>i.cat.toLowerCase().includes(cat.toLowerCase().slice(0,4)));

  const hueFor = (cat) => ({Sleep:295,Nutrition:165,Fitness:75,Mindfulness:220,Recovery:200,Wearables:280,Supplements:160}[cat] || 295);
  const colorFor = (cat) => ({Sleep:'#b8a9ff',Nutrition:'#8fe3b8',Fitness:'#fcd34d',Mindfulness:'#7ad8e0',Recovery:'#7ad8e0',Wearables:'#b8a9ff',Supplements:'#8fe3b8'}[cat] || '#b8a9ff');

  return (
    <div className="col" style={{ gap: 22 }}>
      <Topbar title="Marketplace" subtitle="Trusted products, programs and services for a better you." right={
        <button className="btn ghost"><I.Plus size={13}/> List your service · Stake SLEEP</button>
      }/>

      <div className="tabs" style={{alignSelf:'flex-start'}}>
        {cats.map(c => <button key={c} className={`tab ${cat===c?'active':''}`} onClick={()=>setCat(c)}>{c}</button>)}
      </div>

      <div className="grid grid-4" style={{gap:16}}>
        {filtered.map(item => (
          <div key={item.id} className="card" style={{padding:0, overflow:'hidden', display:'flex', flexDirection:'column'}}>
            <div style={{ position: 'relative' }}>
              {item.img ? (
                <div style={{
                  height: 160,
                  background: `radial-gradient(circle at 50% 50%, ${colorFor(item.cat)}40, rgba(20,14,40,0.95) 75%) center/cover, url(${item.img}) center/cover no-repeat`,
                  position: 'relative',
                }}>
                  <img src={item.img} alt={item.title} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
              ) : (
                <Placeholder label={item.cat} hue={hueFor(item.cat)} height={160}/>
              )}
              <span className="tag" style={{ position:'absolute', top:10, left:10, background: 'rgba(10,7,24,0.6)', backdropFilter:'blur(4px)' }}>{item.cat}</span>
            </div>
            <div style={{padding:14, display:'flex', flexDirection:'column', gap:6, flex:1}}>
              <div style={{fontWeight:600, fontSize:15}}>{item.title}</div>
              <div className="muted" style={{fontSize:12, lineHeight:1.45, flex:1}}>{item.desc}</div>
              <div className="row" style={{justifyContent:'space-between', marginTop:8}}>
                <div className="row" style={{gap:4, fontSize:11, color:'var(--text-3)'}}>
                  ★ {item.rating} <span className="muted">({item.reviews})</span>
                </div>
              </div>
              <div className="row" style={{justifyContent:'space-between', marginTop:6}}>
                <div className="mono" style={{fontWeight:600}}>{item.price} <span style={{fontSize:11, color:'var(--primary)'}}>SLEEP</span></div>
                <button className="btn primary xs" onClick={() => toast.push(`${item.title} added — opening details`)}>View</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-3">
        {[
          {i:<I.Heart size={18}/>, t:'For Partners', d:'Stake SLEEP to list your products or services.'},
          {i:<I.Users size={18}/>, t:'Reach Millions', d:'Connect with a health-focused community.'},
          {i:<I.Trend size={18}/>, t:'Grow Together', d:'Build trust and grow your wellness business.'},
        ].map((c,i) => (
          <div key={i} className="card" style={{display:'flex', gap:14, alignItems:'flex-start'}}>
            <div style={{width:36, height:36, borderRadius:10, background:'rgba(184,169,255,0.15)', display:'grid', placeItems:'center', color:'var(--primary)'}}>{c.i}</div>
            <div>
              <div style={{fontWeight:600}}>{c.t}</div>
              <div className="muted" style={{fontSize:12, marginTop:4}}>{c.d}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const CommunityScreen = () => {
  const c = window.MOCK.community;
  const I = window.Icons;
  return (
    <div className="col" style={{ gap: 22 }}>
      <Topbar title="Community" subtitle="Compare, compete, and learn together." right={
        <button className="btn primary"><I.Plus size={13}/> Share update</button>
      }/>

      <div className="grid" style={{gridTemplateColumns:'2fr 1fr', gap:16}}>
        <div className="col" style={{gap:16}}>
          <div className="card">
            <h3 style={{margin:'0 0 12px', fontSize:15}}>Active Challenges</h3>
            <div className="grid grid-3" style={{gap:12}}>
              {c.challenges.map(ch => (
                <div key={ch.id} style={{padding:14, borderRadius:12, background:'linear-gradient(180deg, rgba(184,169,255,0.10), var(--surface-2))', border:'1px solid var(--border-soft)'}}>
                  <div style={{fontWeight:600}}>{ch.title}</div>
                  <div className="muted" style={{fontSize:11, marginTop:4}}>{ch.participants.toLocaleString()} joined · {ch.days} days</div>
                  <div className="mono" style={{marginTop:10, fontSize:12, color:'var(--accent-amber)'}}>{ch.reward}</div>
                  <button className="btn primary xs" style={{marginTop:10}}>Join</button>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Feed</h3><div className="tabs"><button className="tab active">All</button><button className="tab">Following</button></div></div>
            <div className="col" style={{gap:10}}>
              {c.feed.map(p => (
                <div key={p.id} style={{padding:14, borderRadius:12, background:'var(--surface-2)'}}>
                  <div className="row" style={{gap:10, marginBottom:8}}>
                    <div className="avatar" style={{width:34, height:34, fontSize:12}}>{p.avatar}</div>
                    <div style={{flex:1}}>
                      <div style={{fontWeight:600, fontSize:13}}>{p.user}</div>
                      <div className="muted" style={{fontSize:11}}>{p.mins}m ago · <span className="tag violet" style={{padding:'1px 8px'}}>{p.tag}</span></div>
                    </div>
                  </div>
                  <div style={{fontSize:13, lineHeight:1.5}}>{p.text}</div>
                  <div className="row" style={{marginTop:10, gap:14, fontSize:12, color:'var(--text-3)'}}>
                    <span className="row" style={{gap:5}}><I.Heart size={13}/> {p.likes}</span>
                    <span className="row" style={{gap:5}}><I.Bot size={13}/> {p.comments}</span>
                    <span className="row" style={{gap:5}}><I.Share size={13}/> Share</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card" style={{alignSelf:'flex-start'}}>
          <h3 style={{margin:'0 0 12px', fontSize:15}}>Leaderboard</h3>
          <div className="muted" style={{fontSize:11, marginBottom:10}}>Sleep score · this week</div>
          <div className="col" style={{gap:6}}>
            {c.leaders.map(l => (
              <div key={l.rank} className="row" style={{ padding:'10px 12px', borderRadius:10, background: l.you?'var(--primary-soft)':'var(--surface-2)', border: '1px solid '+ (l.you?'rgba(184,169,255,0.4)':'transparent'), gap:10 }}>
                <div className="mono muted" style={{ width:18 }}>#{l.rank}</div>
                <div className="avatar" style={{width:28, height:28, fontSize:11}}>{l.avatar}</div>
                <div style={{flex:1, fontSize:13, fontWeight: l.you?600:500}}>{l.name}</div>
                <div className="mono" style={{fontWeight:600}}>{l.score}</div>
                <div className="muted" style={{fontSize:11}}>{l.streak}d 🔥</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { RewardsScreen, MarketplaceScreen, CommunityScreen });
