// === Escena 04 — "Te equivocas de coche. Se corrige solo." (CLÍMAX) ===
// EL EJEMPLO (idea de Angel): das de alta un coche como Honda Civic, sus piezas cogen los datos
// del Civic. Caes en el error: era un Renault Clío. Corriges el COCHE una vez. Y como cada pieza
// bebe del coche (versión [ExisteRelacion]), la corrección BAJA como una onda: cada pieza cambia
// su versión, suelta su ficha vieja y se engancha a la del Renault; las referencias Honda → Renault.
// Solo si el coche tiene la identificación automática. Cae aquí La Única Cosa (prueba, 2/3).
function EscenaRD04({ t }){
  const T = {
    coche:4.5,      // "lo pones como Honda Civic" → coche + piezas con datos Civic
    error:16.3,      // "Era un Renault Clío" → flag de error
    corrige:22.6,    // "Cambias el coche a Renault" → editas la versión del coche
    cascada:27.1,   // "la corrección baja sola" → onda desde el coche
    condicion:40.9, // "la identificación automática puesta" → chip de condición
    unica:44.9,     // "se corrige solo" → La Única Cosa (prueba)
    puente:47.3,    // "querrás llevarla tú" → puente
  };
  const pr = (s,d)=> clamp((t-s)/d, 0, 1);

  // ---- Coche (arriba-centro): versión Honda Civic → Renault Clío ----
  const CAR = { x:600, y:150, w:720, h:210 };
  const cocheP = pr(T.coche,0.8), cocheE = Easing.easeOutCubic(cocheP);
  const errP = pr(T.error,0.5), errE = Easing.easeOutBack(errP);
  const corrP = pr(T.corrige,0.5), corrE = Easing.easeOutBack(corrP);
  const corregido = t >= T.corrige;   // el coche ya es Renault

  // ---- Grid de 10 piezas (5×2) ----
  const IDS = Array.from({length:10}, (_,i)=> '#'+(1010+i*4));
  const NX=5, CW=320, CH=168, CGX=24, CGY=22;
  const gridW = NX*CW+(NX-1)*CGX;         // 1696
  const gx0 = (1920-gridW)/2;             // 112
  const gy0 = 560;
  const cardPos = (i)=>({ x: gx0+(i%NX)*(CW+CGX), y: gy0+Math.floor(i/NX)*(CH+CGY) });

  // ---- Onda de corrección desde el coche ----
  const ORIG = { x:960, y:392 };
  const WAVE_SPEED = 150;                  // px/s — lenta: acompaña a la narración
  const waveR = (t-T.cascada)*WAVE_SPEED;
  const distOf = (i)=>{ const c=cardPos(i); return Math.hypot(c.x+CW/2-ORIG.x, c.y+CH/2-ORIG.y); };
  const fixAt = (i)=> T.cascada + distOf(i)/WAVE_SPEED;   // instante en que la onda corrige la pieza i
  const fixedCount = IDS.filter((_,i)=> t >= fixAt(i)).length;
  const allFixed = fixedCount >= 10;
  const working = t >= T.cascada && !allFixed;
  const pulse = working ? 0.5+0.5*Math.sin((t-T.cascada)*7) : 0;

  const condP = pr(T.condicion,0.6), condE = Easing.easeOutCubic(condP);
  const uniP = pr(T.unica,0.7), uniE = Easing.easeOutBack(uniP);

  return (
    <SlideCanvas variant="light-soft">
      <DemoHeader t={t} eyebrow="DESGUACES · TE EQUIVOCAS, SE CORRIGE"
        title={<span>Coche mal asignado. <span className="grad-text">Corrige el coche, no las piezas.</span></span>}/>

      {/* ===== Indicador de actividad ===== */}
      {t >= T.cascada && (
        <div style={{position:'absolute', right:96, top:150, display:'inline-flex', alignItems:'center', gap:10,
          background:'#fff', border:`1px solid ${allFixed?'rgba(16,185,129,0.4)':'rgba(0,133,255,0.35)'}`, borderRadius:100,
          padding:'9px 18px', boxShadow:'0 8px 22px rgba(15,23,42,0.06)'}}>
          <span style={{width:9, height:9, borderRadius:100, background: allFixed?'#10B981':'#0085FF',
            opacity: allFixed?1:0.4+0.6*pulse, boxShadow: allFixed?'0 0 0 3px rgba(16,185,129,0.2)':'none'}}/>
          <span className="f-mono" style={{fontSize:13, fontWeight:800, color: allFixed?'#059669':'#0085FF'}}>
            {allFixed ? `${fixedCount}/10 CORREGIDAS` : 'CORRIGIENDO…'}</span>
        </div>
      )}

      {/* ===== El coche ===== */}
      {cocheP > 0 && (
        <div style={{position:'absolute', left:CAR.x, top:CAR.y, width:CAR.w,
          background:'#fff', borderRadius:20, border:`2px solid ${corregido?'rgba(16,185,129,0.5)':errP>0?'#FB8C00':'#E2E8F0'}`,
          boxShadow: corregido?'0 26px 60px rgba(16,185,129,0.14)':'0 26px 60px rgba(15,23,42,0.10)',
          padding:'20px 26px', opacity:clamp(cocheP*1.3,0,1), transform:`translateY(${(1-cocheE)*24}px)`, zIndex:8}}>
          <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div className="f-mono" style={{fontSize:10, fontWeight:700, letterSpacing:'2.5px', color:'#94A3B8'}}>COCHE · VEHÍCULO DE ORIGEN</div>
            <span className="f-mono" style={{fontSize:12, fontWeight:700, color:'#94A3B8'}}>#V-2291</span>
          </div>
          {/* Versión del coche */}
          <div style={{marginTop:12, display:'flex', alignItems:'center', gap:14}}>
            <span className="f-mono" style={{fontSize:11, fontWeight:700, letterSpacing:'1.5px', color:'#94A3B8'}}>VERSIÓN</span>
            {/* valor viejo (Honda Civic) — tachado al corregir */}
            {!corregido && (
              <span className="f-plex" style={{fontSize:26, fontWeight:800,
                color: errP>0?'#B45309':'#0F172A',
                background: errP>0?'rgba(251,140,0,0.10)':'transparent', borderRadius:8, padding:'2px 10px',
                textDecoration: corrP>0?'line-through':'none'}}>Honda Civic</span>
            )}
            {/* valor nuevo (Renault Clío) — al corregir */}
            {corregido && (
              <span className="f-plex" style={{fontSize:26, fontWeight:800, color:'#059669',
                background:'rgba(16,185,129,0.10)', borderRadius:8, padding:'2px 10px',
                transform:`scale(${lerp(0.7,1,corrE)})`, opacity:clamp(corrP*1.4,0,1), display:'inline-block'}}>
                <Typewriter text="Renault Clío" start={T.corrige} cps={10} t={t} caret={t<T.corrige+1.4}/>
              </span>
            )}
            {corregido && corrP>0.6 && <span style={{color:'#059669', fontWeight:800, fontSize:22}}>✓</span>}
          </div>
          {/* flag de error */}
          {errP > 0 && !corregido && (
            <div style={{position:'absolute', right:22, bottom:-16, display:'inline-flex', alignItems:'center', gap:8,
              background:'#FFF7ED', border:'2px solid #FB8C00', borderRadius:100, padding:'7px 16px',
              boxShadow:'0 8px 22px rgba(251,140,0,0.25)', transform:`scale(${lerp(0.7,1,errE)})`, opacity:clamp(errP*1.3,0,1)}}>
              <span style={{fontSize:15}}>⚠️</span>
              <span className="f-plex" style={{fontSize:14, fontWeight:700, color:'#B45309'}}>Era un Renault, no un Civic</span>
            </div>
          )}
          {/* chip condición: identificación automática */}
          {condP > 0 && (
            <div style={{position:'absolute', left:22, bottom:-16, display:'inline-flex', alignItems:'center', gap:8,
              background:'#fff', border:'1px solid #E2E8F0', borderRadius:100, padding:'6px 14px',
              boxShadow:'0 6px 16px rgba(15,23,42,0.06)', opacity:condE, transform:`translateY(${(1-condE)*6}px)`}}>
              <span style={{fontSize:13}}>🚗</span>
              <span className="f-mono" style={{fontSize:11, fontWeight:700, color:'#059669'}}>identificación automática: ON</span>
            </div>
          )}
        </div>
      )}

      {/* ===== Onda de corrección (anillos) ===== */}
      {t >= T.cascada && !allFixed && (
        <svg width="1920" height="1080" style={{position:'absolute', inset:0, pointerEvents:'none', zIndex:3}}>
          {[0,0.32].map((off,k)=>{
            const r = waveR - off*WAVE_SPEED;
            if (r<=0) return null;
            const op = clamp(1 - r/1000, 0, 1)*0.45;
            return <circle key={k} cx={ORIG.x} cy={ORIG.y} r={r} fill="none" stroke="#10B981" strokeWidth={k===0?3:2} opacity={op}/>;
          })}
        </svg>
      )}

      {/* ===== Grid de 10 piezas ===== */}
      {IDS.map((id,i)=>{
        const p = pr(T.coche+1.6+i*0.38, 0.5), e = Easing.easeOutCubic(p);   // se pueblan mientras narra "se despieza"
        if (p<=0) return null;
        const c = cardPos(i);
        const flagged = errP>0 && t < fixAt(i);      // dato Civic marcado como erróneo (ámbar)
        const fixed = t >= fixAt(i);                 // ya corregido a Renault (verde)
        const kK = clamp((t-fixAt(i))/0.45, 0, 1);
        const kE = Easing.easeOutBack(kK);
        const borderCol = fixed ? 'rgba(16,185,129,0.5)' : flagged ? 'rgba(251,140,0,0.45)' : '#E2E8F0';

        return (
          <div key={i} style={{position:'absolute', left:c.x, top:c.y, width:CW, height:CH,
            background:'#fff', borderRadius:14, border:`${(fixed||flagged)?2:1}px solid ${borderCol}`,
            boxShadow: fixed?`0 12px 30px rgba(16,185,129,${0.10+0.12*(1-kK)})`
                       : flagged?'0 10px 24px rgba(251,140,0,0.10)':'0 8px 20px rgba(15,23,42,0.05)',
            padding:'14px 16px', opacity:clamp(p*1.3,0,1),
            transform:`translateY(${(1-e)*14}px) scale(${fixed?1+0.05*(1-kK):1})`, zIndex: fixed?5:4}}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12}}>
              <span className="f-plex" style={{fontSize:14, fontWeight:700, color:'#0F172A'}}>Faro del. izq.</span>
              <span className="f-mono" style={{fontSize:11, fontWeight:700, color:'#94A3B8'}}>{id}</span>
            </div>
            {/* versión: Honda Civic (mal) → Renault Clío (bien) */}
            <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:9}}>
              <span className="f-mono" style={{fontSize:9, fontWeight:700, letterSpacing:'1px', color:'#CBD5E1', width:52}}>VERSIÓN</span>
              {fixed
                ? <span className="f-mono" style={{fontSize:13, fontWeight:800, color:'#059669',
                    transform:`scale(${lerp(0.6,1,kE)})`, display:'inline-block'}}>Renault Clío</span>
                : <span className="f-mono" style={{fontSize:13, fontWeight:800, color: flagged?'#B45309':'#334155',
                    textDecoration: flagged?'line-through':'none'}}>Honda Civic</span>}
            </div>
            {/* referencia OEM: Honda → Renault */}
            <div style={{display:'flex', alignItems:'center', gap:8}}>
              <span className="f-mono" style={{fontSize:9, fontWeight:700, letterSpacing:'1px', color:'#CBD5E1', width:52}}>OEM</span>
              {fixed
                ? <span className="f-mono" style={{fontSize:13, fontWeight:800, color:'#059669',
                    background:'rgba(16,185,129,0.10)', border:'1px solid rgba(16,185,129,0.3)', borderRadius:8, padding:'2px 8px',
                    transform:`scale(${lerp(0.6,1,kE)})`, display:'inline-block'}}>260600-96R</span>
                : <span className="f-mono" style={{fontSize:13, fontWeight:800, color: flagged?'#B45309':'#334155',
                    textDecoration: flagged?'line-through':'none'}}>33150-TV0</span>}
            </div>
          </div>
        );
      })}

      {/* ===== La Única Cosa (prueba, 2/3) ===== */}
      {uniP > 0 && (
        <div style={{position:'absolute', left:0, right:0, bottom:34, textAlign:'center',
          opacity:clamp(uniP*1.3,0,1), transform:`translateY(${(1-uniE)*12}px) scale(${lerp(0.96,1,uniE)})`}}>
          <span className="f-plex" style={{fontSize:27, fontWeight:800, letterSpacing:'-0.02em', color:'#0F172A'}}>
            Te equivocas una vez. <span style={{color:'#0085FF'}}>Se corrige solo.</span>
          </span>
        </div>
      )}

      {/* puente */}
      {t >= T.puente && (
        <Caption t={t} start={T.puente} style={{fontSize:22, fontWeight:700, color:'#0F172A', bottom:8}}>
          ¿Y si una pieza quieres llevarla tú? <span style={{color:'#0085FF'}}>→</span>
        </Caption>
      )}
    </SlideCanvas>
  );
}
Object.assign(window, { EscenaRD04 });
