// game-parts.jsx — shared UI bits for the prediction game.

// ── PM2.5 colour scale (Colombia / OMS-ish ranges, μg/m³) ─────────
function pmColor(v){
  if(v <= 12)  return '#00E676';   // Buena
  if(v <= 25)  return '#FFEB3B';   // Aceptable
  if(v <= 37)  return '#FFB300';   // Dañina grupos sensibles
  if(v <= 55)  return '#FF8A3D';   // Dañina
  if(v <= 150) return '#E8735A';   // Muy dañina
  return '#B0306E';                 // Peligrosa
}
function pmLabel(v){
  if(v <= 12)  return 'Buena';
  if(v <= 25)  return 'Aceptable';
  if(v <= 37)  return 'Dañina para sensibles';
  if(v <= 55)  return 'Dañina';
  if(v <= 150) return 'Muy dañina';
  return 'Peligrosa';
}
function pmEmoji(v){
  if(v <= 12)  return '😊';
  if(v <= 25)  return '🙂';
  if(v <= 37)  return '😐';
  if(v <= 55)  return '😷';
  if(v <= 150) return '🤢';
  return '☠️';
}

// ── Top chrome ────────────────────────────────────────────────────
function TopBar({step, total, onRestart, onRetryLevel, label}){
  return (
    <div style={{
      position:'sticky', top:0, zIndex:50,
      background:'linear-gradient(180deg, rgba(8,30,54,0.96), rgba(8,30,54,0.78))',
      borderBottom:'1px solid rgba(13,204,192,0.16)',
      padding:'20px 44px', display:'flex', alignItems:'center', gap:28,
      backdropFilter:'blur(8px)',
    }}>
      <img src="assets/siata-amva-white.png" alt="SIATA"
        style={{height:56, width:'auto'}} />
      <div style={{width:1, height:38, background:'rgba(255,255,255,0.16)'}} />
      <div style={{
        fontFamily:'var(--mono)', fontSize:15, color:'var(--cyan)',
        letterSpacing:'0.22em', textTransform:'uppercase',
      }}>
        {label || 'Juego · ¿Puedes predecir el aire?'}
      </div>
      <div style={{flex:1}} />
      <div style={{
        display:'flex', alignItems:'center', gap:6,
      }}>
        {Array.from({length:total}).map((_,i)=>(
          <div key={i} style={{
            width: i===step ? 44 : 12, height:12, borderRadius:7,
            background: i<=step ? 'var(--cyan)' : 'rgba(255,255,255,0.18)',
            transition:'all 0.3s ease',
          }} />
        ))}
      </div>
      <div style={{
        fontFamily:'var(--mono)', fontSize:15, color:'var(--gray)',
        letterSpacing:'0.18em',
      }}>
        <span style={{color:'var(--cyan)'}}>{String(step+1).padStart(2,'0')}</span>
        <span style={{color:'var(--dim)', margin:'0 6px'}}>/</span>
        {String(total).padStart(2,'0')}
      </div>
      {onRetryLevel && (
        <button onClick={onRetryLevel} style={{
          background:'transparent', border:'1px solid rgba(13,204,192,0.45)',
          color:'#0DCCC0', padding:'10px 18px', borderRadius:6,
          fontSize:14, letterSpacing:'0.16em', textTransform:'uppercase',
          fontFamily:'var(--mono)', cursor:'pointer',
          marginLeft:14,
        }}>↻ Reintentar nivel</button>
      )}
      {onRestart && (
        <button onClick={onRestart} style={{
          marginLeft:10,
          background:'transparent', border:'1px solid rgba(255,255,255,0.16)',
          color:'var(--gray)', padding:'10px 18px', borderRadius:6,
          fontSize:14, letterSpacing:'0.16em', textTransform:'uppercase',
          fontFamily:'var(--mono)', cursor:'pointer',
        }}>↺ Reiniciar</button>
      )}
    </div>
  );
}

function BottomBar(){
  return (
    <div style={{
      padding:'24px 40px 32px', marginTop:60,
      borderTop:'1px solid rgba(255,255,255,0.06)',
      display:'flex', alignItems:'center', justifyContent:'space-between',
      fontFamily:'var(--mono)', fontSize:12, color:'var(--dim)',
      letterSpacing:'0.2em', textTransform:'uppercase',
    }}>
      <span>siata.gov.co · Valle de Aburrá · 2025</span>
      <span>Pronóstico operacional · 1 corrida/día</span>
    </div>
  );
}

// ── Big primary button ────────────────────────────────────────────
function PrimaryBtn({children, onClick, disabled, variant}){
  const v = variant || 'cyan';
  const styles = {
    cyan:    {bg:'linear-gradient(135deg, #0DCCC0 0%, #00897B 100%)', sh:'rgba(13,204,192,0.4)'},
    green:   {bg:'linear-gradient(135deg, #84BD45 0%, #5e8a2e 100%)', sh:'rgba(132,189,69,0.4)'},
    ghost:   {bg:'transparent', sh:'transparent'},
  }[v];
  return (
    <button onClick={onClick} disabled={disabled} style={{
      background: v==='ghost' ? 'transparent' : styles.bg,
      border: v==='ghost' ? '1px solid rgba(255,255,255,0.22)' : 'none',
      color: '#fff',
      padding: '20px 40px',
      borderRadius: 8,
      fontFamily:'var(--font)',
      fontSize: 19,
      fontWeight: 600,
      letterSpacing:'0.02em',
      cursor: disabled ? 'not-allowed' : 'pointer',
      opacity: disabled ? 0.4 : 1,
      boxShadow: v==='ghost' ? 'none' : '0 10px 30px ' + styles.sh,
      transition:'transform 0.18s ease, box-shadow 0.18s ease',
    }}
    onMouseEnter={e=>{ if(!disabled) e.currentTarget.style.transform='translateY(-2px)'; }}
    onMouseLeave={e=>{ e.currentTarget.style.transform='translateY(0)'; }}
    >{children}</button>
  );
}

// ── PM2.5 colour scale legend ────────────────────────────────────
function PMScale({value, showValue=true}){
  const stops = [
    {v:0,   c:'#00E676', l:'Buena'},
    {v:12,  c:'#FFEB3B', l:'Aceptable'},
    {v:25,  c:'#FFB300', l:'Sensibles'},
    {v:37,  c:'#FF8A3D', l:'Dañina'},
    {v:55,  c:'#E8735A', l:'Muy dañina'},
  ];
  const max = 80;
  const pct = Math.min(100, (value/max)*100);
  return (
    <div style={{width:'100%'}}>
      <div style={{
        height:18, borderRadius:9, position:'relative',
        background:'linear-gradient(90deg, #00E676 0%, #FFEB3B 18%, #FFB300 36%, #FF8A3D 56%, #E8735A 80%, #B0306E 100%)',
        boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.1)',
      }}>
        {showValue && (
          <div style={{
            position:'absolute', left: pct + '%', top:-10,
            transform:'translateX(-50%)',
            width:0, height:0,
            borderLeft:'10px solid transparent',
            borderRight:'10px solid transparent',
            borderTop:'12px solid #fff',
            filter:'drop-shadow(0 2px 4px rgba(0,0,0,0.4))',
          }} />
        )}
      </div>
      <div style={{
        display:'flex', justifyContent:'space-between',
        marginTop:12, fontSize:13, fontFamily:'var(--mono)',
        color:'var(--gray)', letterSpacing:'0.06em',
      }}>
        {stops.map((s,i)=>(
          <div key={i} style={{textAlign: i===0?'left':(i===stops.length-1?'right':'center')}}>
            <div style={{color:s.c, fontWeight:600}}>{s.l}</div>
            <div style={{color:'var(--dim)', fontSize:11, marginTop:4}}>
              {s.v}{i===stops.length-1?'+':''} μg
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Card shell ───────────────────────────────────────────────────
function Card({children, style, accent}){
  return (
    <div style={{
      background:'linear-gradient(180deg, rgba(16,53,94,0.55), rgba(14,44,77,0.85))',
      border:'1px solid rgba(255,255,255,0.08)',
      borderRadius:14,
      padding:36,
      position:'relative',
      overflow:'hidden',
      ...style,
    }}>
      {accent && (
        <div style={{
          position:'absolute', top:0, left:0, right:0, height:3,
          background:accent,
        }} />
      )}
      {children}
    </div>
  );
}

// ── Kicker + Title ───────────────────────────────────────────────
function ScreenHead({kicker, title, sub}){
  return (
    <div style={{maxWidth:920, margin:'0 auto 40px', textAlign:'center'}}>
      <div className="fade-up" style={{
        fontFamily:'var(--mono)', fontSize:16, color:'var(--cyan)',
        letterSpacing:'0.28em', textTransform:'uppercase',
      }}>{kicker}</div>
      <h1 className="fade-up delay-1" style={{
        fontSize:'clamp(40px, 5.5vw, 72px)', fontWeight:700,
        lineHeight:1.1, marginTop:16, textWrap:'balance',
        letterSpacing:'-0.015em',
      }}>{title}</h1>
      {sub && (
        <p className="fade-up delay-2" style={{
          fontSize:24, color:'var(--gray)', marginTop:24,
          lineHeight:1.5, textWrap:'pretty',
          maxWidth:820, margin:'24px auto 0',
        }}>{sub}</p>
      )}
    </div>
  );
}

// ── Animated number ──────────────────────────────────────────────
function AnimNum({value, decimals=0, duration=600}){
  const [v, setV] = React.useState(value);
  const prevRef = React.useRef(value);
  React.useEffect(()=>{
    const from = prevRef.current;
    const to = value;
    const t0 = performance.now();
    let raf;
    const tick = (t)=>{
      const k = Math.min(1, (t-t0)/duration);
      const eased = 1 - Math.pow(1-k, 3);
      setV(from + (to-from)*eased);
      if(k<1) raf = requestAnimationFrame(tick);
      else prevRef.current = to;
    };
    raf = requestAnimationFrame(tick);
    return ()=> cancelAnimationFrame(raf);
  },[value]);
  return <span>{v.toFixed(decimals)}</span>;
}

Object.assign(window, {
  pmColor, pmLabel, pmEmoji,
  TopBar, BottomBar, PrimaryBtn, PMScale, Card, ScreenHead, AnimNum,
});
