/* global React */
const { useState: uS2, useEffect: uE2, useRef: uR2 } = React;

// ============== 3. Question Screen ==============
window.QuestionScreen = function QuestionScreen({ category, qIndex, total, question, onAnswer, score, streak }) {
  const [time, setTime] = uS2(15);
  const [picked, setPicked] = uS2(null);
  const [revealed, setRevealed] = uS2(false);
  const tRef = uR2(null);

  uE2(()=>{
    if (revealed) return;
    if (time <= 0) { setRevealed(true); return; }
    tRef.current = setTimeout(()=>setTime(t=>t-1), 1000);
    return ()=>clearTimeout(tRef.current);
  }, [time, revealed]);

  const pick = (i)=>{
    if (revealed) return;
    setPicked(i);
    setRevealed(true);
    clearTimeout(tRef.current);
    setTimeout(()=>{
      onAnswer({ correct: i===question.correct, picked: i, timeLeft: time });
    }, 900);
  };

  const slotColors = [
    {bg:'#FFD60A', sh:'#E6B800', fg:'#0E0828', label:'A'},
    {bg:'#FF4D8D', sh:'#E12C6F', fg:'white',   label:'B'},
    {bg:'#38BDF8', sh:'#0284C7', fg:'#0E0828', label:'C'},
    {bg:'#00E5A8', sh:'#00B886', fg:'#0E0828', label:'D'},
  ];

  const timePct = (time/15)*100;
  const timeColor = time>10 ? '#00E5A8' : time>5 ? '#FFD60A' : '#FF4D8D';

  return (
    <div className="tr-screen" style={{background:'#1A0F4A'}}>
      {/* top hud */}
      <div style={{padding:'58px 20px 0',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <button className="icon-btn" style={{width:36,height:36,fontSize:16}}>✕</button>
          <div style={{display:'flex',alignItems:'center',gap:4,background:'rgba(255,255,255,0.12)',borderRadius:999,padding:'6px 10px'}}>
            <img src={category.icon} width="16" height="16" alt=""/>
            <span style={{fontWeight:700,fontSize:12,color:'white'}}>{category.name}</span>
          </div>
        </div>
        <div style={{display:'flex',alignItems:'center',gap:6}}>
          <Pill icon="⚡" value={score} bg="rgba(255,214,10,0.95)" fg="#0E0828" sm/>
          {streak>1 && <Pill icon="🔥" value={`x${streak}`} bg="#FF6B35" fg="white" sm/>}
        </div>
      </div>

      {/* progress dots */}
      <div style={{padding:'12px 20px 0',display:'flex',gap:6}}>
        {Array.from({length: total}).map((_,i)=>(
          <div key={i} style={{
            flex:1,height:5,borderRadius:999,
            background: i<qIndex ? '#00E5A8' : i===qIndex ? '#FFD60A' : 'rgba(255,255,255,0.12)'
          }}/>
        ))}
      </div>
      <div style={{padding:'8px 20px 0',display:'flex',justifyContent:'space-between'}}>
        <div style={{fontWeight:700,fontSize:11,color:'#D6CFFA',letterSpacing:'.04em',textTransform:'uppercase'}}>Pregunta {qIndex+1} de {total}</div>
        <div style={{fontWeight:700,fontSize:11,color:'#D6CFFA',letterSpacing:'.04em',textTransform:'uppercase'}}>+100 pts</div>
      </div>

      {/* timer ring */}
      <div style={{display:'flex',justifyContent:'center',marginTop:14}}>
        <div style={{position:'relative',width:78,height:78}}>
          <svg width="78" height="78" viewBox="0 0 78 78" style={{transform:'rotate(-90deg)'}}>
            <circle cx="39" cy="39" r="33" stroke="rgba(255,255,255,0.12)" strokeWidth="8" fill="none"/>
            <circle cx="39" cy="39" r="33" stroke={timeColor} strokeWidth="8" fill="none"
              strokeLinecap="round"
              strokeDasharray={`${2*Math.PI*33}`}
              strokeDashoffset={`${2*Math.PI*33*(1-timePct/100)}`}
              style={{transition:'stroke-dashoffset 1s linear, stroke 200ms'}}
            />
          </svg>
          <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',flexDirection:'column'}}>
            <div style={{fontWeight:900,fontSize:26,color:'white',fontVariantNumeric:'tabular-nums',letterSpacing:'-0.02em'}}>{time}</div>
            <div style={{fontWeight:700,fontSize:8,color:'#D6CFFA',letterSpacing:'.1em',textTransform:'uppercase',marginTop:-2}}>seg</div>
          </div>
        </div>
      </div>

      {/* question */}
      <div className="pad" style={{marginTop:16}}>
        <div style={{background:'rgba(255,255,255,0.08)',backdropFilter:'blur(10px)',borderRadius:24,padding:'20px 18px',boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.1)'}}>
          <h2 style={{fontWeight:900,fontSize:22,color:'white',letterSpacing:'-0.025em',lineHeight:1.2,textWrap:'pretty'}}>{question.q}</h2>
        </div>
      </div>

      {/* options */}
      <div className="pad" style={{marginTop:14,display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
        {question.options.map((opt,i)=>{
          const sc = slotColors[i];
          let style = {
            background: sc.bg, color: sc.fg,
            boxShadow: `0 6px 0 ${sc.sh}`,
            opacity: 1,
          };
          if (revealed) {
            if (i===question.correct) {
              style = { background:'#00E5A8', color:'#0E0828', boxShadow:'0 0 0 4px rgba(0,229,168,0.4), 0 6px 0 #00B886' };
            } else if (i===picked) {
              style = { background:'#FF4D8D', color:'white', boxShadow:'0 0 0 4px rgba(255,77,141,0.35), 0 6px 0 #E12C6F' };
            } else {
              style = { background: sc.bg, color: sc.fg, boxShadow:`0 6px 0 ${sc.sh}`, opacity: 0.35 };
            }
          }
          return (
            <button key={i} onClick={()=>pick(i)}
              style={{
                ...style,
                border:'none', borderRadius:22, padding:'16px 14px',
                cursor: revealed ? 'default' : 'pointer',
                fontWeight:800, fontSize:15, letterSpacing:'-0.015em', lineHeight:1.2,
                textAlign:'left', display:'flex', flexDirection:'column', gap:8,
                minHeight:92,
                transition:'all 200ms cubic-bezier(.4,1.4,.6,1)',
              }}>
              <div style={{
                width:26,height:26,borderRadius:8,
                background: sc.fg==='white' ? 'rgba(255,255,255,0.25)' : 'rgba(14,8,40,0.15)',
                color: sc.fg, display:'flex', alignItems:'center', justifyContent:'center',
                fontWeight:900, fontSize:13
              }}>{sc.label}</div>
              <div>{opt}</div>
            </button>
          );
        })}
      </div>

      <div style={{flex:1}}/>

      {/* lifelines */}
      <div className="pad" style={{paddingBottom:24}}>
        <div style={{display:'flex',gap:10}}>
          {[
            {icon:'⏱', label:'+5s', count:2},
            {icon:'½', label:'50/50', count:1},
            {icon:'⏭', label:'Saltar', count:3},
          ].map(lf=>(
            <button key={lf.label} disabled={revealed} style={{
              flex:1,background:'rgba(255,255,255,0.08)',border:'none',borderRadius:18,padding:'10px 8px',
              cursor:revealed?'default':'pointer',color:'white',position:'relative',
              boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.12)',
              opacity:revealed?0.4:1,
            }}>
              <div style={{fontSize:20}}>{lf.icon}</div>
              <div style={{fontWeight:700,fontSize:11,marginTop:2,letterSpacing:'-0.005em'}}>{lf.label}</div>
              <div style={{position:'absolute',top:6,right:8,minWidth:16,height:16,padding:'0 4px',borderRadius:999,background:'#FFD60A',color:'#0E0828',fontWeight:900,fontSize:9,display:'flex',alignItems:'center',justifyContent:'center'}}>{lf.count}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============== 4. Correct feedback ==============
window.CorrectFeedback = function CorrectFeedback({ category, points, streak, onNext, fact }) {
  return (
    <div className="tr-screen" style={{background:'linear-gradient(180deg,#00E5A8 0%, #00B886 100%)',color:'#0E0828'}}>
      {/* confetti dots */}
      {Array.from({length:14}).map((_,i)=>{
        const colors = ['#FFD60A','#FF4D8D','#38BDF8','#6C3BFF','white'];
        const left = (i*7+5) % 100;
        const delay = (i%5) * 0.18;
        const dur = 2 + (i%3)*0.6;
        const sz = 8 + (i%4)*4;
        return <div key={i} style={{
          position:'absolute',left:`${left}%`,top:-20,width:sz,height:sz,
          background:colors[i%colors.length],borderRadius: i%3===0?2:999,
          animation:`tr-confetti-fall ${dur}s linear infinite`,animationDelay:`${delay}s`,zIndex:1
        }}/>;
      })}

      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center',alignItems:'center',padding:'0 24px',position:'relative',zIndex:2}}>
        <div className="tr-bounce-in" style={{
          width:140,height:140,borderRadius:999,background:'white',
          display:'flex',alignItems:'center',justifyContent:'center',
          boxShadow:'0 12px 0 rgba(0,0,0,0.15), 0 0 0 12px rgba(255,255,255,0.3)',
        }}>
          <svg width="72" height="72" viewBox="0 0 72 72" fill="none">
            <path d="M18 36 L32 50 L54 24" stroke="#00B886" strokeWidth="9" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div className="tr-bounce-in" style={{fontWeight:900,fontSize:42,color:'#0E0828',marginTop:24,letterSpacing:'-0.04em',animationDelay:'120ms'}}>¡Eso es!</div>
        <div className="tr-bounce-in" style={{fontWeight:700,fontSize:15,color:'rgba(14,8,40,0.7)',marginTop:4,animationDelay:'200ms'}}>Respuesta correcta</div>

        <div className="tr-bounce-in" style={{
          marginTop:28,display:'flex',gap:10,animationDelay:'280ms'
        }}>
          <div style={{background:'#0E0828',color:'#FFD60A',borderRadius:16,padding:'10px 16px',fontWeight:900,fontSize:18,letterSpacing:'-0.02em',boxShadow:'0 4px 0 rgba(0,0,0,0.4)'}}>
            <span style={{fontWeight:700,fontSize:11,letterSpacing:'.06em',textTransform:'uppercase',color:'rgba(255,214,10,0.7)',display:'block'}}>Puntos</span>
            +{points}
          </div>
          {streak>=2 && (
            <div style={{background:'#FF6B35',color:'white',borderRadius:16,padding:'10px 16px',fontWeight:900,fontSize:18,letterSpacing:'-0.02em',boxShadow:'0 4px 0 #D9501F'}}>
              <span style={{fontWeight:700,fontSize:11,letterSpacing:'.06em',textTransform:'uppercase',color:'rgba(255,255,255,0.8)',display:'block'}}>Racha</span>
              🔥 x{streak}
            </div>
          )}
        </div>

        {fact && (
          <div className="tr-bounce-in" style={{
            marginTop:28,padding:'12px 18px',
            background:'rgba(14,8,40,0.12)',borderRadius:16,
            fontWeight:600,fontSize:13,color:'#0E0828',textAlign:'center',
            maxWidth:300,textWrap:'pretty',animationDelay:'360ms'
          }}>
            <span style={{fontWeight:800,opacity:.7,letterSpacing:'.04em',textTransform:'uppercase',fontSize:10,marginRight:6}}>Dato</span>
            {fact}
          </div>
        )}
      </div>

      <div className="pad" style={{paddingBottom:32}}>
        <button className="tr-btn ink full lg" onClick={onNext}>Siguiente pregunta →</button>
      </div>
    </div>
  );
};

// ============== 5. Wrong feedback ==============
window.WrongFeedback = function WrongFeedback({ correctAnswer, onNext, fact, livesLeft = 2 }) {
  return (
    <div className="tr-screen" style={{background:'linear-gradient(180deg,#FF4D8D 0%, #E12C6F 100%)',color:'white'}}>
      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center',alignItems:'center',padding:'0 24px'}}>
        <div className="tr-bounce-in" style={{
          width:140,height:140,borderRadius:999,background:'white',
          display:'flex',alignItems:'center',justifyContent:'center',
          boxShadow:'0 12px 0 rgba(0,0,0,0.18), 0 0 0 12px rgba(255,255,255,0.3)',
          animation:'tr-shake 500ms cubic-bezier(.36,.07,.19,.97) 320ms 1, tr-bounce-in 420ms cubic-bezier(.34,1.56,.64,1) both'
        }}>
          <svg width="68" height="68" viewBox="0 0 68 68" fill="none">
            <path d="M18 18 L50 50 M50 18 L18 50" stroke="#E12C6F" strokeWidth="9" strokeLinecap="round"/>
          </svg>
        </div>
        <div className="tr-bounce-in" style={{fontWeight:900,fontSize:42,color:'white',marginTop:24,letterSpacing:'-0.04em',animationDelay:'120ms'}}>¡Casi!</div>
        <div className="tr-bounce-in" style={{fontWeight:600,fontSize:15,color:'rgba(255,255,255,0.85)',marginTop:4,animationDelay:'200ms'}}>No esta vez</div>

        <div className="tr-bounce-in" style={{
          marginTop:28,padding:'14px 20px',
          background:'rgba(255,255,255,0.18)',borderRadius:18,
          backdropFilter:'blur(10px)',
          textAlign:'center',animationDelay:'280ms',
          boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.25)'
        }}>
          <div style={{fontWeight:700,fontSize:11,color:'rgba(255,255,255,0.85)',letterSpacing:'.06em',textTransform:'uppercase'}}>Respuesta correcta</div>
          <div style={{fontWeight:900,fontSize:22,color:'white',marginTop:4,letterSpacing:'-0.02em'}}>{correctAnswer}</div>
        </div>

        <div className="tr-bounce-in" style={{marginTop:18,display:'flex',gap:6,animationDelay:'360ms'}}>
          {[0,1,2].map(i=>(
            <div key={i} style={{
              width:22,height:22,
              fontSize:18,
              opacity: i<livesLeft ? 1 : 0.3,
              filter: i<livesLeft ? 'none' : 'grayscale(1)',
              display:'flex',alignItems:'center',justifyContent:'center'
            }}>❤️</div>
          ))}
        </div>

        {fact && (
          <div className="tr-bounce-in" style={{
            marginTop:24,padding:'12px 18px',
            background:'rgba(255,255,255,0.18)',borderRadius:16,
            fontWeight:600,fontSize:13,color:'white',textAlign:'center',
            maxWidth:300,textWrap:'pretty',animationDelay:'440ms'
          }}>
            <span style={{fontWeight:800,opacity:.85,letterSpacing:'.04em',textTransform:'uppercase',fontSize:10,marginRight:6}}>Dato</span>
            {fact}
          </div>
        )}
      </div>

      <div className="pad" style={{paddingBottom:32,display:'flex',gap:10}}>
        <button className="tr-btn ghost" onClick={onNext} style={{flex:1}}>Saltar</button>
        <button className="tr-btn ink full lg" onClick={onNext} style={{flex:2}}>Continuar →</button>
      </div>
    </div>
  );
};
