// === Escena 04 — "Las dos vistas" ===  [CLÍMAX]
// La imagen-momento: la fila «Guantes de nitrilo · 88 · 2» se despliega y el 88 se parte en las dos
// líneas que lo formaron —Nave 48 uds, Tienda 40 uds— mientras la flecha se dibuja de abajo arriba.
// La rejilla global lleva <Template> y por eso tiene columna de chevrón (ReposicionSubpage.razor:43-61);
// la de «Por almacén» NO lo lleva (:81-91). ExpandMode.Single: una sola fila abierta a la vez (:43).
// «Pedir» va en el ámbar de producto, pintado con --rz-warning-dark #918908 (var.css:157).
function EscenaRP04({ t }){
  const T = {
    vista:0.1,        // "Vista global" -> se marca la pestaña; el subrayado se dibuja
    titulo:1.9,       // "Necesidad global de compra" -> título de la tarjeta + bajada
    filas:6.8,        // "cuántas pido de cada producto" -> las 3 filas en cascada
    guantes:9.3,      // "Guantes de nitrilo" -> la fila 1 sube a elevación alta; el resto al 0.4
    n88:10.6,         // "ochenta y ocho unidades" -> contador 0 → 88
    calma:15.6,       // "no es un sitio" -> calma: el glow se queda fijo, nada se mueve
    despliega:17.4,   // "Despliega la fila" -> clic en el chevrón; la fila se abre (único overshoot)
    reparto:19.5,     // "Reparto por almacén" -> el panel se despliega vacío, entra su título
    nave:21.0,        // "cuarenta y ocho a la nave" -> EL MOMENTO: el 88 se parte; aterriza «48 uds»
    tienda:22.4,      // "cuarenta a la tienda" -> aterriza «40 uds»; la suma y sus sumandos, juntos
    sumo:26.7,        // "se sumó abajo" -> flecha que se dibuja de abajo hacia arriba
    pestana:29.6,     // "Cambia de pestaña" -> entran las 2 tarjetas de «Por almacén»
    cabeceras:35.7,   // "mínimo, máximo y pedir" -> las 5 cabeceras se encienden en cascada
    pedir:38.4,       // "Pedir va en color" -> la columna «Pedir» en ámbar; las otras 4 al 0.55
    unica1:42.7,      // "Reposición no adivina" -> ÚNICA COSA mitad 1 (prueba)
    unica2:45.1,      // "del techo que pusiste" -> ÚNICA COSA mitad 2
    mide:50.2,        // "Pero mide otra cosa" -> la tabla se encoge hacia arriba-izquierda
    bajadaDelay:0.50,  // retardo de la bajada bajo el título de la tarjeta
    filaStep:0.12,     // cascada de las 3 filas de la rejilla global
    cabeceraStep:0.35, // cascada de las 5 cabeceras de «Por almacén»
    almacenStep:0.15,  // desfase entre las tarjetas Tienda y Nave
  };

  const AZUL = '#1d73e2';    // --rz-primary
  const AMBAR = '#918908';   // --rz-warning-dark (desviación declarada del plan)

  // ── Geometría de la ventana y de la rejilla global ──
  const WX = 210, WY = 190, WW = 1500, CH = 76, BH = 740;
  const CARDX = 240, CARDW = 1440;
  const IX = 266, IW = 1388;              // interior de la tarjeta
  const CARDY = 380;
  const HEADY = 518;                      // cabeceras de la rejilla
  const ROWY = 564;                       // primera fila
  const C = { chev:52, prod:736, unid:320, alm:280 };
  const XUNID = IX + C.chev + C.prod + C.unid;   // 1374 — borde derecho de «Unidades a comprar»
  const XIN = IX + IW;                           // 1654 — borde derecho interior

  // ── Progresos ──
  const vsP = clamp((t-T.vista)/0.4, 0, 1);
  const subW = 238 * Easing.easeOutCubic(clamp((t-T.vista)/0.35, 0, 1));
  const tiP = clamp((t-T.titulo)/0.5, 0, 1), tiE = Easing.easeOutCubic(tiP);
  const baP = clamp((t-T.titulo-T.bajadaDelay)/0.5, 0, 1);

  // La fila 1 se alza y su 88 crece; vuelve a su sitio al desplegarse
  const soloIn = Easing.easeOutCubic(clamp((t-T.n88)/0.6, 0, 1));
  const soloOut = Easing.easeInOutCubic(clamp((t-T.despliega)/0.45, 0, 1));
  const solo = soloIn * (1-soloOut);
  const eleva = clamp((t-T.guantes)/0.5, 0, 1) * (1-clamp((t-T.pestana)/0.4, 0, 1));
  const rowH1 = lerp(68, 132, solo);
  const size88 = lerp(30, 84, solo);
  const n88 = useCountUp(0, 88, T.n88, 1.0, t);
  // Un solo pulse al aterrizar el contador; en T.calma el glow se asienta y ya no se mueve nada.
  const pulse88 = (t >= T.n88 && t < T.n88+1.2) ? Math.sin((t-T.n88)/1.2*Math.PI) : 0;
  const glow88 = t < T.n88 ? 0 : (0.40 + pulse88*0.45) * lerp(1, 0.70, clamp((t-T.calma)/0.5, 0, 1));

  // El panel de reparto
  const panelE = Easing.easeOutBack(clamp((t-T.despliega)/0.55, 0, 1));
  const panelH = (t < T.despliega ? 0 : 200 * panelE);
  const PANY = ROWY + rowH1;
  const repP = clamp((t-T.reparto)/0.5, 0, 1), repE = Easing.easeOutCubic(repP);

  // EL MOMENTO — las dos cifras descienden del 88 hasta sus líneas
  const f1 = clamp((t-T.nave)/0.6, 0, 1),   e1 = Easing.easeOutCubic(f1);
  const f2 = clamp((t-T.tienda)/0.6, 0, 1), e2 = Easing.easeOutCubic(f2);
  const DX = (XIN - 20) - XUNID;   // 260 — los dos bordes derechos coinciden en el arranque
  const flecha = Easing.easeInOutCubic(clamp((t-T.sumo)/0.55, 0, 1));

  // Cambio de pestaña
  const salida = Easing.easeOutCubic(clamp((t-T.pestana)/0.55, 0, 1));
  const pedP = clamp((t-T.pedir)/0.5, 0, 1);

  // La Única Cosa (prueba) y el encogido final
  const midP = clamp((t-T.mide)/0.7, 0, 1), midE = Easing.easeOutCubic(midP);
  const veloOp = (t < T.unica1 ? 0 : clamp((t-T.unica1)/0.7, 0, 1)) * (1-midP) * 0.80;
  const u1P = clamp((t-T.unica1)/0.6, 0, 1), u1E = Easing.easeOutCubic(u1P);
  const u2P = clamp((t-T.unica2)/0.6, 0, 1), u2E = Easing.easeOutCubic(u2P);
  const u2Pulse = (t >= T.unica2+0.6 && t < T.unica2+1.7) ? Math.sin((t-T.unica2-0.6)/1.1*Math.PI) : 0;

  const cardH = 184 + rowH1 + panelH + 136 + 20;

  const Icono = ({ n, s=24, c='#64748B', w=1.9 })=>{
    const P = {
      warehouse: <><path d="M3 10.5 L12 4.5 L21 10.5 V20 H3 Z"/><path d="M8 20 V13.5 H16 V20"/></>,
      globe:     <><circle cx="12" cy="12" r="9"/><path d="M3 12 H21"/><path d="M12 3 C8.2 6.8 8.2 17.2 12 21 C15.8 17.2 15.8 6.8 12 3"/></>,
    }[n];
    return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round">{P}</svg>;
  };

  // ── Una fila de «Vista global» (la 1 es la protagonista) ──
  const FilaGlobal = ({ i, producto, unidades, almacenes, top, alto })=>{
    const p = clamp((t-T.filas-i*T.filaStep)/0.45, 0, 1);
    const prota = i === 0;
    const apag = prota ? 0 : eleva*0.6;
    return (
      <div style={{position:'absolute', left:IX, top, width:IW, height:alto,
                   display:'grid', gridTemplateColumns:`${C.chev}px ${C.prod}px ${C.unid}px ${C.alm}px`,
                   alignItems:'center', borderTop:'1px solid #F1F5F9', borderRadius:prota && eleva > 0 ? 12 : 0,
                   background:prota && eleva > 0 ? '#fff' : 'transparent',
                   boxShadow:prota && eleva > 0 ? `0 24px 60px rgba(15,23,42,${eleva*0.18})` : 'none',
                   opacity:p*(1-apag), zIndex:prota ? 3 : 1}}>
        <span style={{paddingLeft:10, display:'flex', alignItems:'center',
                      transform:prota ? `rotate(${90*Easing.easeOutCubic(clamp((t-T.despliega)/0.4,0,1))}deg)` : 'none',
                      transformOrigin:'center'}}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#94A3B8" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 5 L16 12 L9 19"/>
          </svg>
        </span>
        <span className="f-plex" style={{fontSize:22, fontWeight:prota && eleva > 0 ? 700 : 500, color:'#0F172A'}}>{producto}</span>
        <span className="f-mono" style={{fontSize:prota ? size88 : 24, fontWeight:700, color:'#0F172A', textAlign:'right', lineHeight:1,
                                         opacity:prota ? clamp((t-T.n88)/0.25,0,1) : 1,
                                         textShadow:prota && glow88 > 0 ? `0 0 ${glow88*44}px rgba(29,115,226,0.75)` : 'none'}}>
          {prota ? n88 : unidades}
        </span>
        <span className="f-mono" style={{fontSize:23, color:'#334155', textAlign:'center'}}>{almacenes}</span>
      </div>
    );
  };

  // ── Una línea del reparto: la cifra desciende del 88 ──
  const LineaReparto = ({ nombre, valor, dy, prog, ease, top, filete })=>(
    <div style={{position:'absolute', left:IX+20, top, width:IW-40, height:60,
                 display:'flex', alignItems:'center', borderTop:filete ? '1px solid #E2E8F0' : 'none'}}>
      <Icono n="warehouse" s={26} c="#64748B" w={1.9}/>
      <span className="f-plex" style={{fontSize:23, color:'#334155', marginLeft:12, opacity:repP}}>{nombre}</span>
      <div style={{flex:1}}/>
      <span className="f-mono" style={{fontSize:27, fontWeight:800, color:'#0F172A', display:'inline-block',
              opacity:clamp(prog*3, 0, 1), transformOrigin:'right center',
              transform:`translate(${(1-ease)*DX}px, ${-(1-ease)*dy}px) scale(${lerp(1.55, 1, ease)})`,
              textShadow:prog >= 1 ? '0 0 26px rgba(29,115,226,0.55)' : 'none'}}>
        {valor}
      </span>
    </div>
  );

  // ── Una tarjeta de «Por almacén» ──
  const TarjetaAlmacen = ({ i, nombre, filas, top })=>{
    const p = clamp((t-T.pestana-0.15-i*T.almacenStep)/0.6, 0, 1), e = Easing.easeOutCubic(p);
    const CA = { prod:552, disp:210, min:210, max:210, ped:210 };
    const cols = `${CA.prod}px ${CA.disp}px ${CA.min}px ${CA.max}px ${CA.ped}px`;
    const CAB = ['Producto','Disponible','Mínimo','Máximo','Pedir'];
    return (
      <div style={{position:'absolute', left:CARDX, top, width:CARDW, height:278, borderRadius:16, background:'#fff',
                   border:'1px solid #E2E8F0', boxShadow:'0 22px 54px rgba(15,23,42,0.09)', padding:'24px',
                   opacity:p, transform:`translateX(${(1-e)*160}px)`}}>
        <div style={{display:'flex', alignItems:'center', gap:12, height:46}}>
          <Icono n="warehouse" s={30} c="#334155" w={1.9}/>
          <span className="f-plex" style={{fontSize:28, fontWeight:700, color:'#0F172A'}}>{nombre}</span>
        </div>
        <div style={{display:'grid', gridTemplateColumns:cols, alignItems:'center', height:44, marginTop:12}}>
          {CAB.map((h,j)=>{
            const on = clamp((t-T.cabeceras-(j-2)*T.cabeceraStep)/0.35, 0, 1);
            const esPedir = j === 4;
            return (
              <span key={h} className="f-plex" style={{fontSize:19, fontWeight:esPedir && pedP > 0 ? 700 : 600,
                      color:esPedir && pedP > 0 ? AMBAR : (on > 0 ? '#0F172A' : '#94A3B8'),
                      textAlign:j === 0 ? 'left' : 'right', paddingRight:j === 0 ? 0 : 8,
                      opacity:(!esPedir && pedP > 0) ? lerp(1, 0.55, pedP) : 1,
                      textShadow:on > 0 && on < 1 ? `0 0 ${(1-on)*16}px rgba(29,115,226,0.6)` : 'none'}}>{h}</span>
            );
          })}
        </div>
        {filas.map((f,k)=>(
          <div key={f[0]} style={{display:'grid', gridTemplateColumns:cols, alignItems:'center', height:64, borderTop:'1px solid #F1F5F9'}}>
            <span className="f-plex" style={{fontSize:21, color:'#0F172A', opacity:pedP > 0 ? lerp(1,0.55,pedP) : 1}}>{f[0]}</span>
            {[1,2,3].map(c=>(
              <span key={c} className="f-mono" style={{fontSize:23, color:'#334155', textAlign:'right', paddingRight:8,
                      opacity:pedP > 0 ? lerp(1,0.55,pedP) : 1}}>{f[c]}</span>
            ))}
            <span className="f-mono" style={{fontSize:26, fontWeight:700, textAlign:'right', paddingRight:8,
                    color:pedP > 0 ? AMBAR : '#0F172A'}}>{f[4]}</span>
          </div>
        ))}
      </div>
    );
  };

  return (
    <SlideCanvas variant="light">
      <DemoHeader t={t} eyebrow="LAS DOS VISTAS" title={<span>La misma suma, por los dos lados</span>}/>

      {/* ─────────── La ventana ─────────── */}
      <div style={{position:'absolute', left:WX, top:WY, width:WW, opacity:1-veloOp/0.80*0.78,
                   filter:veloOp > 0 ? 'saturate(0.55)' : 'none',
                   transform:`scale(${lerp(1, 0.62, midE)})`, transformOrigin:'top left'}}>
        <div style={{background:'#fff', borderRadius:18, border:'1px solid #E2E8F0',
                     boxShadow:'0 34px 80px rgba(15,23,42,0.13)', overflow:'hidden', height:CH+BH}}>
          <BrowserChrome url="play.dinaup.com/App/Pymes/Replenishment" title="Reposición"/>
        </div>
      </div>

      {/* Las dos pestañas (dentro del recuadro, pero en capa propia para poder anotarlas) */}
      <div style={{position:'absolute', left:0, top:0, width:1920, height:1080, pointerEvents:'none',
                   opacity:1-veloOp/0.80*0.78, filter:veloOp > 0 ? 'saturate(0.55)' : 'none',
                   transform:`scale(${lerp(1, 0.62, midE)})`, transformOrigin:`${WX}px ${WY}px`}}>

        <div style={{position:'absolute', left:240, top:296, display:'flex', gap:12, opacity:vsP}}>
          {[['Vista global','globe'], ['Por almacén','warehouse']].map((p,i)=>{
            const activa = (i === 0) !== (salida > 0.5);
            return (
              <div key={p[0]} style={{width:238, height:62, display:'flex', alignItems:'center', justifyContent:'center', gap:11}}>
                <Icono n={p[1]} s={24} c={activa ? AZUL : '#64748B'} w={1.9}/>
                <span className="f-plex" style={{fontSize:25, fontWeight:activa ? 700 : 500, color:activa ? AZUL : '#64748B'}}>{p[0]}</span>
              </div>
            );
          })}
        </div>
        <div style={{position:'absolute', left:lerp(240, 490, Easing.easeInOutCubic(clamp((t-T.pestana)/0.45,0,1))),
                     top:358, width:lerp(subW, 238, Easing.easeInOutCubic(clamp((t-T.pestana)/0.45,0,1))),
                     height:4, borderRadius:2, background:AZUL, opacity:vsP}}/>
        <div style={{position:'absolute', left:240, top:360, width:1440, height:1, background:'#EEF2F6', opacity:vsP}}/>

        {/* ─────────── «Vista global» ─────────── */}
        {salida < 1 && (
          <div style={{position:'absolute', left:CARDX, top:CARDY, width:CARDW, height:cardH, borderRadius:16,
                       background:'#fff', border:'1px solid #E2E8F0', boxShadow:'0 22px 54px rgba(15,23,42,0.09)',
                       opacity:tiP*(1-salida), transform:`translateX(${-salida*130}px)`}}/>
        )}
        {salida < 1 && (
          <div style={{position:'absolute', left:0, top:0, opacity:(1-salida), transform:`translateX(${-salida*130}px)`}}>
            <div style={{position:'absolute', left:IX, top:406, display:'flex', alignItems:'center', gap:12,
                         opacity:tiP, transform:`translateY(${(1-tiE)*10}px)`}}>
              <Icono n="globe" s={28} c={AZUL} w={1.9}/>
              <span className="f-plex" style={{fontSize:30, fontWeight:700, color:'#0F172A'}}>Necesidad global de compra</span>
            </div>
            <div className="f-plex" style={{position:'absolute', left:IX, top:452, width:1180, fontSize:19, color:'#64748B',
                         opacity:baP*0.75, lineHeight:1.4}}>
              Unidades totales a comprar de cada producto para abastecer todos los almacenes bajo mínimo. Expande una fila para ver el reparto.
            </div>

            {/* Cabeceras de la rejilla global */}
            <div style={{position:'absolute', left:IX, top:HEADY, width:IW, height:46,
                         display:'grid', gridTemplateColumns:`${C.chev}px ${C.prod}px ${C.unid}px ${C.alm}px`,
                         alignItems:'center', opacity:clamp((t-T.filas+0.4)/0.5,0,1)}}>
              <span/>
              <span className="f-plex" style={{fontSize:19, fontWeight:600, color:'#64748B'}}>Producto</span>
              <span className="f-plex" style={{fontSize:19, fontWeight:600, color:'#64748B', textAlign:'right'}}>Unidades a comprar</span>
              <span className="f-plex" style={{fontSize:19, fontWeight:600, color:'#64748B', textAlign:'center'}}>Almacenes</span>
            </div>

            <FilaGlobal i={0} producto="Guantes de nitrilo" unidades="88" almacenes="2" top={ROWY} alto={rowH1}/>

            {/* El panel de reparto, dentro de la fila abierta */}
            {panelH > 0 && (
              <div style={{position:'absolute', left:IX, top:PANY, width:IW, height:panelH,
                           background:'#F8FAFC', borderTop:'1px solid #E2E8F0', overflow:'hidden'}}>
                <div className="f-plex" style={{position:'absolute', left:20, top:18, fontSize:24, fontWeight:800, color:'#0F172A',
                             opacity:repP, transform:`translateY(${(1-repE)*8}px)`}}>Reparto por almacén</div>
              </div>
            )}
            {panelH > 0 && (
              <>
                <LineaReparto nombre="Nave"   valor="48 uds" dy={134} prog={f1} ease={e1} top={PANY+68}  filete={false}/>
                <LineaReparto nombre="Tienda" valor="40 uds" dy={194} prog={f2} ease={e2} top={PANY+128} filete/>
              </>
            )}

            {/* «se sumó abajo»: la flecha se dibuja de abajo hacia arriba */}
            {flecha > 0 && (
              <svg style={{position:'absolute', left:0, top:0, pointerEvents:'none'}} width="1920" height="1080" fill="none">
                <path d={`M1450 ${PANY+186} V${ROWY+56}`} pathLength="1" stroke={AZUL} strokeWidth="4" strokeLinecap="round"
                      strokeDasharray="1" strokeDashoffset={1-flecha}/>
                <path d={`M1440 ${ROWY+68} L1450 ${ROWY+56} L1460 ${ROWY+68}`} stroke={AZUL} strokeWidth="4"
                      strokeLinecap="round" strokeLinejoin="round" opacity={clamp((flecha-0.82)/0.18,0,1)}/>
              </svg>
            )}

            <FilaGlobal i={1} producto="Cemento gris"    unidades="80" almacenes="1" top={PANY+panelH} alto={68}/>
            <FilaGlobal i={2} producto="Silicona blanca" unidades="15" almacenes="1" top={PANY+panelH+68} alto={68}/>
          </div>
        )}

        {/* ─────────── «Por almacén» — la misma cuenta del revés ─────────── */}
        {salida > 0 && (
          <>
            <TarjetaAlmacen i={0} nombre="Tienda" top={380} filas={[
              ['Cemento gris','40','60','120','80'],
              ['Guantes de nitrilo','20','30','60','40'],
            ]}/>
            <TarjetaAlmacen i={1} nombre="Nave" top={686} filas={[
              ['Guantes de nitrilo','12','30','60','48'],
              ['Silicona blanca','5','20','0','15'],
            ]}/>
          </>
        )}
      </div>

      {/* ─────────── La Única Cosa · PRUEBA, encima de la tabla que la demuestra ─────────── */}
      {veloOp > 0 && <div style={{position:'absolute', inset:0, background:'#fff', opacity:veloOp}}/>}
      {u1P > 0 && midP < 1 && (
        <div className="f-plex" style={{position:'absolute', left:0, right:0, top:410, textAlign:'center', fontSize:68, fontWeight:800,
                                        letterSpacing:'-0.03em', color:'#0F172A', opacity:u1E*(1-midP), transform:`translateY(${(1-u1E)*18}px)`}}>
          Reposición no adivina.
        </div>
      )}
      {u2P > 0 && midP < 1 && (
        <div className="f-plex" style={{position:'absolute', left:0, right:0, top:516, textAlign:'center', fontSize:68, fontWeight:800,
                                        letterSpacing:'-0.03em', opacity:u2E*(1-midP), transform:`translateY(${(1-u2E)*18}px)`,
                                        textShadow:u2Pulse > 0 ? `0 0 ${u2Pulse*36}px rgba(0,133,255,0.45)` : 'none'}}>
          <span className="grad-text">Resta lo que tienes del techo que pusiste.</span>
        </div>
      )}

      <ScriptedCursor t={t} clickTimes={[T.despliega, T.pestana]} frames={[
        { t:0.8,  x:1780, y:1010 },
        { t:16.5, x:1780, y:1010 },
        { t:17.25, x:292, y:615 },
        { t:28.8, x:292, y:615 },
        { t:29.40, x:609, y:327 },
        { t:41.2, x:609, y:327 },
        { t:42.3, x:1980, y:1140 },
      ]}/>
    </SlideCanvas>
  );
}
Object.assign(window, { EscenaRP04 });
