// === Escena 02 — "El editor y sus cuatro pestañas" ===
// Mismo formulario, ahora titulado «Agregar documento dinámico» (TERM\FuncionAPIF.vb:424).
// Pestañas «Básico · Variables · Código · Previa» (FuncionAPIF_Dislpay.vb:24-27), y solo una
// visible a la vez. En «Básico», dos bloques: «Identificación» (Titulo, Categoria, Subcategoria,
// Descripción + icono — Designer:633-638) y «Disponibilidad» (ID con «(Debe guardar para ver el
// ID)», Proteccion, tencoding, Extension y las casillas impresion/ticket/ri/Email — :1112-1121).
// El desplegable «Clase» está OCULTO (Designer:883): gris = «aquí no está», nunca «no existe».
// En alta, «Aplicar» se comporta como «Aceptar» y la ventana se cierra (:301, 308-313, 544);
// el identificador solo se pinta al reabrir (:450). Pie de CINCO controles (:1702, 1059, 1870, 412, 364).
function EscenaPL02({ t }){
  const T = {
    pestanas:0.9,     // "cuatro pestañas"
    soloCodigo:2.1,   // "solo una enseña código"
    ficha:5.0,        // "la ficha del documento"
    describe:8.5,     // "cómo se describe"
    donde:11.2,       // "dónde puede aparecer"
    impTicket:12.4,   // "impresión, ticket"
    informe:14.0,     // "dentro de un informe"
    correo:15.3,      // "o correo"
    cuatro:16.8,      // "Aquí salen las cuatro"
    puedenNo:20.2,    // "pueden no estar"
    laClase:22.0,     // "La clase, por cierto"
    eligio:25.7,      // "La eligió el botón que pulsaste"
    niSiquiera:28.8,  // "ni siquiera está en pantalla"
    ident:33.4,       // "el identificador dice"
    guardar:36.0,     // "debes guardar para verlo"
    cierra:39.1,      // "la ventana se cierra"
    vuelve:42.1,      // "cuando la vuelves a abrir"
    salida:45.1,      // "mira qué datos llegan solos"
    campoStep:0.13,    // cascada de los campos de «Identificación»
    casillaStep:0.10,  // cascada dentro de la fila de casillas
  };

  // ── Geometría ──
  const WX=90, WY=152, WW=1300, WH=900;
  const BODY = WY + 64;                 // techo del cuerpo (bajo la barra de título)
  const TABS = 52;                      // alto de la tira de pestañas
  const PX=34, PW=WW-68;                // panel: margen y ancho locales
  const IDENT_Y = TABS + 20;            // «Identificación», local al cuerpo
  const DISP_Y  = IDENT_Y + 292 + 18;   // «Disponibilidad»
  const ROW_H = 58;
  const AX=1424, AW=436;                // columna de anotación (derecha)

  const IDENTIF = [
    ['Titulo',       'Factura - Moderna'],
    ['Categoria',    'Ventas / Ingresos'],
    ['Subcategoria', 'Facturas'],
    ['Descripción',  'Factura A4 con desglose de impuestos'],
  ];
  const DISPON = [
    ['Proteccion', 'Sin proteccion'],
    ['tencoding',  'UTF-8'],
    ['Extension',  '.pdf'],
  ];
  const CASILLAS = [
    ['impresion', T.impTicket],
    ['ticket',    T.impTicket+0.55],
    ['ri',        T.informe],
    ['Email',     T.correo],
  ];

  // ── Progresos ──
  const wnP = clamp((t-T.pestanas)/0.8,0,1), wnE = Easing.easeOutCubic(wnP);
  const codMark = t >= T.soloCodigo && t < T.soloCodigo+1.35;
  const idnP = clamp((t-T.ficha)/0.6,0,1), idnE = Easing.easeOutBack(idnP);
  const dspP = clamp((t-T.donde)/0.6,0,1), dspE = Easing.easeOutBack(dspP);
  const cuatroGlow = t >= T.cuatro && t < T.cuatro+1.5 ? Math.sin((t-T.cuatro)/1.5*Math.PI) : 0;
  const parpadeo   = t >= T.puedenNo && t < T.puedenNo+1.6 ? Math.sin((t-T.puedenNo)/1.6*Math.PI) : 0;

  // Anotación de la clase oculta
  const clP = clamp((t-T.laClase)/0.6,0,1), clE = Easing.easeOutBack(clP);
  const elP = clamp((t-T.eligio)/0.5,0,1);
  const niP = clamp((t-T.niSiquiera)/0.5,0,1);
  const niTacha = Easing.easeInOutCubic(clamp((t-T.niSiquiera-0.15)/0.6,0,1));

  // El identificador: foco → se levanta del formulario → la ventana se va → vuelve con el número
  const foco = t >= T.ident;
  const lift = clamp(clamp((t-T.cierra)/0.55,0,1) - clamp((t-T.vuelve)/0.6,0,1), 0, 1);
  const liftE = Easing.easeInOutCubic(lift);
  const winOut = clamp(clamp((t-T.cierra+0.05)/0.5,0,1) - clamp((t-T.vuelve)/0.55,0,1), 0, 1);
  const conNumero = t >= T.vuelve + 0.45;
  const salP = clamp((t-T.salida)/0.6,0,1), salE = Easing.easeOutCubic(salP);

  // Posición del campo «ID»: en su hueco (lift 0) o en el aire, grande (lift 1)
  const idSlot = { x:WX+PX+22, y:BODY+DISP_Y+46, w:PW-44 };
  const idX = lerp(idSlot.x, 498, liftE);
  const idY = lerp(idSlot.y, 452, liftE);
  const idS = lerp(1, 1.62, liftE);
  const idW = lerp(PW-44, 570, liftE);

  // ── Ventana de escritorio de Dinaup Terminal ──
  const Ventana = ({ x, y, w, h, titulo, op=1, dy=0, sc=1, children })=>(
    <div style={{position:'absolute', left:x, top:y, width:w, height:h, opacity:op,
                 transform:`translateY(${dy}px) scale(${sc})`, transformOrigin:'50% 50%'}}>
      <div style={{position:'absolute', inset:0, background:'#313236', borderRadius:14,
                   border:'1px solid #45484F', boxShadow:'0 42px 96px rgba(2,6,23,0.50)', overflow:'hidden'}}>
        <div style={{position:'absolute', left:0, right:0, top:0, height:64, background:'linear-gradient(180deg,#2C2E33,#25272B)',
                     borderBottom:'1px solid #3C3F45', display:'flex', alignItems:'center', gap:15, padding:'0 18px'}}>
          <div style={{width:36, height:36, borderRadius:9, background:'linear-gradient(135deg,#0085FF,#0063BE)',
                       display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.9">
              <path d="M6 3 H14 L19 8 V21 H6 Z" strokeLinejoin="round"/><path d="M14 3 V8 H19"/>
            </svg>
          </div>
          <span className="f-plex" style={{fontSize:28, fontWeight:700, color:'#F2F5F9', letterSpacing:'-0.01em'}}>{titulo}</span>
          <div style={{flex:1}}/>
          <div style={{display:'flex', gap:24, opacity:0.65}}>
            <svg width="15" height="15" viewBox="0 0 16 16"><path d="M2 8 H14" stroke="#A9B0BA" strokeWidth="1.6"/></svg>
            <svg width="15" height="15" viewBox="0 0 16 16"><rect x="2.5" y="2.5" width="11" height="11" fill="none" stroke="#A9B0BA" strokeWidth="1.6"/></svg>
            <svg width="15" height="15" viewBox="0 0 16 16"><path d="M3 3 L13 13 M13 3 L3 13" stroke="#A9B0BA" strokeWidth="1.6"/></svg>
          </div>
        </div>
        <div style={{position:'absolute', left:0, right:0, top:64, bottom:0}}>{children}</div>
      </div>
    </div>
  );

  // ── Cabecera de bloque plegable ──
  const Bloque = ({ top, titulo, alto, p, e, children })=>(
    <div style={{position:'absolute', left:PX, top, width:PW, height:alto,
                 background:'#35373C', border:'1px solid #4A4D54', borderRadius:10,
                 opacity:clamp(p*1.35,0,1), transform:`translateY(${(1-e)*14}px)`}}>
      <div style={{height:46, display:'flex', alignItems:'center', gap:12, padding:'0 20px', borderBottom:'1px solid #43464C'}}>
        <svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="#9AA2AD" strokeWidth="2"><path d="M4 6 L8 10 L12 6" strokeLinecap="round"/></svg>
        <span className="f-plex" style={{fontSize:23, fontWeight:700, color:'#DDE3EA', letterSpacing:'0.01em'}}>{titulo}</span>
      </div>
      {children}
    </div>
  );

  // ── Una fila de campo (etiqueta + caja de valor) ──
  const Campo = ({ i, label, valor, top, start, mono })=>{
    const p = clamp((t-start-i*T.campoStep)/0.45,0,1), e = Easing.easeOutCubic(p);
    return (
      <div style={{position:'absolute', left:22, top, width:PW-44, height:ROW_H-8,
                   display:'flex', alignItems:'center', gap:18, opacity:clamp(p*1.4,0,1), transform:`translateY(${(1-e)*8}px)`}}>
        <span className="f-plex" style={{width:196, flexShrink:0, fontSize:19, color:'#A8B0BC', textAlign:'right'}}>{label}</span>
        <div style={{flex:1, height:42, background:'#3D4046', border:'1px solid #4E525A', borderRadius:6,
                     display:'flex', alignItems:'center', padding:'0 14px'}}>
          <span className={mono ? 'f-mono' : 'f-plex'} style={{fontSize:20, color:'#E7ECF3'}}>{valor}</span>
        </div>
      </div>
    );
  };

  return (
    <SlideCanvas variant="light">
      <DemoHeader t={t} eyebrow="EL EDITOR · QUÉ HAY Y QUÉ NO" title={<span>Dónde está cada cosa</span>}/>

      {/* ─────────── El editor ─────────── */}
      {wnP > 0 && (
        <Ventana x={WX} y={WY} w={WW} h={WH} titulo="Agregar documento dinámico"
                 op={clamp(wnP*1.4,0,1)*(1-winOut)} dy={(1-wnE)*22 + winOut*18} sc={lerp(1,0.975,winOut)}>

          {/* Tira de pestañas: solo una visible a la vez */}
          <div style={{position:'absolute', left:0, right:0, top:0, height:TABS, background:'#2A2C30',
                       borderBottom:'1px solid #3C3F45', display:'flex', alignItems:'flex-end', gap:2, padding:'0 18px'}}>
            {['Básico','Variables','Código','Previa'].map((s,i)=>{
              const act = i === 0;
              const mark = codMark && s === 'Código';
              return (
                <span key={s} className="f-plex" style={{padding:'11px 28px', fontSize:21, fontWeight:act||mark?700:500,
                              color:act ? '#F2F5F9' : (mark ? '#0085FF' : '#8C939E'),
                              background:act ? '#313236' : (mark ? 'rgba(0,133,255,0.12)' : 'transparent'),
                              borderTop:`3px solid ${act ? '#0085FF' : (mark ? 'rgba(0,133,255,0.6)' : 'transparent')}`,
                              borderRadius:'6px 6px 0 0'}}>{s}</span>
              );
            })}
            <div style={{flex:1}}/>
            <span className="f-mono" style={{fontSize:16, color:'#6E757F', padding:'0 6px 14px'}}>una a la vez</span>
          </div>

          {/* Bloque «Identificación» */}
          {idnP > 0 && (
            <Bloque top={IDENT_Y} titulo="Identificación" alto={292} p={idnP} e={idnE}>
              {IDENTIF.map((f,i)=>(
                <Campo key={f[0]} i={i} label={f[0]} valor={f[1]} top={46+10+i*ROW_H}
                       start={i < 2 ? T.ficha+0.35 : T.describe}/>
              ))}
              {/* el icono del documento */}
              <div style={{position:'absolute', right:26, top:60, width:78, height:78, borderRadius:10,
                           background:'#3D4046', border:'1px solid #4E525A', display:'flex', alignItems:'center', justifyContent:'center',
                           opacity:clamp((t-T.ficha-0.5)/0.5,0,1)}}>
                <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#8C939E" strokeWidth="1.7">
                  <path d="M6 3 H14 L19 8 V21 H6 Z" strokeLinejoin="round"/><path d="M14 3 V8 H19"/>
                </svg>
              </div>
            </Bloque>
          )}

          {/* Bloque «Disponibilidad» */}
          {dspP > 0 && (
            <Bloque top={DISP_Y} titulo="Disponibilidad" alto={360} p={dspP} e={dspE}>
              {/* el hueco del campo «ID» — el campo se pinta fuera, para poder levantarlo */}
              <div style={{position:'absolute', left:22, top:10, width:PW-44, height:ROW_H-8, opacity:lift > 0.02 ? 0.18 : 0,
                           border:'1px dashed #5A5E66', borderRadius:6}}/>
              {DISPON.map((f,i)=>(
                <Campo key={f[0]} i={i} label={f[0]} valor={f[1]} top={10+(i+1)*ROW_H} start={T.donde+0.3} mono={i > 0}/>
              ))}
              {/* La fila de casillas: aquí salen las cuatro */}
              <div style={{position:'absolute', left:22, top:10+4*ROW_H+6, width:PW-44, height:56,
                           display:'flex', alignItems:'center', gap:44, paddingLeft:214,
                           borderRadius:9, background:cuatroGlow > 0 ? `rgba(0,133,255,${cuatroGlow*0.16})` : 'transparent'}}>
                {CASILLAS.map(([nombre, start], i)=>{
                  const p = clamp((t-start-i*T.casillaStep)/0.4,0,1), e = Easing.easeOutBack(p);
                  const gris = i < 3 ? parpadeo : 0;
                  const col = gris > 0.15 ? '#94A3B8' : '#10B981';
                  return (
                    <span key={nombre} style={{display:'inline-flex', alignItems:'center', gap:11,
                                  opacity:clamp(p*1.3,0,1)*(1-gris*0.45), transform:`scale(${lerp(0.7,1,e)})`}}>
                      <span style={{width:26, height:26, borderRadius:5, background:col, display:'flex', alignItems:'center', justifyContent:'center'}}>
                        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.2">
                          <path d="M5 12.5 L10 17 L19 7" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </span>
                      <span className="f-plex" style={{fontSize:20, color:'#DDE3EA'}}>{nombre}</span>
                    </span>
                  );
                })}
              </div>
            </Bloque>
          )}

          {/* Pie: cinco controles, ninguno oculto */}
          <div style={{position:'absolute', left:PX, right:PX, top:DISP_Y+360+22, height:64,
                       display:'flex', alignItems:'center', gap:16, opacity:clamp((t-T.donde-0.9)/0.6,0,1)}}>
            <span className="f-plex" style={{padding:'13px 26px', borderRadius:8, background:'#3A3D43', border:'1px solid #565A62',
                          fontSize:21, fontWeight:600, color:'#C3CAD4'}}>Duplicar</span>
            <span style={{width:42, height:42, borderRadius:8, background:'#3A3D43', border:'1px solid #565A62',
                          display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
              <svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="#C3CAD4" strokeWidth="1.8">
                <path d="M4 4 H16 L20 8 V20 H4 Z" strokeLinejoin="round"/><path d="M8 4 V10 H16 V4"/><rect x="8" y="14" width="8" height="6"/>
              </svg>
            </span>
            <div style={{flex:1}}/>
            {['Aplicar','Aceptar','Cancelar'].map((s,i)=>(
              <span key={s} className="f-plex" style={{padding:'13px 30px', borderRadius:8,
                            background:i===1 ? '#0F6FD1' : '#3A3D43', border:`1px solid ${i===1 ? '#0085FF' : '#565A62'}`,
                            fontSize:21, fontWeight:600, color:i===1 ? '#fff' : '#C3CAD4'}}>{s}</span>
            ))}
          </div>
        </Ventana>
      )}

      {/* ─────────── El campo «ID»: se levanta del formulario cuando la ventana se va ─────────── */}
      {dspP > 0 && (
        <div style={{position:'absolute', left:idX, top:idY, width:idW, height:ROW_H-8,
                     transform:`scale(${idS})`, transformOrigin:'left center', zIndex:20,
                     display:'flex', alignItems:'center', gap:18,
                     opacity:clamp((t-T.donde-0.3)/0.5,0,1)}}>
          <span className="f-plex" style={{width:196, flexShrink:0, fontSize:19, color:foco ? '#0085FF' : '#A8B0BC', textAlign:'right', fontWeight:foco?700:400}}>ID</span>
          <div style={{flex:1, height:42, background:'#3D4046', borderRadius:6,
                       border:`${foco ? 2 : 1}px solid ${foco ? '#0085FF' : '#4E525A'}`,
                       boxShadow:foco ? `0 0 ${26+lift*20}px rgba(0,133,255,0.45)` : 'none',
                       display:'flex', alignItems:'center', padding:'0 14px'}}>
            {conNumero
              ? <Typewriter text="1042" start={T.vuelve+0.45} cps={9} t={t} caret
                            style={{fontFamily:"'JetBrains Mono',monospace", fontSize:22, fontWeight:700, color:'#56E16A'}}/>
              : <span className="f-plex" style={{fontSize:20, color:t >= T.guardar ? '#FB8C00' : '#98A0AC',
                            fontWeight:t >= T.guardar ? 700 : 400}}>(Debe guardar para ver el ID)</span>}
          </div>
        </div>
      )}

      {/* ─────────── Anotación: la clase no se elige aquí ─────────── */}
      {clP > 0 && (
        <div style={{position:'absolute', left:AX, top:322, width:AW,
                     opacity:clamp(clP*1.3,0,1)*(foco ? 0.4 : 1)*(1-lift),
                     transform:`scale(${lerp(0.9,1,clE)})`}}>
          <div style={{background:'#fff', borderRadius:16, border:'1px solid #E2E8F0', boxShadow:'0 24px 56px rgba(15,23,42,0.10)', padding:'26px 28px'}}>
            <div className="f-plex" style={{fontSize:17, fontWeight:700, letterSpacing:'2.2px', color:'#94A3B8'}}>LA CLASE</div>
            {/* El desplegable, dibujado en gris: existe en el diseñador y no está en la ventana */}
            <div style={{position:'relative', marginTop:16, height:56, borderRadius:8, background:'#F1F5F9',
                         border:'1px dashed #B6BDC8', display:'flex', alignItems:'center', padding:'0 16px', gap:12}}>
              <span className="f-plex" style={{fontSize:22, color:'#94A3B8'}}>Documento - Libre</span>
              <div style={{flex:1}}/>
              <span style={{color:'#B6BDC8', fontSize:18}}>▾</span>
              <span style={{position:'absolute', left:10, right:10, top:'50%', height:3, borderRadius:2, background:'#94A3B8',
                            transform:`scaleX(${niTacha})`, transformOrigin:'left'}}/>
            </div>
            {niP > 0 && (
              <div className="f-mono" style={{fontSize:17, color:'#94A3B8', marginTop:14, lineHeight:1.5, opacity:niP}}>
                no está en la ventana<br/>ClaseCB.Visible = False
              </div>
            )}
            {elP > 0 && (
              <div style={{marginTop:18, paddingTop:16, borderTop:'1px solid #F1F5F9', opacity:elP,
                           transform:`translateY(${(1-elP)*8}px)`}}>
                <span className="f-plex" style={{fontSize:23, fontWeight:600, color:'#0F172A', lineHeight:1.35}}>
                  La fijó el botón que pulsaste.
                </span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Puente hacia la escena 3 */}
      {salP > 0 && (
        <div className="f-plex" style={{position:'absolute', left:0, right:0, top:1000, textAlign:'center', fontSize:32, fontWeight:600,
                                        color:'#64748B', opacity:salE, transform:`translateY(${(1-salE)*12}px)`}}>
          Ahora, qué datos llegan solos.
        </div>
      )}
    </SlideCanvas>
  );
}
Object.assign(window, { EscenaPL02 });
