// === F2 · Flex — El ANTES (14s): el Excel que sostiene tu negocio único ===
// Una hoja de cálculo (chrome verde tipo Excel) se construye con datos de un
// minigolf, se degrada (#¡REF!, #N/D, rojos a mano, total que no cuadra,
// rellenos inconsistentes), acumula badges de dolor… y GIRO: la ventana se
// encoge y desatura hacia la izquierda mientras Dinaup entra nítido a la
// derecha. Sincronizado con CAPTIONS.slide_flexexcel
// (0.5-3.2 / 3.2-6.0 / 6.0-8.8 / 8.8-11.4 / 11.4-13.7).

function SlideFlexExcel({ t }){
  // ---- Timeline ----
  const winAt = 0.5, headAt = 1.25, rowsAt = 1.5, totRowAt = 3.0;          // beat 1: la hoja aparece
  const refAt = 3.4, ndAt = 3.95, fillVerdeAt = 4.5, fillNaranjaAt = 5.05; // beat 2: el caos entra, goteo
  const notaAt = 5.05, malTotalAt = 5.6, notaTotalAt = 5.9;
  const badgeAts = [6.2, 7.0, 7.8];                                        // beat 3: dolores alrededor
  const giroAt = 8.8, arrowAt = 9.3, logoAt = 9.5, fraseAt = 10.3;         // beat 4: el giro
  const verdeAt = 11.6;                                                    // beat 5: mismo control, cero caos

  // ---- Progresos ----
  const winP = clamp((t-winAt)/0.7, 0, 1), winE = Easing.easeOutCubic(winP);
  const headP = clamp((t-headAt)/0.4, 0, 1);
  const totP = clamp((t-totRowAt)/0.4, 0, 1);
  const ge = Easing.easeInOutCubic(clamp((t-giroAt)/1.4, 0, 1));

  // ---- Geometría de la ventana Excel ----
  const W = 1150, H = 560, L = 385, T = 200;
  const COLS = '36px 292px 128px 122px 150px 158px 1fr';
  const tx = -400*ge;
  const ty = (1-winE)*24 + 8*ge;
  const sc = lerp(0.97, 1, winE) * lerp(1, 0.60, ge);

  // ---- Datos verosímiles del minigolf ----
  const rows = [
    { j:'María López',    p:'Pista 4', h:'17:30', tk:'TK-1041', tot:'12,00 €' },
    { j:'Jorge Ruiz',     p:'Pista 2', h:'17:45', tk:'TK-1042', tot:'18,00 €', fillRow:fillVerdeAt },
    { j:'Familia Ortega', p:'Pista 1', h:'18:00', tk:'TK-1043', tot:'24,00 €', fillTk:fillNaranjaAt, nota:'¿cobrado en efectivo?' },
    { j:'Lucía Gómez',    p:'Pista 4', h:'18:15', tk:'TK-1045', tot:'12,00 €', refTot:refAt },
    { j:'Andrés Peña',    p:'Pista 3', h:'18:30', tk:'TK-1046', tot:'6,00 €',  ndHora:ndAt },
    { j:'Carmen Sanz',    p:'Pista 4', h:'19:00', tk:'TK-1047', tot:'12,00 €' },
  ];

  // Relleno que entra con flash y reposa translúcido (color a mano de Excel)
  const fill = (at, r, g2, b) => {
    if (at === undefined || t < at) return 'transparent';
    const p = clamp((t-at)/0.6, 0, 1);
    return `rgba(${r},${g2},${b},${lerp(0.34, 0.16, p)})`;
  };

  const cellBase = { display:'flex', alignItems:'center', padding:'0 10px', borderRight:'1px solid #E4E7EC', borderBottom:'1px solid #E4E7EC', fontSize:13.5, color:'#202124', overflow:'hidden', whiteSpace:'nowrap' };
  const numCell  = { ...cellBase, justifyContent:'center', padding:0, background:'#F5F6F8', color:'#7A8089', fontSize:11, fontFamily:"'JetBrains Mono',monospace" };
  const totalSel = t >= malTotalAt; // E9 seleccionada: el total "escrito a mano"

  const totalPulse = totalSel
    ? `inset 0 0 0 2.5px #DC2626, 0 0 ${12 + 5*Math.sin(t*3.2)}px rgba(220,38,38,${0.35*(1-ge)})`
    : 'none';

  // ---- Badges de dolor (viajan y se desaturan con la ventana) ----
  const badges = [
    { at:badgeAts[0], txt:'Sin permisos', style:{ left:-148, top:106, transform:'rotate(-2.5deg)' },
      icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="4.5" y="10.5" width="13" height="9" rx="2" stroke="#B91C1C" strokeWidth="1.8"/><path d="M8 10.5 V7 A4 4 0 0 1 15.6 5.4" stroke="#B91C1C" strokeWidth="1.8" strokeLinecap="round"/><circle cx="11" cy="15" r="1.4" fill="#B91C1C"/></svg> },
    { at:badgeAts[1], txt:'Sin copia de seguridad', style:{ right:-92, top:150, transform:'rotate(2deg)' },
      icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M7 17.5 A4.3 4.3 0 0 1 7.6 9 A5.5 5.5 0 0 1 18 10.6 A3.7 3.7 0 0 1 17.3 17.5 Z" stroke="#B91C1C" strokeWidth="1.8" strokeLinejoin="round"/><path d="M4.5 4.5 L19.5 19.5" stroke="#B91C1C" strokeWidth="1.8" strokeLinecap="round"/></svg> },
    { at:badgeAts[2], txt:'v3(2) — ¿cuál es la buena?', style:{ left:44, bottom:-27, transform:'rotate(-1.5deg)' },
      icon:<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M7 3 H14 L18.5 7.5 V19 A2 2 0 0 1 16.5 21 H7 A2 2 0 0 1 5 19 V5 A2 2 0 0 1 7 3 Z" stroke="#B91C1C" strokeWidth="1.8" strokeLinejoin="round"/><path d="M14 3 V8 H18.5" stroke="#B91C1C" strokeWidth="1.8" strokeLinejoin="round"/><path d="M9.9 11.6 A2 2 0 1 1 12 14.8 V15.8" stroke="#B91C1C" strokeWidth="1.7" strokeLinecap="round"/><circle cx="12" cy="18.3" r="1" fill="#B91C1C"/></svg> },
  ];

  // ---- Giro: contenido Dinaup a la derecha ----
  const logoP  = clamp((t-logoAt)/0.6, 0, 1), logoE = Easing.easeOutBack(logoP);
  const arrowP = clamp((t-arrowAt)/0.8, 0, 1), arrowE = Easing.easeInOutCubic(arrowP);
  const fraseP = clamp((t-fraseAt)/0.7, 0, 1), fraseE = Easing.easeOutCubic(fraseP);
  const verdeP = clamp((t-verdeAt)/0.6, 0, 1), verdeE = Easing.easeOutCubic(verdeP);

  return (
    <SlideCanvas variant="light-soft">
      {/* Tensión roja mientras el caos crece; se disuelve con el giro */}
      <div style={{position:'absolute', inset:0, background:'radial-gradient(ellipse 60% 55% at 50% 42%, rgba(239,68,68,0.10), transparent 62%)', opacity: clamp((t-3.3)/2.5,0,1)*(1-ge), pointerEvents:'none'}}/>
      {/* Aire limpio azul/verde que entra con Dinaup */}
      <div style={{position:'absolute', inset:0, background:'radial-gradient(ellipse 42% 48% at 72% 44%, rgba(0,133,255,0.10), transparent 65%), radial-gradient(ellipse 30% 35% at 78% 62%, rgba(86,225,106,0.08), transparent 65%)', opacity:ge, pointerEvents:'none'}}/>

      {/* Píldora de contexto — desaparece con el giro */}
      <div style={{position:'absolute', top:44, left:'50%', transform:'translateX(-50%)', zIndex:6, opacity: Math.min(clamp((t-0.3)/0.5,0,1), 1-clamp((t-giroAt)/0.4,0,1))}}>
        <span className="f-mono" style={{display:'inline-flex', alignItems:'center', gap:8, padding:'8px 16px', background:'rgba(15,23,42,0.92)', border:'1px solid rgba(255,255,255,0.10)', borderRadius:100, fontSize:11, fontWeight:700, letterSpacing:'3px', color:'#fff', boxShadow:'0 12px 32px rgba(15,23,42,0.25)'}}>
          <span style={{width:7, height:7, borderRadius:100, background:'#EF4444', boxShadow:'0 0 0 3px rgba(239,68,68,0.25)'}}/>
          EL ANTES
        </span>
      </div>

      {/* ===== Ventana Excel (encoge y se apaga hacia la izquierda en el giro) ===== */}
      <div style={{position:'absolute', left:L, top:T, width:W, height:H, zIndex:2, opacity: winP === 0 ? 0 : 1-ge*0.18, transform:`translate(${tx}px, ${ty}px) scale(${sc})`, filter: ge > 0 ? `grayscale(${ge*0.95}) brightness(${1-ge*0.07})` : 'none'}}>
        <div style={{position:'absolute', inset:0, background:'#fff', borderRadius:10, overflow:'hidden', border:'1px solid #C9CFD6', boxShadow:'0 30px 80px rgba(15,23,42,0.18)', opacity:winE}}>

          {/* Barra de título verde Excel */}
          <div style={{height:36, background:'#185C37', display:'flex', alignItems:'center', padding:'0 0 0 12px', gap:10}}>
            <div style={{width:19, height:19, borderRadius:4, background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
              <span className="f-plex" style={{fontSize:11.5, fontWeight:800, color:'#185C37', lineHeight:1}}>X</span>
            </div>
            <span style={{display:'inline-flex', alignItems:'center', gap:6, padding:'3px 10px', border:'1px solid rgba(255,255,255,0.30)', borderRadius:100, fontSize:10, color:'rgba(255,255,255,0.85)', flexShrink:0}}>
              <span style={{width:8, height:8, borderRadius:100, border:'1.5px solid rgba(255,255,255,0.7)'}}/>
              Autoguardado: desactivado
            </span>
            <div style={{flex:1, textAlign:'center', fontSize:12.5, color:'#fff', fontWeight:500, overflow:'hidden', whiteSpace:'nowrap'}}>pistas_partidas_FINAL_v3(2).xlsx — Sin guardar</div>
            <div style={{display:'flex', alignSelf:'stretch', flexShrink:0}}>
              <div style={{width:38, display:'flex', alignItems:'center', justifyContent:'center'}}><svg width="10" height="10" viewBox="0 0 10 10"><path d="M0 5 H10" stroke="#fff" strokeWidth="1"/></svg></div>
              <div style={{width:38, display:'flex', alignItems:'center', justifyContent:'center'}}><svg width="10" height="10" viewBox="0 0 10 10"><rect x="0.5" y="0.5" width="9" height="9" fill="none" stroke="#fff" strokeWidth="1"/></svg></div>
              <div style={{width:38, display:'flex', alignItems:'center', justifyContent:'center'}}><svg width="10" height="10" viewBox="0 0 10 10"><path d="M0 0 L10 10 M10 0 L0 10" stroke="#fff" strokeWidth="1"/></svg></div>
            </div>
          </div>

          {/* Ribbon */}
          <div style={{height:32, background:'#F3F2F1', display:'flex', alignItems:'center', padding:'0 12px', gap:16, borderBottom:'1px solid #E1DFDD', fontSize:12, color:'#444'}}>
            <span style={{background:'#107C41', color:'#fff', padding:'3px 12px', borderRadius:3, fontWeight:600}}>Archivo</span>
            {['Inicio','Insertar','Disposición','Fórmulas','Datos','Revisar','Vista'].map((tab,i)=>(
              <span key={i} style={i===0 ? {fontWeight:700, color:'#107C41', borderBottom:'2.5px solid #107C41', paddingBottom:3, marginBottom:-5} : {}}>{tab}</span>
            ))}
          </div>

          {/* Barra de fórmulas — al seleccionar E9 se ve que el total está escrito a mano: "96" */}
          <div style={{height:28, background:'#fff', display:'flex', alignItems:'center', borderBottom:'1px solid #E1DFDD'}}>
            <div className="f-mono" style={{width:72, alignSelf:'stretch', display:'flex', alignItems:'center', justifyContent:'center', borderRight:'1px solid #E1DFDD', fontSize:11.5, color:'#444'}}>{totalSel ? 'E9' : 'A1'}</div>
            <div style={{width:34, textAlign:'center', fontStyle:'italic', fontSize:12, color:'#8A8886', fontFamily:'Georgia,serif'}}>fx</div>
            <div className="f-mono" style={{fontSize:12, color:'#202124'}}>{totalSel ? '96' : ''}</div>
          </div>

          {/* Letras de columna */}
          <div style={{display:'grid', gridTemplateColumns:COLS, height:22, background:'#F7F8FA', borderBottom:'1px solid #D9DCE1', fontSize:11, color:'#666'}}>
            <div style={{borderRight:'1px solid #D9DCE1'}}/>
            {['A','B','C','D','E','F'].map((ltr,i)=>(
              <div key={i} style={{display:'flex', alignItems:'center', justifyContent:'center', borderRight:'1px solid #D9DCE1', background: ltr==='E' && totalSel ? '#D6E9DC' : 'transparent', color: ltr==='E' && totalSel ? '#0B6B37' : '#666', fontWeight: ltr==='E' && totalSel ? 700 : 400}}>{ltr}</div>
            ))}
          </div>

          {/* Fila 1 — cabeceras que pintó el usuario */}
          <div style={{display:'grid', gridTemplateColumns:COLS, height:44, opacity:headP}}>
            <div style={numCell}>1</div>
            {['Jugador','Pista','Hora','Ticket','Total',''].map((lbl,i)=>(
              <div key={i} style={{...cellBase, background:'#DDEBF7', fontWeight:700, color:'#1F3864', justifyContent: i===4 ? 'flex-end' : 'flex-start'}}>{lbl}</div>
            ))}
          </div>

          {/* Filas 2-7 — datos */}
          {rows.map((r,i)=>{
            const rp = clamp((t-(rowsAt+i*0.24))/0.4, 0, 1);
            const re = Easing.easeOutCubic(rp);
            const rowBg = fill(r.fillRow, 112, 173, 71);
            const esRef = r.refTot !== undefined && t >= r.refTot;
            const esNd  = r.ndHora !== undefined && t >= r.ndHora;
            return (
              <div key={i} style={{display:'grid', gridTemplateColumns:COLS, height:44, opacity:rp, transform:`translateY(${(1-re)*6}px)`}}>
                <div style={numCell}>{i+2}</div>
                <div style={{...cellBase, background:rowBg}}>{r.j}</div>
                <div style={{...cellBase, background:rowBg}}>{r.p}</div>
                <div style={{...cellBase, background: esNd ? fill(r.ndHora, 220, 38, 38) : rowBg, color: esNd ? '#C00000' : '#202124', fontWeight: esNd ? 700 : 400}}>{esNd ? '#N/D' : r.h}</div>
                <div className="f-mono" style={{...cellBase, fontSize:12.5, background: r.fillTk !== undefined ? fill(r.fillTk, 237, 125, 49) : rowBg}}>{r.tk}</div>
                <div style={{...cellBase, justifyContent:'flex-end', background: esRef ? fill(r.refTot, 220, 38, 38) : rowBg, color: esRef ? '#C00000' : '#202124', fontWeight: esRef ? 700 : 400}}>{esRef ? '#¡REF!' : r.tot}</div>
                <div style={{...cellBase, background:rowBg}}>
                  {r.nota && t >= notaAt && (()=>{
                    const np = clamp((t-notaAt)/0.4, 0, 1);
                    return <span style={{color:'#DC2626', fontStyle:'italic', fontWeight:600, fontSize:13, transform:`rotate(-1.2deg) scale(${lerp(1.15,1,Easing.easeOutCubic(np))})`, opacity:np, display:'inline-block'}}>{r.nota}</span>;
                  })()}
                </div>
              </div>
            );
          })}

          {/* Fila 8 — vacía */}
          <div style={{display:'grid', gridTemplateColumns:COLS, height:44}}>
            <div style={numCell}>8</div>
            {[0,1,2,3,4,5].map(i=><div key={i} style={cellBase}/>)}
          </div>

          {/* Fila 9 — TOTAL que no cuadra (12+18+24+6+12 no dan 96 ni de lejos) */}
          <div style={{display:'grid', gridTemplateColumns:COLS, height:44, opacity:totP}}>
            <div style={{...numCell, background: totalSel ? '#D6E9DC' : '#F5F6F8', color: totalSel ? '#0B6B37' : '#7A8089', fontWeight: totalSel ? 700 : 400}}>9</div>
            <div style={cellBase}/>
            <div style={cellBase}/>
            <div style={cellBase}/>
            <div style={{...cellBase, justifyContent:'flex-end', fontWeight:700}}>TOTAL</div>
            <div style={{...cellBase, justifyContent:'flex-end', fontWeight:700, background: totalSel ? '#FFF2CC' : 'transparent', boxShadow:totalPulse}}>96,00 €</div>
            <div style={cellBase}>
              {t >= notaTotalAt && (()=>{
                const np = clamp((t-notaTotalAt)/0.4, 0, 1);
                return <span style={{color:'#DC2626', fontStyle:'italic', fontWeight:700, fontSize:13.5, transform:'rotate(-1deg)', opacity:np, display:'inline-block'}}>&#8592; ¿¿no cuadra??</span>;
              })()}
            </div>
          </div>

          {/* Tira de relleno + pestañas de hoja */}
          <div style={{display:'grid', gridTemplateColumns:COLS, height:20, overflow:'hidden'}}>
            <div style={{...numCell, borderBottom:'none'}}>10</div>
            {[0,1,2,3,4,5].map(i=><div key={i} style={{...cellBase, borderBottom:'none'}}/>)}
          </div>
          <div style={{height:26, background:'#F3F2F1', borderTop:'1px solid #D9DCE1', display:'flex', alignItems:'stretch', fontSize:11, color:'#555'}}>
            <div style={{display:'flex', alignItems:'center', padding:'0 14px', background:'#fff', borderTop:'2px solid #107C41', color:'#107C41', fontWeight:700, borderRight:'1px solid #D9DCE1'}}>Hoja1</div>
            <div style={{display:'flex', alignItems:'center', padding:'0 14px', borderRight:'1px solid #D9DCE1'}}>Hoja1 (2)</div>
            <div style={{display:'flex', alignItems:'center', padding:'0 14px', borderRight:'1px solid #D9DCE1'}}>antigua NO TOCAR</div>
            <div style={{display:'flex', alignItems:'center', padding:'0 12px', color:'#999', fontSize:14}}>+</div>
            <div style={{flex:1}}/>
            <div style={{display:'flex', alignItems:'center', padding:'0 14px', color:'#777'}}>Listo</div>
          </div>
        </div>

        {/* Badges de dolor — pegados a la ventana, viajan con ella */}
        {badges.map((b,i)=>{
          const p = clamp((t-b.at)/0.5, 0, 1);
          const e = Easing.easeOutBack(p);
          if (p === 0) return null;
          return (
            <div key={i} style={{position:'absolute', zIndex:4, ...b.style, opacity:clamp(p*1.3,0,1)}}>
              <span className="f-plex" style={{display:'inline-flex', alignItems:'center', gap:9, padding:'11px 18px', background:'#FEF2F2', border:'1px solid #FECACA', borderRadius:100, color:'#B91C1C', fontSize:16, fontWeight:700, whiteSpace:'nowrap', boxShadow:'0 10px 28px rgba(220,38,38,0.16)', transform:`scale(${lerp(0.6,1,e)})`}}>
                {b.icon}
                {b.txt}
              </span>
            </div>
          );
        })}
      </div>

      {/* ===== GIRO — Dinaup entra nítido a la derecha ===== */}
      {t >= arrowAt && (
        <svg width="320" height="160" viewBox="0 0 320 160" fill="none" style={{position:'absolute', left:870, top:360, zIndex:3, overflow:'visible'}}>
          <path d="M 14 146 C 112 150, 192 64, 292 30" stroke="var(--dn-primary)" strokeWidth="5" strokeLinecap="round" pathLength="1" strokeDasharray="1" strokeDashoffset={1-arrowE} fill="none"/>
          <path d="M 299 28 L 280.6 42.6 L 275.4 27.4 Z" fill="var(--dn-primary)" opacity={clamp((arrowP-0.85)/0.15, 0, 1)}/>
        </svg>
      )}

      <div style={{position:'absolute', left:970, top:0, width:810, height:1080, zIndex:3, pointerEvents:'none'}}>
        {/* Logo Dinaup */}
        {t >= logoAt && (
          <div style={{position:'absolute', top:296, left:0, right:0, display:'flex', justifyContent:'center', opacity:clamp(logoP*1.2,0,1), transform:`scale(${lerp(0.7,1,logoE)})`}}>
            <DinaupLogo size={58}/>
          </div>
        )}
        {/* La frase del giro */}
        {t >= fraseAt && (
          <div className="f-plex" style={{position:'absolute', top:462, left:0, right:0, textAlign:'center', fontSize:46, fontWeight:700, letterSpacing:'-0.03em', lineHeight:1.22, color:'#0F172A', opacity:fraseE, transform:`translateY(${(1-fraseE)*18}px)`}}>
            La potencia de un Excel,<br/>llevada a <span className="grad-text">un ERP</span>.
          </div>
        )}
        {/* Sello verde */}
        {t >= verdeAt && (
          <div className="f-plex" style={{position:'absolute', top:626, left:0, right:0, display:'flex', alignItems:'center', justifyContent:'center', gap:12, fontSize:30, fontWeight:700, color:'#059669', opacity:verdeE, transform:`translateY(${(1-verdeE)*12}px)`}}>
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" style={{flexShrink:0}}>
              <circle cx="12" cy="12" r="9.2" stroke="#059669" strokeWidth="1.8"/>
              <path d="M8 12.2 L10.8 15 L16 9.5" stroke="#059669" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            Mismo control. Cero caos.
          </div>
        )}
      </div>

      <SocialCaption t={t} cues={CAPTIONS.slide_flexexcel}/>
    </SlideCanvas>
  );
}

Object.assign(window, { SlideFlexExcel });
