// Variant A — "Póster cinemático" (con concurso completo)
//
// El navegador solo recuerda el último piloto registrado. El alta, la subida
// de fotos y el ranking viven en el servidor para que todo sea compartido.

const CAS_STATE_KEY = 'cas-state-v1';
const CAS_REGISTER_API = '/api/register.php?format=json';
const CAS_UPLOAD_API = '/api/upload.php?format=json';
const CAS_RANKING_API = '/ranking.php?format=json&v=20260509a';
const CAS_RANKING_CACHE_KEY = 'cas-ranking-cache-v6';
const CAS_WHATSAPP_GROUP_URL = 'https://chat.whatsapp.com/FVRHwKoBqTT3ncAlU1DWDk';

function loadState(){
  try{
    const raw = localStorage.getItem(CAS_STATE_KEY);
    if(!raw) return defaultState();
    const s = JSON.parse(raw);
    const next = {...defaultState(), ...s};
    if (typeof next.me === 'string') next.me = null;
    if (next.me && typeof next.me === 'object' && !next.me.codigo) next.me = null;
    return { me: next.me || null };
  }catch{return defaultState();}
}
function defaultState(){
  return { me: null };
}
function saveState(s){
  try{ localStorage.setItem(CAS_STATE_KEY, JSON.stringify(s)); }catch{}
}
const StateCtx = React.createContext(null);

function useCasState(){
  const [state, setState] = React.useState(loadState);
  const update = React.useCallback((fn)=>{
    setState(prev=>{
      const next = typeof fn==='function' ? fn(prev) : fn;
      saveState(next);
      return next;
    });
  },[]);
  // sync across tabs
  React.useEffect(()=>{
    const onStorage = (e)=>{ if(e.key===CAS_STATE_KEY) setState(loadState()); };
    window.addEventListener('storage', onStorage);
    return ()=>window.removeEventListener('storage', onStorage);
  },[]);
  return [state, update];
}

// ─────────────────────────────────────────────────────────────
function VariantPoster() {
  const [state, setState] = useCasState();
  const [lightbox, setLightbox] = React.useState(null);
  const [legalOpen, setLegalOpen] = React.useState(false);

  return (
    <StateCtx.Provider value={{state, setState, openLightbox:setLightbox, openLegal:()=>setLegalOpen(true)}}>
      <div style={{
        width: '100%', minHeight:'100vh',
        background: '#0d0a08', color: '#e8e2d5',
        fontFamily: 'var(--cas-body, "Inter", system-ui, sans-serif)',
        position: 'relative',
      }}>
        <GlobalStyle />
        <HeroPoster />
        <HowItWorks />
        <RegistrationSection />
        <RankingSection />
        <WhatsappSection />
        <PrizesSection />
        <FooterSection />
        {lightbox && <Lightbox src={lightbox.src} title={lightbox.title} onClose={()=>setLightbox(null)}/>}
        {legalOpen && <LegalModal onClose={()=>setLegalOpen(false)}/>}
      </div>
    </StateCtx.Provider>
  );
}

function scrollToSection(id) {
  const el = document.getElementById(id);
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}

function getRankChipStyle(slotState, slot) {
  const isBonus = !!slot?.bonus;
  const isExtra = !!slot?.extra;
  const isApproved = slotState === 'aprobado' || slot?.done;
  const isSubmitted = slotState === 'pendiente' || slotState === 'revision';
  const isRejected = slotState === 'rechazado';

  if (isBonus) {
    if (isApproved) return { bg: 'linear-gradient(180deg,#e06a58 0%,#8d2018 100%)', border: '#b24337', color: '#fff4f1' };
    if (isSubmitted) return { bg: 'linear-gradient(180deg,#f08a7a 0%,#a63428 100%)', border: '#d56a5d', color: '#fff4f1' };
    if (isRejected) return { bg: 'linear-gradient(180deg,#4a231c 0%,#26120f 100%)', border: 'rgba(205,94,74,.32)', color: '#f0c9be' };
    return { bg: 'linear-gradient(180deg,rgba(91,28,24,.78) 0%,rgba(47,14,12,.84) 100%)', border: 'rgba(198,76,63,.22)', color: '#f0c9be' };
  }

  if (isExtra) {
    if (isApproved) return { bg: 'linear-gradient(180deg,#c87f41 0%,#7a4a20 100%)', border: '#a96b34', color: '#1a0f06' };
    if (isSubmitted) return { bg: 'linear-gradient(180deg,#d7a358 0%,#8c5a21 100%)', border: '#b97b35', color: '#1a0f06' };
    if (isRejected) return { bg: 'linear-gradient(180deg,#422218 0%,#24130f 100%)', border: 'rgba(205,94,74,.28)', color: '#efc9bc' };
    return { bg: 'linear-gradient(180deg,rgba(72,45,28,.75) 0%,rgba(36,22,16,.82) 100%)', border: 'rgba(185,123,53,.2)', color: '#c9b29a' };
  }

  if (isApproved) return { bg: 'linear-gradient(180deg,#e28a48 0%,#b35b24 100%)', border: '#c86d31', color: '#1a0f06' };
  if (isSubmitted) return { bg: 'linear-gradient(180deg,#fff06a 0%,#f0b700 100%)', border: '#f1c83a', color: '#1a0f06' };
  if (isRejected) return { bg: 'linear-gradient(180deg,#4a231c 0%,#26120f 100%)', border: 'rgba(205,94,74,.32)', color: '#f0c9be' };
  return { bg: 'rgba(0,0,0,.32)', border: 'var(--cas-border)', color: 'var(--cas-bone-dim)' };
}

// ── Global style ──────────────────────────────────────────────
function GlobalStyle() {
  return (
    <style>{`
      :root{
        --cas-orange:#d97435; --cas-orange-2:#e08848;
        --cas-bone:#e8e2d5; --cas-bone-dim:#b8ae9a;
        --cas-ink:#0d0a08; --cas-ink-2:#15110d; --cas-card:#1a1612;
        --cas-border:rgba(216,200,170,.14);
        --cas-display:"Anton","Bebas Neue",sans-serif;
        --cas-hand:"Caveat",cursive;
        --cas-stencil:"Special Elite",monospace;
        --cas-body:"Inter",system-ui,sans-serif;
      }
      *{box-sizing:border-box}
      html{scroll-behavior:smooth}
      img{max-width:100%}
      .cas-hero-grid{display:grid;grid-template-columns:1.2fr .8fr;gap:32px;align-items:end;margin-top:64px}
      .cas-reg-grid{display:grid;grid-template-columns:1fr 1.2fr;gap:48px;align-items:start}
      .cas-rank-head,.cas-rank-row{display:grid;grid-template-columns:70px 1fr 1.8fr 90px;gap:0}
      .cas-reg-title{font-size:74px}
      .cas-reg-sub{font-size:42px}
      .cas-countbox-num{font-size:124px}
      .cas-code-num{font-size:120px}
      .cas-section{padding:100px 48px}
      .cas-grid-4{display:grid;grid-template-columns:repeat(4,1fr);gap:22px}
      .cas-grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:28px}
      .cas-grid-2{display:grid;grid-template-columns:1fr 1fr;gap:40px}
      .cas-how-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:22px;margin-top:60px}
      .cas-hero-nav{display:flex;gap:24px}
      .cas-mobile-quicknav{display:none}
      .cas-hero-bottom{display:flex;justify-content:space-between;align-items:flex-end;gap:40px;padding:0 48px}
      .cas-h1{font-size:92px}
      .cas-h2{font-size:72px}
      .cas-rank-grid{display:grid;grid-template-columns:60px 1fr 80px repeat(6,1fr) 70px;gap:0;padding:14px 16px;align-items:center}
      .cas-rank-topline{
        display:grid;
        grid-template-columns:auto minmax(0,1fr) auto;
        align-items:end;
        gap:12px;
      }
      .cas-rank-bottomline{
        display:grid;
        grid-template-columns:1fr;
        align-items:center;
        gap:14px;
      }
      .cas-rank-bar{
        display:flex;
        gap:4px;
        align-items:stretch;
        min-width:0;
        width:100%;
      }
      .cas-rank-segment{
        display:flex;
        align-items:center;
        justify-content:center;
        height:20px;
        border-radius:999px;
        border:1px solid var(--cas-border);
        background:rgba(0,0,0,.32);
        color:var(--cas-bone-dim);
        font-family:var(--cas-stencil);
        font-size:10px;
        letter-spacing:.18em;
        text-transform:uppercase;
        overflow:hidden;
        white-space:nowrap;
        min-width:0;
      }
      .cas-rank-segment.is-aprobado{
        background:linear-gradient(180deg,#e28a48 0%,#b35b24 100%);
        color:#1a0f06;
        border-color:#c86d31;
      }
      .cas-rank-segment.is-pendiente,
      .cas-rank-segment.is-revision{
        background:linear-gradient(180deg,#fff06a 0%,#f0b700 100%);
        color:#1a0f06;
        border-color:#f1c83a;
      }
      .cas-rank-segment.is-rechazado{
        background:linear-gradient(180deg,#4a231c 0%,#26120f 100%);
        color:#f0c9be;
        border-color:rgba(205,94,74,.32);
      }
      .cas-rank-segment.extra.is-aprobado{
        background:linear-gradient(180deg,#c87f41 0%,#7a4a20 100%);
        color:#1a0f06;
        border-color:#a96b34;
      }
      .cas-rank-segment.extra.is-pendiente,
      .cas-rank-segment.extra.is-revision{
        background:linear-gradient(180deg,#fff06a 0%,#f0b700 100%);
        color:#1a0f06;
        border-color:#f1c83a;
      }
      .cas-rank-segment.extra.is-empty{
        background:linear-gradient(180deg,rgba(72,45,28,.75) 0%,rgba(36,22,16,.82) 100%);
        color:#c9b29a;
        border-color:rgba(185,123,53,.2);
      }
      .cas-rank-segment.bonus.is-aprobado{
        background:linear-gradient(180deg,#e06a58 0%,#8d2018 100%);
        color:#fff4f1;
        border-color:#b24337;
      }
      .cas-rank-segment.bonus.is-pendiente,
      .cas-rank-segment.bonus.is-revision{
        background:linear-gradient(180deg,#f08a7a 0%,#a63428 100%);
        color:#fff4f1;
        border-color:#d56a5d;
      }
      .cas-rank-segment.bonus.is-empty{
        background:linear-gradient(180deg,rgba(91,28,24,.78) 0%,rgba(47,14,12,.84) 100%);
        color:#f0c9be;
        border-color:rgba(198,76,63,.22);
      }
      .cas-rank-points{
        font-family:var(--cas-display);
        font-size:24px;
        color:var(--cas-orange);
        font-variant-numeric:tabular-nums;
        text-align:right;
        white-space:nowrap;
      }
      .cas-rank-count{
        font-family:var(--cas-stencil);
        font-size:10px;
        letter-spacing:.24em;
        color:var(--cas-bone-dim);
        text-transform:uppercase;
        text-align:right;
        white-space:nowrap;
      }
      .cas-rank-mobile-cell{display:none}
      @media (max-width:780px){
        .cas-section{padding:64px 20px !important}
        .cas-grid-4,.cas-grid-3,.cas-grid-2{grid-template-columns:1fr !important;gap:18px !important}
        .cas-how-grid{display:flex !important;flex-direction:column !important;gap:16px !important;margin-top:32px !important}
        .cas-hero-grid{grid-template-columns:1fr !important;gap:20px !important;margin-top:28px !important}
        .cas-hero-nav{display:none !important}
        .cas-mobile-quicknav{
          display:grid !important;
          grid-template-columns:1fr 1fr;
          gap:10px;
          margin-top:18px;
        }
        .cas-mobile-quicknav a{
          display:flex;
          align-items:center;
          justify-content:center;
          min-height:46px;
          padding:10px 12px;
          background:rgba(0,0,0,.28);
          border:1px solid var(--cas-border);
          color:var(--cas-bone);
          font-family:var(--cas-stencil);
          font-size:10px;
          letter-spacing:.22em;
          text-transform:uppercase;
          text-decoration:none;
        }
        .cas-hero-bottom{flex-direction:column;align-items:flex-start;padding:0 20px !important;gap:20px !important}
        .cas-h1{font-size:56px !important}
        .cas-h2{font-size:44px !important}
        .cas-reg-grid{grid-template-columns:1fr !important;gap:28px !important}
        .cas-reg-title{font-size:52px !important}
        .cas-reg-sub{font-size:28px !important}
        .cas-code-num{font-size:72px !important}
        .cas-rank-head{display:none !important}
        .cas-rank-row{display:flex !important;flex-direction:column !important;gap:10px !important;padding:14px 16px !important;align-items:stretch !important}
        .cas-rank-topline{display:grid !important;grid-template-columns:auto minmax(0,1fr) auto;align-items:end;gap:10px;width:100%}
        .cas-rank-bottomline{display:block !important;width:100%}
        .cas-rank-pos{font-size:20px !important}
        .cas-rank-name{font-size:16px !important}
        .cas-rank-count{font-size:9px !important;letter-spacing:.18em !important}
        .cas-rank-points{font-size:13px !important;text-align:right !important;letter-spacing:.08em !important;white-space:nowrap !important}
        .cas-rank-bar{gap:2px !important}
        .cas-rank-segment{
          min-width:6px !important;
          height:8px !important;
          padding:0 !important;
          border-radius:999px !important;
          font-size:0 !important;
          letter-spacing:0 !important;
        }
        .cas-hero-follow{display:none !important}
        .cas-countbox-num{font-size:92px !important}
        .cas-hero-inner{padding:16px 20px 20px !important}
        .cas-hero{height:auto !important;min-height:0 !important;padding-bottom:18px !important}
        .cas-hero-figure{display:none !important}
        .cas-stamp{font-size:9px}
        .cas-section-h{font-size:48px !important}
        .cas-mobile-stack{flex-direction:column !important;align-items:flex-start !important}
        .cas-rank-head > div,.cas-rank-row > div{min-width:0}
      }
      .cas-grain{
        position:absolute;inset:0;pointer-events:none;opacity:.35;mix-blend-mode:overlay;
        background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='240' height='240'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.9 0 0 0 0 0.85 0 0 0 0 0.7 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>");
      }
      .cas-stamp{
        display:inline-block;padding:6px 14px;border:2px solid var(--cas-orange);
        color:var(--cas-orange);font-family:var(--cas-stencil);font-size:11px;
        letter-spacing:.35em;text-transform:uppercase;transform:rotate(-2deg);
        background:rgba(217,116,53,.05);
      }
      .cas-ticker{display:flex;gap:40px;white-space:nowrap;animation:cas-ticker 40s linear infinite}
      @keyframes cas-ticker{0%{transform:translateX(0)}100%{transform:translateX(-50%)}}
      .cas-btn-primary{
        display:inline-flex;align-items:center;gap:10px;padding:16px 28px;
        background:var(--cas-orange);color:#1a0f06;font-family:var(--cas-display);
        font-size:18px;letter-spacing:.15em;text-transform:uppercase;
        border:none;cursor:pointer;transition:all .15s;
        clip-path:polygon(8px 0,100% 0,calc(100% - 8px) 100%,0 100%);
      }
      .cas-btn-primary:hover{background:var(--cas-orange-2);transform:translateY(-2px)}
      .cas-btn-ghost{
        display:inline-flex;align-items:center;gap:10px;padding:14px 24px;
        background:transparent;color:var(--cas-bone);font-family:var(--cas-display);
        font-size:16px;letter-spacing:.15em;text-transform:uppercase;
        border:1px solid var(--cas-border);cursor:pointer;transition:all .15s;
      }
      .cas-btn-ghost:hover{border-color:var(--cas-orange);color:var(--cas-orange)}
      .cas-input,.cas-select{
        width:100%;background:rgba(0,0,0,.35);border:1px solid var(--cas-border);
        border-bottom:2px solid rgba(216,200,170,.4);
        color:var(--cas-bone);font-family:var(--cas-body);font-size:15px;
        padding:14px 16px;transition:all .15s;outline:none;
      }
      .cas-input:focus,.cas-select:focus{border-bottom-color:var(--cas-orange);background:rgba(0,0,0,.55)}
      .cas-input::placeholder{color:rgba(184,174,154,.5)}
      .cas-label{
        font-family:var(--cas-stencil);font-size:10px;letter-spacing:.3em;
        text-transform:uppercase;color:var(--cas-bone-dim);margin-bottom:6px;display:block;
      }
      .cas-card-panel{background:var(--cas-card);border:1px solid var(--cas-border);position:relative}
      .cas-taped{position:relative}
      .cas-taped::before,.cas-taped::after{
        content:'';position:absolute;width:70px;height:18px;
        background:rgba(230,220,190,.18);border:1px dashed rgba(230,220,190,.3);
        top:-9px;transform:rotate(-3deg);pointer-events:none;
      }
      .cas-taped::before{left:18px}
      .cas-taped::after{right:18px;transform:rotate(4deg)}
      .cas-clue-img{cursor:zoom-in;transition:transform .25s,filter .25s}
      .cas-clue-img:hover{transform:scale(1.02);filter:brightness(1.1)}
      .cas-rank-row{transition:background .2s,transform .2s}
      .cas-rank-row:hover{background:rgba(217,116,53,.06)}
      .cas-rank-row.cas-mine{background:rgba(217,116,53,.12);border-left:3px solid var(--cas-orange)}
      @keyframes cas-pulse{0%,100%{box-shadow:0 0 0 0 rgba(217,116,53,.5)}50%{box-shadow:0 0 0 12px rgba(217,116,53,0)}}
      .cas-pulse{animation:cas-pulse 2s infinite}
    `}</style>
  );
}

// ── HERO ──────────────────────────────────────────────────────
function HeroPoster() {
  return (
    <section className="cas-hero" style={{ position: 'relative', width: '100%', overflow: 'hidden', background:'linear-gradient(180deg,#0b0806 0%,#120f0c 100%)', borderBottom:'1px solid var(--cas-border)' }}>
      <div className="cas-grain"/>
      <div className="cas-hero-inner" style={{position:'relative',maxWidth:1280,margin:'0 auto',padding:'28px 24px 72px'}}>
      <div style={{position:'absolute',inset:0,background:'radial-gradient(ellipse at 30% 20%,rgba(217,116,53,.08) 0%,transparent 40%),radial-gradient(ellipse at 80% 30%,rgba(217,116,53,.06) 0%,transparent 42%)',pointerEvents:'none'}}/>
      <div style={{position:'relative',zIndex:2,display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:12}}>
        <div style={{display:'flex',alignItems:'center',gap:12,color:'var(--cas-bone)'}}>
          <div style={{width:36,height:36}}><LogoSvg/></div>
          <span style={{fontFamily:'var(--cas-display)',fontSize:22,letterSpacing:'.25em'}}>CASCOTERAPIA</span>
        </div>
        <nav className="cas-hero-nav" style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',textTransform:'uppercase'}}>
          <a href="#como" style={linkStyle}>Cómo funciona</a>
          <a href={CAS_WHATSAPP_GROUP_URL} target="_blank" rel="noopener" style={linkStyle}>Grupo WhatsApp</a>
          <a href="/encuesta.php" style={linkStyle}>Encuesta</a>
          <a
            href="#subir"
            onClick={(e)=>{e.preventDefault(); scrollToSection('subir');}}
            style={{
              ...linkStyle,
              padding:'10px 14px',
              border:'1px solid var(--cas-orange)',
              background:'var(--cas-orange)',
              borderRadius:999,
              color:'#1a0f06',
              boxShadow:'0 0 0 1px rgba(217,116,53,.14)',
              fontWeight:800,
            }}
          >
            Subir foto
          </a>
          <a
            href="#ranking"
            onClick={(e)=>{e.preventDefault(); scrollToSection('ranking');}}
            style={{
              ...linkStyle,
              padding:'10px 14px',
              border:'1px solid var(--cas-border)',
              borderRadius:999,
              color:'var(--cas-bone)',
            }}
            >
            Ver ranking
          </a>
          <a href="#ficha-piloto" style={linkStyle}>Participar</a>
          <a href="#premios" style={linkStyle}>Premios</a>
        </nav>
      </div>
      <div className="cas-mobile-quicknav">
        <a href="#subir" onClick={(e)=>{e.preventDefault(); scrollToSection('subir');}}>SUBIR FOTO</a>
        <a href="#ranking" onClick={(e)=>{e.preventDefault(); scrollToSection('ranking');}}>VER RANKING</a>
      </div>
      <div className="cas-hero-grid" style={{position:'relative',zIndex:2,alignItems:'end',marginTop:64}}>
        <div style={{maxWidth:760}}>
          <div className="cas-stamp" style={{marginBottom:14}}>Estreno · web + concurso</div>
          <div style={{fontFamily:'var(--cas-display)',fontSize:14,letterSpacing:'.45em',color:'var(--cas-orange)',marginBottom:8}}>SOLO PARA LOS QUE SALEN DEL CAPARAZÓN</div>
          <h1 className="cas-h1" style={{fontFamily:'var(--cas-display)',lineHeight:.92,margin:'0 0 8px',color:'var(--cas-bone)',letterSpacing:'.01em'}}>LA PRUEBA</h1>
          <div style={{fontFamily:'var(--cas-hand)',fontSize:44,color:'var(--cas-orange)',marginTop:-4,marginLeft:4,transform:'rotate(-2deg)',display:'inline-block'}}>cascoterapia</div>
          <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.55,color:'var(--cas-bone-dim)',marginTop:20,maxWidth:500}}>
            spin off del Feel it Challenge del 4º aniversario en 2026. Una pequeña prueba para ir abriendo boca hasta que llegue el tan deseado Challenge.
          </p>
          <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.55,color:'var(--cas-bone-dim)',marginTop:14,maxWidth:500}}>
            Los avisos se comunicarán solo en el grupo de WhatsApp y la subida de fotos se hace aquí, por la web.
          </p>
          <div style={{display:'flex',gap:12,flexWrap:'wrap',marginTop:28}}>
            <a href="#subir" onClick={(e)=>{e.preventDefault(); scrollToSection('subir');}} className="cas-btn-primary">SUBIR FOTO</a>
            <a href={CAS_WHATSAPP_GROUP_URL} target="_blank" rel="noopener" className="cas-btn-ghost">GRUPO WHATSAPP</a>
            <a href="/encuesta.php" className="cas-btn-ghost">ENCUESTA</a>
          </div>
        </div>
        <div className="cas-hero-follow" style={{textAlign:'right',fontFamily:'var(--cas-display)',color:'var(--cas-bone-dim)',justifySelf:'end'}}>
          <div style={{fontSize:11,letterSpacing:'.4em',opacity:.7}}>↓ SIGUE BAJANDO</div>
          <div style={{fontSize:11,letterSpacing:'.4em',marginTop:4}}>CÓMO FUNCIONA</div>
        </div>
      </div>
      </div>
    </section>
  );
}

function LogoSvg(){
  return <img src="/assets/logo-optimized.png" alt="cascoterapia" loading="eager" decoding="async" style={{width:'100%',height:'100%',objectFit:'contain',display:'block'}}/>;
}
const linkStyle = { color:'inherit', textDecoration:'none', transition:'color .15s' };

// ── HOW IT WORKS ──────────────────────────────────────────────
function HowItWorks(){
  const steps = [
    {n:'01',t:'INSCRÍBETE',d:'Nombre y teléfono. Te asignamos un código de 4 dígitos que te identifica en el ranking.'},
    {n:'02',t:'MIRA LAS PISTAS EN EL GRUPO WHATSAPP',d:'Las pistas y los avisos se comparten ahí.'},
    {n:'03',t:'SUBE LA FOTO',d:'Hazte la foto con la pegatina, usa tu código y selecciona el punto que has encontrado.'},
    {n:'04',t:'SUBE EN EL RANKING EN DIRECTO',d:'La barra de progreso crece al subir la foto y se pone naranja cuando el admin la valida.'},
  ];
  return (
    <section id="como" style={{padding:'100px 48px',position:'relative',background:'#0d0a08'}}>
      <div style={{maxWidth:1200,margin:'0 auto'}}>
        <SectionHeader kicker="01 · CÓMO FUNCIONA" title="CÓMO FUNCIONA"/>
        <div className="cas-how-grid" style={{marginTop:60}}>
          {steps.map((st,i)=>(
            <div key={i} style={{position:'relative',padding:'32px 24px',background:'var(--cas-card)',border:'1px solid var(--cas-border)'}}>
              <div style={{fontFamily:'var(--cas-display)',fontSize:48,color:'var(--cas-orange)',lineHeight:1,marginBottom:18}}>{st.n}</div>
              <h3 style={{fontFamily:'var(--cas-display)',fontSize:22,color:'var(--cas-bone)',margin:'0 0 10px',letterSpacing:'.08em'}}>{st.t}</h3>
              <p style={{fontFamily:'var(--cas-body)',fontSize:13.5,lineHeight:1.6,color:'var(--cas-bone-dim)',margin:0}}>{st.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function SectionHeader({kicker,title,align='left'}){
  return (
    <div style={{textAlign:align}}>
      <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.45em',color:'var(--cas-orange)',marginBottom:12}}>{kicker}</div>
      <h2 className="cas-h2 cas-section-h" style={{fontFamily:'var(--cas-display)',fontSize:72,lineHeight:.95,margin:0,color:'var(--cas-bone)',letterSpacing:'.01em'}}>{title}</h2>
      <div style={{marginTop:16,width:80,height:3,background:'var(--cas-orange)'}}/>
    </div>
  );
}

// ── CLUES ─────────────────────────────────────────────────────
const MAIN_POINTS = [
  {id:'pista1', n:'PISTA 01', title:'PISTA 01', place:'', points:1},
  {id:'pista2', n:'PISTA 02', title:'PISTA 02', place:'', points:1},
  {id:'pista3', n:'PISTA 03', title:'PISTA 03', place:'', points:1},
  {id:'pista4', n:'PISTA 04', title:'PISTA 04', place:'', points:1},
  {id:'pista5', n:'PISTA 05', title:'PISTA 05', place:'', points:1},
  {id:'bonus1', n:'BONUS 01', title:'BONUS 01', place:'', points:5, isBonus:true, badge:'★'},
  {id:'bonus2', n:'BONUS 02', title:'BONUS 02', place:'', points:5, isBonus:true, badge:'✦'},
];
const EXTRA_POINTS = Array.from({length:36}, (_, i) => {
  const n = i + 1;
  const label = String(n).padStart(2, '0');
  return {
    id:`extra${n}`,
    n:`CASCO ${label}`,
    title:`Casco ${label}`,
    place:`Casco ${label}`,
    points:2,
    isExtra:true,
    badge:'⛑',
  };
});
const CLUES = MAIN_POINTS;
const RANK_SLOTS = [...MAIN_POINTS, ...EXTRA_POINTS];
const RANK_TOTAL_POINTS = 87;
const RANK_TOTAL_PHOTOS = 45;

function WhatsappSection(){
  return (
    <section id="whatsapp" className="cas-section" style={{padding:'100px 48px',background:'#15110d',position:'relative',borderTop:'1px solid var(--cas-border)',borderBottom:'1px solid var(--cas-border)'}}>
      <div className="cas-grain"/>
      <div style={{maxWidth:1280,margin:'0 auto',position:'relative'}}>
        <div className="cas-grid-2" style={{alignItems:'center'}}>
          <div>
            <SectionHeader kicker="05 · GRUPO PRIVADO" title="WHATSAPP"/>
            <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.6,color:'var(--cas-bone-dim)',marginTop:20,maxWidth:560}}>
              Los avisos se compartirán en el grupo de WhatsApp. La recogida de fotos y la validación siguen haciéndose por la web para que todo quede ordenado.
            </p>
            <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.6,color:'var(--cas-bone-dim)',marginTop:14,maxWidth:560}}>
              Una vez entres al grupo, podrás seguir el avance del reto y subir cada foto desde el formulario de arriba.
            </p>
          </div>
          <div className="cas-card-panel" style={{padding:'30px 28px',background:'rgba(10,8,6,.9)'}}>
            <div className="cas-stamp" style={{marginBottom:16}}>MENSAJES + AVISOS</div>
            <div style={{fontFamily:'var(--cas-display)',fontSize:42,lineHeight:.95,color:'var(--cas-bone)'}}>TODO SE COMUNICA AHÍ</div>
            <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.6,color:'var(--cas-bone-dim)',margin:'18px 0 0'}}>
              Únete al grupo para recibir los avisos en tiempo real.
            </p>
            <div style={{marginTop:22,display:'flex',gap:10,flexWrap:'wrap'}}>
              <a href={CAS_WHATSAPP_GROUP_URL} target="_blank" rel="noopener" className="cas-btn-primary">UNIRME AL GRUPO</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── LIGHTBOX ──────────────────────────────────────────────────
function Lightbox({src,title,onClose}){
  React.useEffect(()=>{
    const onKey = (e)=>{ if(e.key==='Escape') onClose(); };
    window.addEventListener('keydown',onKey);
    document.body.style.overflow='hidden';
    return ()=>{window.removeEventListener('keydown',onKey);document.body.style.overflow=''};
  },[onClose]);
  return (
    <div onClick={onClose} style={{
      position:'fixed',inset:0,background:'rgba(5,3,2,.94)',zIndex:9000,
      display:'flex',alignItems:'center',justifyContent:'center',padding:40,cursor:'zoom-out',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{position:'relative',maxWidth:'90vw',maxHeight:'90vh'}}>
        <div style={{fontFamily:'var(--cas-display)',fontSize:18,letterSpacing:'.3em',color:'var(--cas-orange)',marginBottom:14,textAlign:'center'}}>{title}</div>
        <img src={src} alt={title} style={{maxWidth:'100%',maxHeight:'80vh',display:'block',background:'#1a1612',border:'1px solid var(--cas-border)'}} onError={e=>{e.target.style.display='none'}}/>
        <div style={{
          fontFamily:'var(--cas-hand)',fontSize:24,color:'var(--cas-bone-dim)',textAlign:'center',marginTop:14,
        }}>esc · click fuera para cerrar</div>
      </div>
      <button onClick={onClose} aria-label="Cerrar" style={{position:'absolute',top:24,right:24,width:48,height:48,borderRadius:'50%',background:'rgba(0,0,0,.6)',border:'1px solid var(--cas-border)',color:'var(--cas-bone)',fontSize:24,cursor:'pointer'}}>×</button>
    </div>
  );
}

// ── UPLOAD SECTION ────────────────────────────────────────────
function UploadSection(){
  const {state, setState} = React.useContext(StateCtx);
  const me = state.me && state.me.codigo ? state.me : null;
  const [pistaId, setPistaId] = React.useState(CLUES[0].id);
  const [codigo, setCodigo] = React.useState(me?.codigo || '');
  const [file, setFile] = React.useState(null);
  const [preview, setPreview] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState('');
  const uploadRef = React.useRef(null);

  React.useEffect(()=>{
    if (state.me && state.me.codigo) {
      setCodigo(state.me.codigo);
    } else {
      setCodigo('');
    }
  }, [state.me]);

  const onFile = (e)=>{
    const f = e.target.files?.[0];
    if(!f) return;
    setFile(f);
    const r = new FileReader();
    r.onload = ()=>setPreview(r.result);
    r.readAsDataURL(f);
  };

  const submit = (e)=>{
    e.preventDefault();
    setErr('');
    if(!/^\d{4}$/.test(codigo)){ setErr('Tu código son 4 dígitos.'); return; }
    if(!file){ setErr('Sube una foto con la pegatina.'); return; }
    setSending(true);
    (async ()=>{
      try{
        const formData = new FormData();
        formData.append('codigo', codigo);
        formData.append('pista', pistaId);
        formData.append('foto', file);
        const res = await fetch(CAS_UPLOAD_API, {
          method:'POST',
          headers:{ Accept:'application/json' },
          body: formData,
        });
        const data = await res.json().catch(()=>null);
        if(!res.ok || !data?.ok){
          throw new Error(data?.error || 'No se pudo subir la foto');
        }
        setDone(true);
        setFile(null);
        setPreview('');
        if (uploadRef.current) uploadRef.current.value = '';
        setTimeout(()=>setDone(false), 4000);
      }catch(err){
        setErr(err.message || 'No se pudo subir la foto.');
      }finally{
        setSending(false);
      }
    })();
  };

  return (
    <section id="subir" style={{padding:'100px 48px',background:'#0d0a08',position:'relative',borderTop:'1px solid var(--cas-border)'}}>
      <div style={{maxWidth:1100,margin:'0 auto'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',flexWrap:'wrap',gap:20,marginBottom:50}}>
          <SectionHeader kicker="03 · DEMUESTRA QUE LO ENCONTRASTE" title="SUBE TU FOTO"/>
          {me && (
            <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)'}}>
              PILOTO · <span style={{color:'var(--cas-orange)'}}>{me.codigo}</span> · {me.nombre}
            </div>
          )}
        </div>

        <div className="cas-grid-2" style={{alignItems:'start'}}>
          <div>
            <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.6,color:'var(--cas-bone-dim)',maxWidth:440}}>
              Cuando encuentres una pegatina, hazte <strong style={{color:'var(--cas-bone)'}}>una foto con ella</strong>: un selfie
              o el saludo motero, como prefieras. Mete tu código, selecciona qué punto has encontrado y súbela.
            </p>
            <ul style={{listStyle:'none',padding:0,margin:'24px 0 0',display:'flex',flexDirection:'column',gap:10,fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',textTransform:'uppercase'}}>
              <li>◉ 1 FOTO POR PUNTO</li>
              <li>◉ SELFIE O SALUDO MOTERO</li>
              <li>◉ HASTA QUE AVISEMOS</li>
            </ul>
            {!me && (
              <div style={{marginTop:30,padding:'18px 22px',border:'1px dashed var(--cas-orange)',background:'rgba(217,116,53,.07)',fontFamily:'var(--cas-body)',fontSize:13.5,color:'var(--cas-bone)'}}>
                ▲ ¿Aún no tienes código? <a href="#ficha-piloto" style={{color:'var(--cas-orange)'}}>Inscríbete aquí</a> y te damos uno.
              </div>
            )}
          </div>

          <form onSubmit={submit} className="cas-card-panel" style={{padding:'30px 28px'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:24,letterSpacing:'.1em',color:'var(--cas-bone)',marginBottom:22}}>NUEVA ENTRADA</div>
            <div style={{marginBottom:18}}>
              <label className="cas-label">Tu código · 4 dígitos</label>
              <input
                className="cas-input"
                inputMode="numeric"
                pattern="[0-9]*"
                maxLength={4}
                placeholder="••••"
                value={codigo}
                onChange={e=>setCodigo(e.target.value.replace(/\D/g,'').slice(0,4))}
                style={{letterSpacing:'.4em',fontFamily:'var(--cas-display)',fontSize:22,textAlign:'center'}}
              />
            </div>
            <div style={{marginBottom:18}}>
              <label className="cas-label">Punto que has encontrado</label>
              <select className="cas-select" value={pistaId} onChange={e=>setPistaId(e.target.value)}>
                {CLUES.map(c=>(<option key={c.id} value={c.id} style={{background:'#0d0a08'}}>{c.n}</option>))}
              </select>
            </div>
            <div style={{marginBottom:18}}>
              <label className="cas-label">Foto con la pegatina</label>
              <label htmlFor="cas-upload" style={{
                display:'block',cursor:'pointer',padding:preview?0:'24px 16px',
                border:'1px dashed rgba(216,200,170,.35)',background:'rgba(0,0,0,.3)',
                textAlign:'center',position:'relative',minHeight:preview?0:120,
              }}>
                {preview ? (
                  <img src={preview} alt="preview" style={{display:'block',width:'100%',maxHeight:280,objectFit:'cover'}}/>
                ) : (
                  <>
                    <div style={{fontFamily:'var(--cas-display)',fontSize:32,color:'var(--cas-orange)'}}>＋</div>
                    <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',marginTop:8}}>SELECCIONAR FOTO O ARCHIVO</div>
                  </>
                )}
              </label>
              <input ref={uploadRef} id="cas-upload" type="file" accept="image/*,.jpg,.jpeg,.png,.webp,.gif" onChange={onFile} style={{display:'none'}}/>
            </div>
            {err && <div style={{color:'#ff7a6b',fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.2em',marginBottom:14}}>▲ {err}</div>}
            {done && <div style={{color:'var(--cas-orange)',fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.2em',marginBottom:14}}>✓ FOTO ENVIADA</div>}
            <button type="submit" className="cas-btn-primary" disabled={sending} style={{width:'100%',justifyContent:'center'}}>
              {sending?'SUBIENDO...':'ENVIAR FOTO →'}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}

// ── RANKING ───────────────────────────────────────────────────
function RankingSection(){
  const {state} = React.useContext(StateCtx);
  const [ranking, setRanking] = React.useState([]);
  const [organizers, setOrganizers] = React.useState([]);
  const [maxPoints, setMaxPoints] = React.useState(RANK_TOTAL_POINTS);
  const [maxPhotos, setMaxPhotos] = React.useState(RANK_TOTAL_PHOTOS);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  React.useEffect(()=>{
    let alive = true;
    const loadRanking = async ()=>{
      try{
        setError('');
        const res = await fetch(CAS_RANKING_API, { headers:{ Accept:'application/json' } });
        const data = await res.json().catch(()=>null);
        if(!res.ok || !data || !Array.isArray(data.items)){
          throw new Error('No se pudo cargar el ranking');
        }
        if (alive) {
          const safeItems = Array.isArray(data.items) ? data.items.filter(Boolean) : [];
          const safeOrganizers = Array.isArray(data.organizers) ? data.organizers.filter(Boolean) : [];
          const safeMaxPoints = Number.isFinite(Number(data.maxPoints)) ? Number(data.maxPoints) : RANK_TOTAL_POINTS;
          const safeMaxPhotos = Number.isFinite(Number(data.maxPhotos)) ? Number(data.maxPhotos) : RANK_TOTAL_PHOTOS;
          setRanking(safeItems);
          setOrganizers(safeOrganizers);
          setMaxPoints(safeMaxPoints);
          setMaxPhotos(safeMaxPhotos);
          try {
            localStorage.setItem(CAS_RANKING_CACHE_KEY, JSON.stringify({
              items: safeItems,
              organizers: safeOrganizers,
              maxPoints: safeMaxPoints,
              maxPhotos: safeMaxPhotos,
            }));
          } catch {}
        }
      }catch(err){
        if (alive) {
          try {
            const cached = JSON.parse(localStorage.getItem(CAS_RANKING_CACHE_KEY) || 'null');
            if (cached && Array.isArray(cached.items)) {
              setRanking(cached.items.filter(Boolean));
              setOrganizers(Array.isArray(cached.organizers) ? cached.organizers.filter(Boolean) : []);
              setMaxPoints(Number.isFinite(Number(cached.maxPoints)) ? Number(cached.maxPoints) : RANK_TOTAL_POINTS);
              setMaxPhotos(Number.isFinite(Number(cached.maxPhotos)) ? Number(cached.maxPhotos) : RANK_TOTAL_PHOTOS);
              setError('');
              return;
            }
          } catch {}
          setError(err.message || 'No se pudo cargar el ranking');
        }
      }finally{
        if (alive) setLoading(false);
      }
    };
    loadRanking();
    const id = setInterval(loadRanking, 5000);
    return ()=>{ alive = false; clearInterval(id); };
  },[]);

  const safeRanking = Array.isArray(ranking) ? ranking.filter(Boolean) : [];
  const safeOrganizers = Array.isArray(organizers) ? organizers.filter(Boolean) : [];
  const displayRanking = [...safeRanking, ...safeOrganizers];
  const visibleMaxPoints = Number.isFinite(Number(maxPoints)) ? Number(maxPoints) : RANK_TOTAL_POINTS;
  const visibleMaxPhotos = Number.isFinite(Number(maxPhotos)) ? Number(maxPhotos) : RANK_TOTAL_PHOTOS;

  return (
    <section id="ranking" style={{padding:'100px 48px',background:'#15110d',borderTop:'1px solid var(--cas-border)',position:'relative'}}>
      <div className="cas-grain"/>
      <div style={{maxWidth:1100,margin:'0 auto',position:'relative'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',flexWrap:'wrap',gap:20,marginBottom:40}}>
          <SectionHeader kicker="04 · EN DIRECTO" title="RANKING EN DIRECTO"/>
          <div style={{display:'flex',alignItems:'center',gap:10,fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)'}}>
            <span className="cas-pulse" style={{width:10,height:10,borderRadius:'50%',background:'var(--cas-orange)'}}/>
            ACTUALIZA CADA 5 SEGUNDOS · AMARILLO = ENVIADA / REVISIÓN · NARANJA = VALIDADA · ROJO = RECHAZADA · BARRA HASTA {visibleMaxPoints} PUNTOS · {visibleMaxPhotos} FOTOS
          </div>
        </div>

        {loading ? (
          <div style={{padding:'60px 30px',border:'1px dashed var(--cas-border)',textAlign:'center',background:'rgba(0,0,0,.3)'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:32,color:'var(--cas-bone-dim)',letterSpacing:'.1em'}}>CARGANDO RANKING</div>
          </div>
        ) : error ? (
          <div style={{padding:'60px 30px',border:'1px dashed var(--cas-border)',textAlign:'center',background:'rgba(0,0,0,.3)'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:32,color:'var(--cas-bone-dim)',letterSpacing:'.1em'}}>RANKING NO DISPONIBLE</div>
            <div style={{fontFamily:'var(--cas-hand)',fontSize:24,color:'var(--cas-orange)',marginTop:8}}>reintentando en unos segundos</div>
          </div>
        ) : displayRanking.length===0 ? (
          <div style={{padding:'60px 30px',border:'1px dashed var(--cas-border)',textAlign:'center',background:'rgba(0,0,0,.3)'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:32,color:'var(--cas-bone-dim)',letterSpacing:'.1em'}}>AÚN NO HAY PILOTOS REGISTRADOS</div>
            <div style={{fontFamily:'var(--cas-hand)',fontSize:24,color:'var(--cas-orange)',marginTop:8}}>en cuanto se inscriban, aparecerán aquí ↓</div>
          </div>
        ) : (
          <div>
            {displayRanking.length > 0 && (
              <div style={{background:'#0a0806',border:'1px solid var(--cas-border)'}}>
                <div className="cas-rank-head" style={{gap:0,padding:'14px 20px',borderBottom:'1px solid var(--cas-border)',background:'rgba(217,116,53,.05)',fontFamily:'var(--cas-stencil)',fontSize:10,letterSpacing:'.3em',color:'var(--cas-bone-dim)',textTransform:'uppercase'}}>
                  <div>POS</div>
                  <div>PILOTO</div>
                  <div>PROGRESO</div>
                  <div style={{textAlign:'right'}}>RESUMEN</div>
                </div>
                {displayRanking.map((r,i)=>{
                  const isOrganizer = !!r.organizer;
  const score = Number(r.puntos ?? 0);
                  const submittedCount = Number.isFinite(Number(r.fotos_subidas))
                    ? Number(r.fotos_subidas)
                    : (r.slots || []).reduce((total, slot) => total + (Number(slot.photos ?? 0) || ((slot.state || (slot.done ? 'aprobado' : 'empty')) !== 'empty' && (slot.state || (slot.done ? 'aprobado' : 'empty')) !== 'rechazado' ? 1 : 0)), 0);
                  const summaryText = `${score} puntos - ${submittedCount}/${visibleMaxPhotos} fotos`;
                  return (
                    <div key={r.codigo || r.puesto || i} className={`cas-rank-row ${isOrganizer ? 'cas-organizer' : ''} ${state.me?.codigo===r.codigo?'cas-mine':''}`} style={{
                      borderBottom:i<displayRanking.length-1?'1px solid rgba(216,200,170,.06)':'none',
                      alignItems:'center',
                      padding:'16px 20px',
                      background:isOrganizer?'rgba(240,201,77,.04)':'transparent',
                    }}>
                      <div className="cas-rank-topline">
                        <div className="cas-rank-pos" style={{fontFamily:'var(--cas-display)',fontSize:24,color:isOrganizer?'#f0c94d':i<3?'var(--cas-orange)':'var(--cas-bone-dim)'}}>
                          {isOrganizer ? '—' : (r.puesto || i+1)}
                        </div>
                        <div className="cas-rank-name" style={{fontFamily:'var(--cas-display)',fontSize:18,color:'var(--cas-bone)',letterSpacing:'.05em',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                          {r.piloto} {isOrganizer && <span style={{fontFamily:'var(--cas-stencil)',fontSize:10,color:'#f0c94d',marginLeft:8,letterSpacing:'.18em',textTransform:'uppercase'}}>Fuera del ranking</span>} {state.me?.codigo===r.codigo && <span style={{fontFamily:'var(--cas-hand)',fontSize:18,color:'var(--cas-orange)',marginLeft:6}}>· tú</span>}
                        </div>
                        <div className="cas-rank-points" style={{textAlign:'right',fontFamily:'var(--cas-display)',fontSize:18,color:'var(--cas-orange)',fontVariantNumeric:'tabular-nums',whiteSpace:'nowrap'}}>
                          {summaryText}
                        </div>
                      </div>
                      <div className="cas-rank-bottomline">
                        <div className="cas-rank-bar">
                          {(r.slots || RANK_SLOTS.map(s => ({id:s.id, label:s.label, bonus:!!(s.isBonus || s.bonus), extra:!!(s.isExtra || s.extra), state:s.state || 'empty', done:false, points:s.points}))).map(slot => {
                            const slotState = slot.state || (slot.done ? 'aprobado' : 'empty');
                            const points = Number(slot.points || 1);
                            const chipPalette = getRankChipStyle(slotState, slot);
                            return (
                              <div
                                key={slot.id}
                                className={`cas-rank-segment ${slotState}${slot.bonus ? ' bonus' : ''}${slot.extra ? ' extra' : ''}`}
                                title={`${slot.label} · ${slotState}`}
                                aria-label={`${slot.label} · ${slotState}`}
                                style={{
                                  flex: `${points} 1 0`,
                                  minWidth: slot.bonus ? 42 : 34,
                                  height: 28,
                                  padding: '0 12px',
                                  borderRadius: 999,
                                  border: `1px solid ${chipPalette.border}`,
                                  background: chipPalette.bg,
                                  color: chipPalette.color,
                                  display:'inline-flex',
                                  alignItems:'center',
                                  justifyContent:'center',
                                  fontFamily:'var(--cas-stencil)',
                                  fontSize:11,
                                  letterSpacing:'.15em',
                                  textTransform:'uppercase',
                                }}
                              >
                                {slot.bonus ? '★' : ''}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
}

// ── PRIZES ────────────────────────────────────────────────────
function PrizesSection(){
  const prizes = [{p:'1º'},{p:'2º'},{p:'3º'}];
  return (
    <section id="premios" style={{padding:'100px 48px',background:'#0d0a08'}}>
      <div style={{maxWidth:1200,margin:'0 auto'}}>
        <SectionHeader kicker="06 · RECOMPENSA" title="PREMIOS · 3 PRIMEROS"/>
        <div className="cas-grid-3" style={{maxWidth:980,margin:'60px auto 0'}}>
          {prizes.map((p,i)=>(
            <div key={i} style={{
              padding:'56px 24px 56px',background:i===0?'linear-gradient(180deg,#1a1207 0%,#0a0806 100%)':'var(--cas-card)',
              border:`1px solid ${i===0?'rgba(217,116,53,.45)':'var(--cas-border)'}`,position:'relative',textAlign:'center',
            }}>
              {i===0 && <div style={{position:'absolute',top:-1,left:-1,right:-1,height:3,background:'var(--cas-orange)'}}/>}
              <div style={{fontFamily:'var(--cas-display)',fontSize:96,color:i===0?'var(--cas-orange)':'var(--cas-bone-dim)',lineHeight:1}}>{p.p}</div>
              <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.4em',color:'var(--cas-bone-dim)',marginTop:24}}>SECRETO</div>
              <div style={{fontFamily:'var(--cas-hand)',fontSize:22,color:'var(--cas-orange)',marginTop:8,transform:'rotate(-1.5deg)'}}>se revela más adelante</div>
            </div>
          ))}
        </div>
        <div style={{textAlign:'center',marginTop:30,fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)'}}>
          ENTREGA · FECHA POR ANUNCIAR · EN <a href="https://www.feelitmotorcycles.com/nosotros-es/" target="_blank" rel="noopener" style={{color:'var(--cas-orange)',textDecoration:'none',borderBottom:'1px solid var(--cas-orange)'}}>FEEL IT MOTORCYCLES</a>
        </div>
      </div>
    </section>
  );
}

// ── REGISTRATION + UPLOAD ────────────────────────────────────
function RegistrationSection(){
  const {state, setState, openLegal} = React.useContext(StateCtx);
  const me = state.me && state.me.codigo ? state.me : null;
  const [form,setForm] = React.useState({nombre:'',telefono:'',acepta:false});
  const [sending,setSending] = React.useState(false);
  const [regErr,setRegErr] = React.useState('');
  const [pistaId, setPistaId] = React.useState(CLUES[0].id);
  const [pointGroup, setPointGroup] = React.useState('main');
  const [extraId, setExtraId] = React.useState(EXTRA_POINTS[0].id);
  const [codigo, setCodigo] = React.useState(me?.codigo || '');
  const [file, setFile] = React.useState(null);
  const [preview, setPreview] = React.useState('');
  const [uploading, setUploading] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [uploadErr, setUploadErr] = React.useState('');
  const uploadRef = React.useRef(null);

  React.useEffect(()=>{
    if (me?.codigo) {
      setCodigo(me.codigo);
    } else {
      setCodigo('');
    }
  }, [me]);

  const submitRegistration = async (e)=>{
    e.preventDefault();
    setRegErr('');
    if(!form.nombre.trim()) return setRegErr('Necesitamos un nombre, aunque sea un alias.');
    if(!/^[\d +().-]{6,}$/.test(form.telefono)) return setRegErr('Teléfono con pinta rara.');
    if(!form.acepta) return setRegErr('Tienes que aceptar las bases.');
    setSending(true);
    try{
      const body = new URLSearchParams({
        nombre: form.nombre.trim(),
        telefono: form.telefono.trim(),
      });
      const res = await fetch(CAS_REGISTER_API, {
        method:'POST',
        headers:{ Accept:'application/json' },
        body,
      });
      const data = await res.json().catch(()=>null);
      if(!res.ok || !data?.ok || !data?.participant){
        throw new Error(data?.error || 'No se pudo registrar');
      }
      setState({ me: data.participant });
      setForm(f=>({...f,acepta:false}));
    }catch(err){
      setRegErr(err.message || 'No se pudo registrar');
    }finally{
      setSending(false);
    }
  };

  const onFile = (e)=>{
    const f = e.target.files?.[0];
    if(!f) return;
    setFile(f);
    const r = new FileReader();
    r.onload = ()=>setPreview(r.result);
    r.readAsDataURL(f);
  };

  const submitUpload = async (e)=>{
    e.preventDefault();
    setUploadErr('');
    if(!/^\d{4}$/.test(codigo)){ setUploadErr('Tu código son 4 dígitos.'); return; }
    if(!file){ setUploadErr('Sube una foto con la pegatina.'); return; }
    setUploading(true);
    try{
      const selectedPointId = pointGroup === 'extra' ? extraId : pistaId;
      const formData = new FormData();
      formData.append('codigo', codigo);
      formData.append('pista', selectedPointId);
      formData.append('foto', file);
      const res = await fetch(CAS_UPLOAD_API, {
        method:'POST',
        headers:{ Accept:'application/json' },
        body: formData,
      });
      const data = await res.json().catch(()=>null);
      if(!res.ok || !data?.ok){
        throw new Error(data?.error || 'No se pudo subir la foto');
      }
      setDone(true);
      setFile(null);
      setPreview('');
      if (uploadRef.current) uploadRef.current.value = '';
      setTimeout(()=>setDone(false), 4000);
    }catch(err){
      setUploadErr(err.message || 'No se pudo subir la foto.');
    }finally{
      setUploading(false);
    }
  };

  return (
    <section id="inscripcion" style={{
      padding:'100px 48px',
      backgroundImage:`radial-gradient(circle at 20% 30%,rgba(217,116,53,.06),transparent 50%),radial-gradient(circle at 85% 75%,rgba(217,116,53,.04),transparent 45%),linear-gradient(180deg,#15110d 0%,#0d0a08 100%)`,
      borderTop:'1px solid var(--cas-border)',position:'relative',overflow:'hidden',
    }}>
      <div style={{position:'absolute',inset:0,pointerEvents:'none',opacity:.25,backgroundImage:'repeating-linear-gradient(45deg,rgba(216,200,170,.04) 0 2px,transparent 2px 16px)'}}/>
      <div className="cas-grain"/>
      <div className="cas-reg-grid" style={{maxWidth:1200,margin:'0 auto',position:'relative'}}>
        <div>
          <div className="cas-stamp" style={{marginBottom:16}}>Paso 03</div>
          <h2 className="cas-reg-title" style={{fontFamily:'var(--cas-display)',lineHeight:.92,margin:0,color:'var(--cas-bone)'}}>SUBE TU FOTO</h2>
          <div className="cas-reg-sub" style={{fontFamily:'var(--cas-hand)',color:'var(--cas-orange)',transform:'rotate(-2deg)',display:'inline-block',marginTop:4}}>inscríbete primero.</div>
          <p style={{fontFamily:'var(--cas-body)',fontSize:15,lineHeight:1.6,color:'var(--cas-bone-dim)',marginTop:24,maxWidth:440}}>
            Te registras, recibes tu código y en esta misma zona subes la foto de cada punto.
            Todo queda más limpio y más rápido.
          </p>
          <div style={{marginTop:32,display:'flex',flexDirection:'column',gap:12,fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',textTransform:'uppercase'}}>
            <div>✓ CÓDIGO ÚNICO</div>
            <div>✓ SUBIDA DE FOTOS</div>
            <div>✓ TODO EN LA MISMA PÁGINA</div>
          </div>
        </div>

        <div style={{display:'grid',gap:20}}>
          <form id="ficha-piloto" onSubmit={submitRegistration} className="cas-card-panel" style={{padding:'36px 32px',background:'rgba(10,8,6,.88)'}}>
            {!me ? (
              <>
                <div style={{fontFamily:'var(--cas-display)',fontSize:26,letterSpacing:'.1em',color:'var(--cas-bone)',marginBottom:24}}>FICHA DEL PILOTO</div>
                <div style={{marginBottom:18}}>
                  <label className="cas-label">Nombre · o alias</label>
                  <input className="cas-input" placeholder="Cómo te llamamos" value={form.nombre} onChange={e=>setForm(f=>({...f,nombre:e.target.value}))}/>
                </div>
                <div style={{marginBottom:22}}>
                  <label className="cas-label">Teléfono</label>
                  <input className="cas-input" placeholder="+34 6xx xxx xxx" type="tel" value={form.telefono} onChange={e=>setForm(f=>({...f,telefono:e.target.value}))}/>
                </div>
                <label style={{display:'flex',alignItems:'flex-start',gap:10,cursor:'pointer',marginBottom:22,fontFamily:'var(--cas-body)',fontSize:12,color:'var(--cas-bone-dim)',lineHeight:1.5}}>
                  <input type="checkbox" checked={form.acepta} onChange={e=>setForm(f=>({...f,acepta:e.target.checked}))} style={{marginTop:2,accentColor:'var(--cas-orange)'}}/>
                  <span>Acepto las <button type="button" onClick={openLegal} style={{background:'none',border:'none',color:'var(--cas-orange)',textDecoration:'underline',cursor:'pointer',padding:0,font:'inherit'}}>bases legales</button> y participar bajo mi propia responsabilidad.</span>
                </label>
                {regErr && <div style={{color:'#ff7a6b',fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.2em',marginBottom:16}}>▲ {regErr}</div>}
                <button type="submit" className="cas-btn-primary" disabled={sending} style={{width:'100%',justifyContent:'center'}}>
                  {sending?'REGISTRANDO CÓDIGO...':'APÚNTAME →'}
                </button>
              </>
            ) : (
              <div style={{textAlign:'center',padding:'20px 10px'}}>
                <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.4em',color:'var(--cas-bone-dim)',marginBottom:12}}>TU CÓDIGO</div>
                <div className="cas-code-num" style={{fontFamily:'var(--cas-display)',lineHeight:1,color:'var(--cas-orange)',letterSpacing:'.06em'}}>{me.codigo}</div>
                <div style={{fontFamily:'var(--cas-display)',fontSize:24,color:'var(--cas-bone)',letterSpacing:'.1em',marginTop:14}}>{me.nombre}</div>
                <div style={{fontFamily:'var(--cas-hand)',fontSize:22,color:'var(--cas-orange)',marginTop:14}}>guárdalo bien · lo necesitas para subir fotos</div>
                <div style={{marginTop:18}}>
                  <button type="button" onClick={()=>{ if(confirm('¿Salir y borrar tus datos de este dispositivo?')) { setState({ me:null }); setForm({nombre:'',telefono:'',acepta:false}); setCodigo(''); setFile(null); setPreview(''); if (uploadRef.current) uploadRef.current.value=''; } }} style={{background:'none',border:'none',color:'var(--cas-bone-dim)',fontFamily:'var(--cas-stencil)',fontSize:10,letterSpacing:'.3em',cursor:'pointer'}}>↺ CAMBIAR PILOTO</button>
                </div>
              </div>
            )}
          </form>

          <form id="subir" onSubmit={submitUpload} className="cas-card-panel" style={{padding:'32px 28px',background:'rgba(10,8,6,.88)',scrollMarginTop:'18px'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:26,letterSpacing:'.1em',color:'var(--cas-bone)',marginBottom:24}}>SUBIR FOTO</div>
            <div style={{marginBottom:18}}>
              <label className="cas-label">Tu código · 4 dígitos</label>
              <input
                className="cas-input"
                inputMode="numeric"
                pattern="[0-9]*"
                maxLength={4}
                placeholder="••••"
                value={codigo}
                onChange={e=>setCodigo(e.target.value.replace(/\D/g,'').slice(0,4))}
                style={{letterSpacing:'.4em',fontFamily:'var(--cas-display)',fontSize:22,textAlign:'center'}}
              />
            </div>
            <div style={{marginBottom:18}}>
              <label className="cas-label">Tipo de foto</label>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                <button
                  type="button"
                  onClick={()=>setPointGroup('main')}
                  style={{
                    border:'1px solid ' + (pointGroup === 'main' ? 'var(--cas-orange)' : 'var(--cas-border)'),
                    background: pointGroup === 'main' ? 'rgba(217,116,53,.12)' : 'rgba(0,0,0,.25)',
                    color:'var(--cas-bone)',
                    fontFamily:'var(--cas-stencil)',
                    fontSize:10,
                    letterSpacing:'.25em',
                    textTransform:'uppercase',
                    padding:'12px 10px',
                    cursor:'pointer',
                  }}
                >
                  Pistas y bonus
                </button>
                <button
                  type="button"
                  onClick={()=>setPointGroup('extra')}
                  style={{
                    border:'1px solid ' + (pointGroup === 'extra' ? 'var(--cas-orange)' : 'var(--cas-border)'),
                    background: pointGroup === 'extra' ? 'rgba(217,116,53,.12)' : 'rgba(0,0,0,.25)',
                    color:'var(--cas-bone)',
                    fontFamily:'var(--cas-stencil)',
                    fontSize:10,
                    letterSpacing:'.25em',
                    textTransform:'uppercase',
                    padding:'12px 10px',
                    cursor:'pointer',
                  }}
                >
                  Puntos extra
                </button>
              </div>
              <div style={{marginTop:8,fontFamily:'var(--cas-stencil)',fontSize:9,letterSpacing:'.2em',color:'var(--cas-bone-dim)'}}>LOS EXTRAS SE SUBEN DE UNO EN UNO</div>
            </div>
            {pointGroup === 'main' ? (
              <div style={{marginBottom:18}}>
                <label className="cas-label">Punto que has encontrado</label>
                <select className="cas-select" value={pistaId} onChange={e=>setPistaId(e.target.value)}>
                  {CLUES.map(c=>(<option key={c.id} value={c.id} style={{background:'#0d0a08'}}>{c.n}</option>))}
                </select>
              </div>
            ) : (
              <div style={{marginBottom:18}}>
                <label className="cas-label">Punto extra · 36 cascos</label>
                <select className="cas-select" value={extraId} onChange={e=>setExtraId(e.target.value)}>
                  {EXTRA_POINTS.map(c=>(<option key={c.id} value={c.id} style={{background:'#0d0a08'}}>{c.n}</option>))}
                </select>
              </div>
            )}
            <div style={{marginBottom:18}}>
              <label className="cas-label">Foto con la pegatina</label>
              <label htmlFor="cas-upload" style={{
                display:'block',cursor:'pointer',padding:preview?0:'24px 16px',
                border:'1px dashed rgba(216,200,170,.35)',background:'rgba(0,0,0,.3)',
                textAlign:'center',position:'relative',minHeight:preview?0:120,
              }}>
                {preview ? (
                  <img src={preview} alt="preview" style={{display:'block',width:'100%',maxHeight:280,objectFit:'cover'}}/>
                ) : (
                  <>
                    <div style={{fontFamily:'var(--cas-display)',fontSize:32,color:'var(--cas-orange)'}}>＋</div>
                    <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',marginTop:8}}>SELECCIONAR FOTO O ARCHIVO</div>
                  </>
                )}
              </label>
              <input ref={uploadRef} id="cas-upload" type="file" accept="image/*,.jpg,.jpeg,.png,.webp,.gif" onChange={onFile} style={{display:'none'}}/>
            </div>
            {uploadErr && <div style={{color:'#ff7a6b',fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.2em',marginBottom:14}}>▲ {uploadErr}</div>}
            {done && <div style={{color:'var(--cas-orange)',fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.2em',marginBottom:14}}>✓ FOTO ENVIADA</div>}
            <button type="submit" className="cas-btn-primary" disabled={uploading} style={{width:'100%',justifyContent:'center'}}>
              {uploading?'SUBIENDO...':'ENVIAR FOTO →'}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}

// ── LEGAL MODAL ───────────────────────────────────────────────
function LegalModal({onClose}){
  React.useEffect(()=>{
    const onKey=(e)=>{if(e.key==='Escape')onClose()};
    window.addEventListener('keydown',onKey);
    document.body.style.overflow='hidden';
    return()=>{window.removeEventListener('keydown',onKey);document.body.style.overflow=''};
  },[onClose]);
  return (
    <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(5,3,2,.92)',zIndex:9000,display:'flex',alignItems:'center',justifyContent:'center',padding:30}}>
      <div onClick={e=>e.stopPropagation()} style={{maxWidth:760,width:'100%',maxHeight:'88vh',overflowY:'auto',background:'#0d0a08',border:'1px solid var(--cas-border)',padding:'40px 48px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:24}}>
          <div>
            <div style={{fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.45em',color:'var(--cas-orange)'}}>📝 BASES LEGALES</div>
            <h2 style={{fontFamily:'var(--cas-display)',fontSize:42,margin:'8px 0 0',color:'var(--cas-bone)',letterSpacing:'.02em'}}>LA PRUEBA · CASCOTERAPIA</h2>
          </div>
          <button onClick={onClose} style={{width:40,height:40,borderRadius:'50%',background:'rgba(0,0,0,.4)',border:'1px solid var(--cas-border)',color:'var(--cas-bone)',fontSize:22,cursor:'pointer'}}>×</button>
        </div>
        <div style={{fontFamily:'var(--cas-body)',fontSize:14,lineHeight:1.7,color:'var(--cas-bone-dim)'}}>
          <LegalItem n="1" t="ORGANIZADOR">Cascoterapia · grupo privado de aficionados al motociclismo, sin personalidad jurídica y sin ánimo de lucro. Actividad lúdica, social y recreativa.</LegalItem>
          <LegalItem n="2" t="OBJETO">Búsqueda de pegatinas en distintos puntos geográficos dentro del plazo establecido.</LegalItem>
          <LegalItem n="3" t="PARTICIPACIÓN">Voluntaria, gratuita y abierta. El participante declara ser mayor de edad (o contar con autorización), participar bajo su propia responsabilidad y aceptar estas bases.</LegalItem>
          <LegalItem n="4" t="NATURALEZA">No es competición deportiva oficial, ni federativa, ni comercial. Es una dinámica recreativa entre particulares.</LegalItem>
          <LegalItem n="5" t="PREMIOS">Carácter simbólico y no comercial (merch / obsequios). La organización puede modificar premios, ajustar el número de ganadores o introducir categorías.</LegalItem>
          <LegalItem n="6" t="PROTECCIÓN DE DATOS">Cascoterapia almacena en el servidor los datos de inscripción (nombre, teléfono y código) y las fotos subidas para gestionar la participación, la validación y el ranking. No se publica el teléfono ni el código en abierto y el contenido compartido (imágenes) es responsabilidad del participante.</LegalItem>
          <LegalItem n="7" t="RESPONSABILIDAD">Cada participante es responsable de su seguridad, del cumplimiento del código de circulación y del uso adecuado del vehículo. Cascoterapia queda exenta de responsabilidad por accidentes, sanciones o daños.</LegalItem>
          <LegalItem n="8" t="CONDUCTA">Comportamiento respetuoso, no poner en riesgo a terceros, respetar espacios públicos y privados. La organización podrá excluir incumplimientos.</LegalItem>
          <LegalItem n="9" t="ACEPTACIÓN">Participar implica la aceptación íntegra de estas bases.</LegalItem>
          <LegalItem n="10" t="MODIFICACIONES">La organización se reserva el derecho de modificar las bases o cancelar la actividad si las circunstancias lo requieren.</LegalItem>
          <div style={{marginTop:30,padding:'22px 24px',border:'1px solid var(--cas-orange)',background:'rgba(217,116,53,.06)'}}>
            <div style={{fontFamily:'var(--cas-display)',fontSize:18,color:'var(--cas-orange)',letterSpacing:'.15em',marginBottom:6}}>🐌 NOTA FINAL</div>
            <div style={{color:'var(--cas-bone)',fontFamily:'var(--cas-body)',fontSize:14,lineHeight:1.6}}>
              Cascoterapia es, ante todo, un grupo de amigos. Este evento nace para compartir rutas, desconectar y disfrutar del camino.
              <br/><strong style={{color:'var(--cas-orange)'}}>Sin presión. Sin excusas. Solo ruta.</strong>
            </div>
          </div>
          <div style={{marginTop:24,textAlign:'center'}}>
            <a href="/assets/bases-legales.pdf" target="_blank" rel="noopener" className="cas-btn-ghost">↓ DESCARGAR PDF</a>
          </div>
        </div>
      </div>
    </div>
  );
}
function LegalItem({n,t,children}){
  return (
    <div style={{marginBottom:18,paddingBottom:18,borderBottom:'1px solid var(--cas-border)'}}>
      <div style={{fontFamily:'var(--cas-display)',fontSize:18,color:'var(--cas-bone)',letterSpacing:'.1em',marginBottom:6}}>
        <span style={{color:'var(--cas-orange)'}}>{n}.</span> {t}
      </div>
      <div>{children}</div>
    </div>
  );
}

// ── FOOTER ────────────────────────────────────────────────────
function FooterSection(){
  const {openLegal} = React.useContext(StateCtx);
  return (
    <footer style={{padding:'60px 48px 40px',background:'#0a0806',borderTop:'1px solid var(--cas-border)'}}>
      <div style={{maxWidth:1200,margin:'0 auto',display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:24}}>
        <div style={{display:'flex',alignItems:'center',gap:14,color:'var(--cas-bone)'}}>
          <div style={{width:44,height:44}}><LogoSvg/></div>
          <div>
            <div style={{fontFamily:'var(--cas-display)',fontSize:22,letterSpacing:'.2em'}}>CASCOTERAPIA</div>
            <div style={{fontFamily:'var(--cas-stencil)',fontSize:10,letterSpacing:'.35em',color:'var(--cas-bone-dim)',marginTop:2}}>SOLO RUTA · DESDE 2026</div>
          </div>
        </div>
        <div style={{display:'flex',gap:28,fontFamily:'var(--cas-stencil)',fontSize:11,letterSpacing:'.3em',color:'var(--cas-bone-dim)',textTransform:'uppercase',flexWrap:'wrap'}}>
          <a href="mailto:hola@cascoterapia.com" style={linkStyle}>HOLA@CASCOTERAPIA.COM</a>
          <a href="https://www.instagram.com/casco.terapia/" target="_blank" rel="noopener" style={linkStyle}>@CASCO.TERAPIA</a>
          <a href="/encuesta.php" style={linkStyle}>ENCUESTA</a>
          <a href="/admin/login.php" style={linkStyle}>ADMIN</a>
          <button onClick={openLegal} style={{background:'none',border:'none',color:'inherit',font:'inherit',letterSpacing:'inherit',textTransform:'inherit',cursor:'pointer'}}>BASES LEGALES</button>
        </div>
      </div>
    </footer>
  );
}

window.VariantPoster = VariantPoster;
