// === Slide Caos (10s) — siete ventanas desordenadas colapsan en una ===
// 0.0-4.6 : las 7 ventanas del día a día caen en cascada, giradas, apilándose.
// 5.0-6.2 : tiemblan, y se absorben hacia el centro.
// 6.2-10  : aparece UNA ventana Dinaup limpia que lo recoge todo.

function SlideCaos({ t }){
  const wins = [
    { title:'Stock_FINAL_v3.xlsx', icon:'📊', accent:'#1D6F42', sub:'Modificado hace 41 días\n⚠ Otro usuario tiene el archivo abierto', x:200,  y:270, w:470, rot:-5, at:0.5 },
    { title:'RE: RE: RE: factura adjunta', icon:'✉️', accent:'#0F6CBD', sub:'Bandeja de entrada: 47 sin leer\n«te la reenvío otra vez, no llegó»', x:1260, y:250, w:480, rot:4,  at:1.0 },
    { title:'Grupo Turnos', icon:'💬', accent:'#25D366', sub:'99+ mensajes\n«¿quién cierra hoy? 🙏🙏»', x:330,  y:570, w:440, rot:6,  at:1.5 },
    { title:'TPV (no responde)', icon:'🖥️', accent:'#64748B', sub:'Esperando al programa…\nÚltimo cierre de caja: descuadre −5 €', x:1250, y:560, w:460, rot:-4, at:2.0 },
    { title:'Facturas para gestoría', icon:'📁', accent:'#E8A82A', sub:'231 elementos · sin ordenar\n«factura_escaneada_(23).pdf»', x:650,  y:340, w:460, rot:-2, at:2.5 },
    { title:'pendientes_DEFINITIVO.txt', icon:'📝', accent:'#94A3B8', sub:'— llamar al banco\n— ¡¡IVA antes del 20!!\n— nóminas el viernes', x:790,  y:590, w:410, rot:3,  at:3.0 },
    { title:'Banca online', icon:'🏦', accent:'#DC2626', sub:'Sesión caducada.\nVuelve a identificarte para ver tus movimientos.', x:690,  y:165, w:430, rot:2,  at:3.5 },
  ];

  const collapseAt = 5.2;
  const dinaupAt   = 6.4;
  const cx = 960, cy = 560;

  const titleP = clamp(t/0.6, 0, 1);
  const titleSwap = t >= dinaupAt;

  return (
    <SlideCanvas variant={titleSwap ? 'promise' : 'problem'}>
      {/* Header */}
      <div style={{position:'absolute',top:56,left:0,right:0,textAlign:'center',opacity:titleP,zIndex:25}}>
        <div className="f-plex" style={{fontSize:14,fontWeight:600,letterSpacing:'2px',color: titleSwap ? '#059669' : '#DC2626'}}>
          {titleSwap ? 'Y ASÍ EMPIEZA HOY' : 'EL DÍA A DÍA, HASTA HOY'}
        </div>
        <h2 className="f-plex" style={{fontSize:52,fontWeight:700,letterSpacing:'-0.03em',margin:'14px 0 0',color:'#0F172A'}}>
          {titleSwap
            ? <>Una pestaña. <span className="grad-text">Todo dentro.</span></>
            : <>Siete ventanas. <span style={{color:'#DC2626'}}>Ninguna habla con la otra.</span></>}
        </h2>
      </div>

      {/* Ventanas caóticas */}
      {wins.map((w,i)=>{
        const inP = clamp((t - w.at)/0.5, 0, 1);
        const inE = Easing.easeOutBack(inP);
        // Temblor previo al colapso
        const shake = t > collapseAt - 0.6 && t < collapseAt ? Math.sin(t*40 + i)*2.2 : 0;
        // Colapso: cada ventana viaja al centro y se encoge
        const colP = clamp((t - collapseAt - i*0.07)/0.55, 0, 1);
        const colE = Easing.easeInCubic(colP);
        const x = lerp(w.x, cx - w.w/2, colE);
        const y = lerp(w.y, cy - 60, colE);
        const sc = lerp(lerp(0.85, 1, inE), 0.05, colE);
        const op = Math.min(clamp(inP*1.2,0,1), 1 - colE);
        if (op <= 0) return null;
        return (
          <div key={i} style={{
            position:'absolute', left:x + shake, top:y, width:w.w, zIndex:10+i,
            transform:`rotate(${lerp(w.rot, 0, colE)}deg) scale(${sc})`,
            transformOrigin:'center center',
            opacity:op,
            background:'#fff', borderRadius:10, overflow:'hidden',
            border:'1px solid #D7DDE6',
            boxShadow:'0 24px 60px rgba(15,23,42,0.22)',
          }}>
            {/* Barra de título genérica */}
            <div style={{height:34,background:'#F1F3F6',borderBottom:'1px solid #E2E6EC',display:'flex',alignItems:'center',padding:'0 12px',gap:9}}>
              <span style={{fontSize:13}}>{w.icon}</span>
              <span className="f-plex" style={{flex:1,fontSize:12,fontWeight:600,color:'#1F2937',overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}}>{w.title}</span>
              <span style={{display:'flex',gap:6,color:'#64748B',fontSize:10}}>
                <span>—</span><span>□</span><span style={{color:'#DC2626'}}>✕</span>
              </span>
            </div>
            <div style={{padding:'16px 18px',borderLeft:`3px solid ${w.accent}`}}>
              <div className="f-mono" style={{fontSize:12,color:'#64748B',whiteSpace:'pre-line',lineHeight:1.7}}>{w.sub}</div>
            </div>
          </div>
        );
      })}

      {/* Destello en el punto de absorción */}
      {t >= collapseAt + 0.4 && t < dinaupAt + 0.3 && (()=>{
        const p = clamp((t - collapseAt - 0.4)/0.8, 0, 1);
        return (
          <div style={{position:'absolute', left:cx, top:cy, transform:'translate(-50%,-50%)', width:lerp(20,260,Easing.easeOutCubic(p)), height:lerp(20,260,Easing.easeOutCubic(p)), borderRadius:'100%', background:'radial-gradient(circle, rgba(0,133,255,0.35), transparent 70%)', opacity:1-p, zIndex:20}}/>
        );
      })()}

      {/* Ventana Dinaup única */}
      {t >= dinaupAt && (()=>{
        const p = clamp((t - dinaupAt)/0.7, 0, 1);
        const e = Easing.easeOutBack(p);
        const items = [
          { i:'📥', l:'Facturas',  s:'129 leídas' },
          { i:'🏦', l:'Banco',     s:'conciliado' },
          { i:'🤝', l:'Ventas',    s:'pipeline al día' },
          { i:'👥', l:'Equipo',    s:'fichado' },
          { i:'🛒', l:'Local',     s:'vendiendo' },
          { i:'📒', l:'Asientos',  s:'cuadrados' },
        ];
        return (
          <div style={{
            position:'absolute', left:cx-380, top:360, width:760, zIndex:22,
            opacity:clamp(p*1.2,0,1), transform:`scale(${lerp(0.7,1,e)})`,
            background:'#fff', borderRadius:14, overflow:'hidden',
            border:'1px solid #E2E8F0',
            boxShadow:'0 40px 100px rgba(0,133,255,0.22), 0 10px 26px rgba(15,23,42,0.10)',
          }}>
            <BrowserChrome url="play.dinaup.com/App" title="Dinaup — Tu empresa"/>
            <DinaupAppHeader breadcrumb={["Inicio"]}/>
            <div style={{padding:'22px 26px',background:'#F8FAFC',display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:12}}>
              {items.map((it,j)=>{
                const ip = clamp((t - dinaupAt - 1.4 - j*0.12)/0.4, 0, 1);
                const ie = Easing.easeOutBack(ip);
                return (
                  <div key={j} style={{display:'flex',alignItems:'center',gap:11,padding:'13px 14px',background:'#fff',border:'1px solid #E2E8F0',borderRadius:10,opacity:clamp(ip*1.3,0,1),transform:`scale(${lerp(0.8,1,ie)})`}}>
                    <span style={{fontSize:20}}>{it.i}</span>
                    <div>
                      <div className="f-plex" style={{fontSize:13,fontWeight:700,color:'#0F172A'}}>{it.l}</div>
                      <div style={{fontSize:11,color:'#059669',fontWeight:600}}>✓ {it.s}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

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

Object.assign(window, { SlideCaos });
