/* global React */
const { useState: uS1 } = React;

// ============== Reusable bits ==============
window.TopBar = function TopBar({ left, right, dark = true }) {
  return <div className="tr-app-bar">{left}{right}</div>;
};

window.Pill = function Pill({ icon, value, bg, fg, sm }) {
  return (
    <div style={{
      background:bg, color:fg,
      borderRadius:999,
      padding: sm ? '4px 10px' : '6px 12px',
      display:'inline-flex', alignItems:'center', gap:6,
      fontWeight:800, fontSize: sm ? 12 : 13,
      fontVariantNumeric:'tabular-nums', letterSpacing:'-0.01em'
    }}>
      <span style={{fontSize: sm ? 12 : 14}}>{icon}</span>
      <span>{typeof value === 'number' ? value.toLocaleString('es-ES') : value}</span>
    </div>
  );
};

window.BottomNav = function BottomNav({ active='home', onChange }) {
  const items = [
    {id:'home', label:'Inicio',   svg:(c)=><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M3 11l9-7 9 7v9a2 2 0 01-2 2h-3v-7H10v7H7a2 2 0 01-2-2v-9z" stroke={c} strokeWidth="2" strokeLinejoin="round"/></svg>},
    {id:'play', label:'Jugar',    svg:(c)=><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" stroke={c} strokeWidth="2"/><path d="M10 8.5v7l6-3.5-6-3.5z" fill={c}/></svg>},
    {id:'rank', label:'Ranking',  svg:(c)=><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M7 4h10v3a5 5 0 01-5 5 5 5 0 01-5-5V4zM12 12v4M9 20h6M5 4h2M17 4h2M5 4a3 3 0 003 3M19 4a3 3 0 01-3 3" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>},
    {id:'me',   label:'Perfil',   svg:(c)=><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="8" r="4" stroke={c} strokeWidth="2"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8" stroke={c} strokeWidth="2" strokeLinecap="round"/></svg>},
  ];
  return (
    <div style={{padding:'10px 16px 24px'}}>
      <div style={{background:'white',borderRadius:28,padding:6,display:'flex',alignItems:'center',gap:4,boxShadow:'0 -8px 30px -10px rgba(0,0,0,0.35)'}}>
        {items.map(it=>{
          const isActive = it.id===active;
          const color = isActive ? '#6C3BFF' : '#8E8E93';
          return (
            <button key={it.id} onClick={()=>onChange&&onChange(it.id)} style={{
              flex:1, background: isActive ? '#F1ECFF' : 'transparent',
              border:'none', borderRadius:20, padding:'8px 0', cursor:'pointer',
              display:'flex', flexDirection:'column', alignItems:'center', gap:2,
            }}>
              {it.svg(color)}
              <div style={{fontWeight: isActive?700:600, fontSize:10, color, letterSpacing:'-0.01em'}}>{it.label}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
};

// ============== 1. Home ==============
window.HomeScreen = function HomeScreen({ user, onPlay, onCategories, onRewards, onLeaderboard, onProfile }) {
  return (
    <div className="tr-screen">
      <div style={{position:'absolute',top:-60,left:-40,width:200,height:200,borderRadius:999,background:'#FFD60A',opacity:.2,filter:'blur(20px)'}}/>
      <div style={{position:'absolute',top:140,right:-50,width:160,height:160,borderRadius:999,background:'#FF4D8D',opacity:.22,filter:'blur(20px)'}}/>

      <div className="tr-app-bar">
        <button className="icon-btn" onClick={onProfile} style={{background:'#FFD60A',color:'#0E0828',fontWeight:800}}>{user.initials}</button>
        <div style={{display:'flex',gap:8}}>
          <Pill icon="🪙" value={user.coins} bg="#FFD60A" fg="#0E0828"/>
          <Pill icon="💎" value={user.gems} bg="rgba(56,189,248,0.95)" fg="#0E0828"/>
        </div>
      </div>

      <div className="pad" style={{paddingTop:8}}>
        <div style={{fontWeight:600,fontSize:14,color:'#D6CFFA'}}>¡Hola, {user.name}! 👋</div>
        <h1 style={{fontWeight:900,fontSize:30,color:'white',marginTop:4,letterSpacing:'-0.03em',lineHeight:1.05}}>¿Listo para arrasar hoy?</h1>
      </div>

      {/* XP bar */}
      <div className="pad" style={{marginTop:14}}>
        <div style={{background:'rgba(255,255,255,0.12)',backdropFilter:'blur(10px)',borderRadius:18,padding:14,boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.1)'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <div style={{display:'flex',alignItems:'center',gap:10}}>
              <div style={{width:38,height:38,borderRadius:12,background:'linear-gradient(135deg,#FFD60A,#FF6B35)',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:900,fontSize:15,color:'#0E0828',boxShadow:'0 4px 12px rgba(255,107,53,0.4)'}}>{user.level}</div>
              <div>
                <div style={{fontWeight:700,fontSize:13,color:'white',letterSpacing:'-0.01em'}}>Nivel {user.level}</div>
                <div style={{fontWeight:500,fontSize:11,color:'#D6CFFA',fontVariantNumeric:'tabular-nums'}}>{user.xp.toLocaleString('es-ES')} / {user.xpNext.toLocaleString('es-ES')} XP</div>
              </div>
            </div>
            <div style={{fontWeight:700,fontSize:11,color:'#FFD60A',letterSpacing:'.04em',textTransform:'uppercase'}}>+150 hoy</div>
          </div>
          <div style={{height:8,background:'rgba(255,255,255,0.18)',borderRadius:999,marginTop:10,overflow:'hidden'}}>
            <div style={{height:'100%',width:`${(user.xp/user.xpNext)*100}%`,background:'linear-gradient(90deg,#FFD60A,#FF6B35)',borderRadius:999,boxShadow:'0 0 12px rgba(255,214,10,0.6)',animation:'tr-fill 1s cubic-bezier(.4,1.4,.6,1)'}}/>
          </div>
        </div>
      </div>

      {/* Daily streak strip */}
      <div className="pad" style={{marginTop:10}}>
        <div style={{display:'flex',gap:6,background:'rgba(255,255,255,0.08)',borderRadius:16,padding:10,alignItems:'center',justifyContent:'space-between'}}>
          <div style={{display:'flex',gap:6,flex:1}}>
            {['L','M','M','J','V','S','D'].map((d,i) => {
              const done = i < user.streakDays;
              const today = i === user.streakDays;
              return (
                <div key={i} style={{flex:1,textAlign:'center'}}>
                  <div style={{width:28,height:28,margin:'0 auto',borderRadius:999,background:today?'#FF6B35':done?'#FFD60A':'rgba(255,255,255,0.1)',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:12,color:done||today?'#0E0828':'#D6CFFA',boxShadow:today?'0 0 0 4px rgba(255,107,53,0.3)':'none'}}>
                    {done?'✓':today?'🔥':d}
                  </div>
                  <div style={{fontWeight:600,fontSize:9,color:today?'#FFD60A':'#D6CFFA',marginTop:4,letterSpacing:'.04em',textTransform:'uppercase'}}>{d}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Big play button */}
      <div className="pad" style={{marginTop:18}}>
        <button onClick={onPlay} style={{
          width:'100%',background:'#FFD60A',border:'none',borderRadius:24,padding:'18px 20px',cursor:'pointer',
          boxShadow:'0 8px 0 #E6B800, 0 12px 24px -8px rgba(255,214,10,0.5)',display:'flex',alignItems:'center',justifyContent:'space-between'
        }}>
          <div style={{textAlign:'left'}}>
            <div style={{fontWeight:700,fontSize:11,letterSpacing:'.06em',textTransform:'uppercase',color:'#0E0828',opacity:.6}}>Partida rápida</div>
            <div style={{fontWeight:900,fontSize:24,color:'#0E0828',marginTop:2,letterSpacing:'-0.03em'}}>¡Jugar ahora!</div>
            <div style={{fontWeight:500,fontSize:12,color:'#0E0828',opacity:.65,marginTop:2}}>5 preguntas · ⏱ 15s c/u</div>
          </div>
          <div style={{width:54,height:54,borderRadius:999,background:'#0E0828',display:'flex',alignItems:'center',justifyContent:'center',color:'#FFD60A'}}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M8 5l12 7-12 7V5z" fill="#FFD60A"/></svg>
          </div>
        </button>
      </div>

      {/* Quick actions */}
      <div className="pad" style={{marginTop:10,display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
        <button onClick={onCategories} style={{background:'rgba(255,255,255,0.12)',backdropFilter:'blur(10px)',border:'none',borderRadius:18,padding:'14px',cursor:'pointer',textAlign:'left',color:'white',boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.1)'}}>
          <div style={{fontSize:24}}>🎯</div>
          <div style={{fontWeight:700,fontSize:14,marginTop:4,letterSpacing:'-0.01em'}}>Categorías</div>
          <div style={{fontWeight:500,fontSize:11,color:'#D6CFFA',marginTop:2}}>6 disponibles</div>
        </button>
        <button onClick={onRewards} style={{background:'rgba(255,255,255,0.12)',backdropFilter:'blur(10px)',border:'none',borderRadius:18,padding:'14px',cursor:'pointer',textAlign:'left',color:'white',position:'relative',boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.1)'}}>
          <div style={{position:'absolute',top:10,right:10,minWidth:18,height:18,padding:'0 5px',borderRadius:999,background:'#FF4D8D',color:'white',fontWeight:800,fontSize:10,display:'flex',alignItems:'center',justifyContent:'center'}}>3</div>
          <div style={{fontSize:24}}>🎁</div>
          <div style={{fontWeight:700,fontSize:14,marginTop:4,letterSpacing:'-0.01em'}}>Recompensas</div>
          <div style={{fontWeight:500,fontSize:11,color:'#D6CFFA',marginTop:2}}>3 sin reclamar</div>
        </button>
      </div>

      <div style={{flex:1}}/>
      <BottomNav active="home" onChange={(id)=>{
        if (id==='play') onCategories();
        else if (id==='rank') onLeaderboard();
        else if (id==='me') onProfile();
      }}/>
    </div>
  );
};

// ============== 2. Category Selection ==============
window.CategorySelectScreen = function CategorySelectScreen({ user, onPick, onBack, onLeaderboard, onProfile }) {
  return (
    <div className="tr-screen">
      <div className="tr-app-bar">
        <button className="icon-btn" onClick={onBack}>‹</button>
        <div style={{fontWeight:700,fontSize:15,color:'white',letterSpacing:'-0.01em'}}>Elegir categoría</div>
        <Pill icon="🪙" value={user.coins} bg="#FFD60A" fg="#0E0828" sm/>
      </div>

      <div className="pad" style={{paddingTop:8,paddingBottom:8}}>
        <div style={{fontWeight:700,fontSize:11,letterSpacing:'.06em',textTransform:'uppercase',color:'#FFD60A'}}>Categorías</div>
        <h1 style={{fontWeight:900,fontSize:26,color:'white',marginTop:4,letterSpacing:'-0.03em',lineHeight:1.1}}>¿En qué eres bueno hoy?</h1>
      </div>

      <div className="pad" style={{flex:1,overflow:'auto',paddingBottom:0}}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,paddingTop:6,paddingBottom:12}}>
          {window.CATEGORIES.map((c,i)=>(
            <button key={c.id} onClick={()=>onPick(c)}
              className="tr-bounce-in"
              style={{
                background:c.color, border:'none', borderRadius:22,
                padding:'16px 12px 14px', cursor:'pointer',
                boxShadow:`0 6px 0 ${c.shadow}`,
                display:'flex', flexDirection:'column', alignItems:'center', gap:6,
                color: c.textDark ? '#0E0828' : 'white',
                animationDelay: `${i*60}ms`,
                textAlign:'center'
              }}>
              <img src={c.icon} width="56" height="56" alt=""/>
              <div style={{fontWeight:900,fontSize:16,letterSpacing:'-0.02em'}}>{c.name}</div>
              <div style={{fontWeight:500,fontSize:10,opacity:.75,letterSpacing:'-0.005em',lineHeight:1.25}}>{c.desc}</div>
            </button>
          ))}
        </div>
      </div>

      <BottomNav active="play" onChange={(id)=>{
        if (id==='home') onBack();
        else if (id==='rank') onLeaderboard();
        else if (id==='me') onProfile();
      }}/>
    </div>
  );
};
