// === Escena 06 — "Límites + eco" ===
// Tres límites dichos en voz alta, cada uno con su prueba en pantalla:
//   1. Los seis marcadores son de toda la empresa (Dashboard:210-223); «Mi día» pide solo los
//      eventos del usuario de la sesión (:291 → Eventos.vb:33-37).
//   2. Todo se calcula una vez en OnInitializedAsync (:201-263): sin Tick ni monitorización en las
//      313 líneas. Y si la carga falla, el catch solo notifica (:259): el marcado del panel caído
//      es idéntico al del panel vacío.
//   3. «Estancada» mide desde el último cambio de estado O de fase (:232, Tarjeta:17): cambiarle
//      el estado la saca de la lista sin moverla de columna.
// Cierra con el ECO de La Única Cosa, bookend con la escena 1.
function EscenaPN06({ t }){
  // LOCUCIÓN (audio/escena-06.mp3): tres cosas en voz alta → pausa → toda la empresa / tu día no →
  // de cuando abriste → se calculan una vez → nadie te avisa → el aviso se desvanece → caído igual
  // que vacío → parada no es parada en su fase → estado o fase → sin moverse de columna → ECO.
  const T = {
    tres:0.3,        // "Tres cosas, en voz alta" -> fondo sobrio; tres huecos numerados
    empresa:7.0,     // "son de toda la empresa" -> límite 1: los seis abarcan a los tres comerciales
    tusEventos:10.1, // "solo trae tus eventos" -> «Mi día» se recorta a una sola cara
    abriste:14.6,    // "de cuando abriste" -> límite 2: el reloj congelado sobre el panel
    unaVez:16.0,     // "Se calculan una vez" -> un solo latido, y se para
    avisa:19.5,      // "nadie te avisa" -> campana tachada
    desvanece:21.9,  // "el aviso se desvanece solo" -> la notificación entra y se va
    desvaneceDur:0.6, // (lo que la notificación aguanta en pantalla)
    igual:25.3,      // "se ve igual que uno vacío" -> panel vacío y panel caído, idénticos
    fase:28.8,       // "parada no es parada en su fase" -> límite 3: dos relojes distintos
    cambio:31.7,     // "último cambio de estado o de fase" -> los dos relojes se funden en uno
    columna:36.2,    // "sin moverse de columna" -> cambia el estado y sale de la lista, quieta
    unica1:39.3,     // "dos traen lista" -> ECO mitad 1 (bookend con la escena 1)
    unica2:40.9,     // "Esa lista es el trabajo de hoy" -> ECO mitad 2 + logo; pantalla fija
  };

  const COLX = [80, 680, 1280], COLW = 560;

  const Ico = ({ n, s=24, c='#0F172A', w=2 })=>{
    const P = {
      today:<><rect x="3" y="5" width="18" height="16" rx="2.5"/><path d="M3 10 H21"/><path d="M8 3 V7 M16 3 V7"/></>,
      bell:<><path d="M6 10 A6 6 0 0 1 18 10 C18 15, 19.6 16.6, 19.6 16.6 H4.4 C4.4 16.6, 6 15, 6 10 Z"/><path d="M10 19.4 A2.2 2.2 0 0 0 14 19.4"/></>,
      warning:<><path d="M12 3.6 L21.4 19.6 H2.6 Z"/><path d="M12 9.6 V14"/><circle cx="12" cy="16.9" r="0.9" fill={c} stroke="none"/></>,
      user:<><circle cx="12" cy="8.4" r="3.8"/><path d="M4.8 19.4 C 5.8 15.6, 8.6 14, 12 14 C 15.4 14, 18.2 15.6, 19.2 19.4"/></>,
      layers:<><path d="M12 3 L21 8 L12 13 L3 8 Z"/><path d="M3 12.5 L12 17.5 L21 12.5"/></>,
    };
    return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round">{P[n]}</svg>;
  };

  // Reloj de esfera con las agujas quietas (el panel no vuelve a mirar la hora)
  const Reloj = ({ s=110, c='#64748B', hh=9, mm=14 })=>{
    const ah = ((hh%12)/12 + mm/720)*2*Math.PI - Math.PI/2;
    const am = (mm/60)*2*Math.PI - Math.PI/2;
    return (
      <svg width={s} height={s} viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="44" fill="#fff" stroke={c} strokeWidth="4"/>
        {[0,1,2,3,4,5,6,7,8,9,10,11].map(i=>{
          const a = i/12*2*Math.PI - Math.PI/2;
          return <circle key={i} cx={50+Math.cos(a)*35} cy={50+Math.sin(a)*35} r="1.9" fill={c} opacity="0.5"/>;
        })}
        <path d={`M50 50 L${50+Math.cos(ah)*20} ${50+Math.sin(ah)*20}`} stroke={c} strokeWidth="5.5" strokeLinecap="round"/>
        <path d={`M50 50 L${50+Math.cos(am)*30} ${50+Math.sin(am)*30}`} stroke={c} strokeWidth="4" strokeLinecap="round"/>
        <circle cx="50" cy="50" r="4" fill={c}/>
      </svg>
    );
  };

  // ── Progresos ──
  const trP = clamp((t-T.tres)/0.7,0,1);
  const c1P = clamp((t-T.empresa)/0.7,0,1), c1E = Easing.easeOutBack(c1P);
  const carasP = clamp((t-T.tusEventos)/0.6,0,1);
  const carasTacha = Easing.easeInOutCubic(clamp((t-T.tusEventos-0.25)/0.6,0,1));
  const c2P = clamp((t-T.abriste)/0.7,0,1), c2E = Easing.easeOutBack(c2P);
  const latido = clamp((t-T.unaVez)/1.1,0,1);
  const belP = clamp((t-T.avisa)/0.5,0,1);
  const belTacha = Easing.easeInOutCubic(clamp((t-T.avisa-0.2)/0.5,0,1));
  const toastIn  = clamp((t-T.desvanece)/0.2,0,1);
  const toastOut = clamp((t-T.desvanece-T.desvaneceDur)/0.35,0,1);
  const toast = clamp(toastIn - toastOut, 0, 1);
  const igP = clamp((t-T.igual)/0.65,0,1), igE = Easing.easeOutCubic(igP);
  const c3P = clamp((t-T.fase)/0.7,0,1), c3E = Easing.easeOutBack(c3P);
  const fuP = clamp((t-T.cambio)/1.0,0,1), fuE = Easing.easeInOutCubic(fuP);
  const colP = clamp((t-T.columna)/0.7,0,1), colE = Easing.easeOutCubic(colP);

  const act = [
    clamp((t-T.empresa+0.4)/0.6,0,1) * (1 - clamp((t-T.abriste+0.4)/0.6,0,1)*0.62),
    clamp((t-T.abriste+0.4)/0.6,0,1) * (1 - clamp((t-T.fase+0.4)/0.6,0,1)*0.62),
    clamp((t-T.fase+0.4)/0.6,0,1),
  ];
  const opCol = (i)=> lerp(0.30, 1, act[i]) * trP;

  const veloOp = t < T.unica1 ? 0 : clamp((t-T.unica1)/0.7,0,1)*0.95;
  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 logoP = clamp((t-T.unica2-0.9)/0.7,0,1), logoE = Easing.easeOutCubic(logoP);

  // ── Panel en miniatura: seis marcadores a cero y el texto de vacío ──
  const MiniPanel = ({ w=268 })=>(
    <div style={{width:w, background:'#fff', border:'1px solid #E2E8F0', borderRadius:12, overflow:'hidden'}}>
      <div style={{height:22, background:'#F1F5F9', borderBottom:'1px solid #E2E8F0'}}/>
      <div style={{display:'flex', gap:7, padding:'12px 12px 0'}}>
        {['0 €','0 €','0'].map((v,i)=>(
          <div key={i} style={{flex:1, height:40, border:'1px solid #E2E8F0', borderRadius:7,
                               display:'flex', alignItems:'center', justifyContent:'center'}}>
            <span className="f-plex" style={{fontSize:17, fontWeight:800, color:'#CBD5E1'}}>{v}</span>
          </div>
        ))}
      </div>
      <div style={{display:'flex', gap:7, padding:'7px 12px 12px'}}>
        {['0','0','0'].map((v,i)=>(
          <div key={i} style={{flex:1, height:40, border:'1px solid #E2E8F0', borderRadius:7,
                               display:'flex', alignItems:'center', justifyContent:'center'}}>
            <span className="f-plex" style={{fontSize:17, fontWeight:800, color:'#CBD5E1'}}>{v}</span>
          </div>
        ))}
      </div>
      <div style={{margin:'0 12px 12px', padding:'16px 12px', background:'#FAFCFE', border:'1px solid #EEF2F6', borderRadius:8}}>
        <span className="f-plex" style={{fontSize:16, color:'#94A3B8', lineHeight:1.35}}>
          No hay oportunidades estancadas
        </span>
      </div>
    </div>
  );

  const Columna = ({ i, n, titulo, children })=>(
    <div style={{position:'absolute', left:COLX[i], top:214, width:COLW, opacity:opCol(i)}}>
      <div style={{display:'flex', alignItems:'center', gap:18}}>
        <span className="f-plex" style={{width:66, height:66, borderRadius:99, flexShrink:0,
                      border:act[i] > 0.5 ? '3px solid #0F172A' : '3px dashed #CBD5E1',
                      color:act[i] > 0.5 ? '#0F172A' : '#94A3B8', fontSize:32, fontWeight:800,
                      display:'flex', alignItems:'center', justifyContent:'center'}}>{n}</span>
        <span className="f-plex" style={{fontSize:31, fontWeight:700, color:'#0F172A', lineHeight:1.2}}>{titulo}</span>
      </div>
      <div style={{marginTop:26}}>{children}</div>
    </div>
  );

  return (
    <SlideCanvas variant="light-soft">
      <div style={{opacity:1-veloOp/0.95}}>
        <DemoHeader t={t} eyebrow="ANTES DE PROYECTARLO" title={<span>Tres límites de esta pantalla</span>}/>
      </div>

      <div style={{opacity:1-veloOp/0.95}}>
        {/* ══════ UNO · los seis son de toda la empresa; «Mi día» no ══════ */}
        <Columna i={0} n="1" titulo={<span>Toda la empresa</span>}>
          {c1P > 0.01 && (
            <div style={{opacity:clamp(c1P*1.3,0,1), transform:`translateY(${(1-c1E)*14}px)`}}>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12}}>
                {['231.700 €','103.400 €','31','7','9','12'].map((v,i)=>(
                  <div key={i} style={{height:62, background:'#fff', border:'1px solid #E2E8F0', borderRadius:10,
                                       display:'flex', alignItems:'center', justifyContent:'center'}}>
                    <span className="f-plex" style={{fontSize:24, fontWeight:800,
                          color:['#2e7d32','#1565c0','#6a1b9a','#e65100','#bf360c','#ff6f00'][i]}}>{v}</span>
                  </div>
                ))}
              </div>
              <svg width={COLW} height="40" viewBox={`0 0 ${COLW} 40`} style={{display:'block', marginTop:6}}>
                <path d={`M14 4 V22 H${COLW-14} V4`} stroke="#94A3B8" strokeWidth="3" fill="none" strokeLinecap="round"/>
                <path d={`M${COLW/2} 22 V36`} stroke="#94A3B8" strokeWidth="3" strokeLinecap="round"/>
              </svg>
              <div style={{display:'flex', justifyContent:'center', gap:20, marginTop:6}}>
                {[['SL','Sergio'],['NP','Nuria'],['IC','Iván']].map(c=>(
                  <div key={c[0]} style={{textAlign:'center'}}>
                    <span className="f-plex" style={{width:56, height:56, borderRadius:99, display:'flex', alignItems:'center', justifyContent:'center',
                                  background:'linear-gradient(135deg,#0085FF,#56E16A)', color:'#fff', fontSize:20, fontWeight:700}}>{c[0]}</span>
                    <div className="f-plex" style={{fontSize:19, color:'#64748B', marginTop:7}}>{c[1]}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {carasP > 0.01 && (
            <div style={{marginTop:26, opacity:clamp(carasP*1.3,0,1)}}>
              <div style={{background:'#fff', border:'1px solid #E2E8F0', borderRadius:12, padding:'18px 20px'}}>
                <div style={{display:'flex', alignItems:'center', gap:11}}>
                  <Ico n="today" s={24} c="#0F172A" w={2}/>
                  <span className="f-plex" style={{fontSize:25, fontWeight:700, color:'#0F172A'}}>Mi día</span>
                  <div style={{flex:1}}/>
                  {[['SL',false],['NP',true],['IC',false]].map(c=>(
                    <span key={c[0]} style={{position:'relative', marginLeft:10}}>
                      <span className="f-plex" style={{width:44, height:44, borderRadius:99, display:'flex', alignItems:'center', justifyContent:'center',
                                    background:c[1] ? 'linear-gradient(135deg,#0085FF,#56E16A)' : '#E2E8F0',
                                    color:c[1] ? '#fff' : '#94A3B8', fontSize:17, fontWeight:700,
                                    filter:c[1] ? 'none' : `grayscale(1)`, opacity:c[1] ? 1 : lerp(1, 0.75, carasTacha)}}>{c[0]}</span>
                      {c[1] === false && (
                        <span style={{position:'absolute', left:2, right:2, top:'50%', height:3, borderRadius:2, background:'#EF4444',
                                      transform:`scaleX(${carasTacha})`, transformOrigin:'left'}}/>
                      )}
                    </span>
                  ))}
                </div>
                <div style={{display:'flex', alignItems:'center', gap:14, marginTop:16, paddingTop:16, borderTop:'1px solid #F1F5F9'}}>
                  <span className="f-mono" style={{fontSize:21, fontWeight:600, color:'#0F172A'}}>Hoy 10:00</span>
                  <span className="f-plex" style={{fontSize:19, color:'#94A3B8'}}>45 min.</span>
                  <span className="f-plex" style={{fontSize:20, color:'#334155'}}>Envases Duero</span>
                </div>
                <div className="f-plex" style={{fontSize:21, color:'#64748B', marginTop:16}}>Solo los tuyos.</div>
              </div>
            </div>
          )}
        </Columna>

        {/* ══════ DOS · los números son de cuando abriste ══════ */}
        <Columna i={1} n="2" titulo={<span>De cuando abriste</span>}>
          {c2P > 0.01 && (
            <div style={{position:'relative', opacity:clamp(c2P*1.3,0,1), transform:`translateY(${(1-c2E)*14}px)`}}>
              <div style={{display:'flex', alignItems:'center', gap:22}}>
                <div style={{position:'relative'}}>
                  <Reloj s={118} c="#64748B"/>
                  {0 < latido && latido < 1 && (
                    <div style={{position:'absolute', left:'50%', top:'50%', width:118, height:118, marginLeft:-59, marginTop:-59,
                                 borderRadius:99, border:'3px solid #0085FF',
                                 transform:`scale(${lerp(0.85,1.5,Easing.easeOutCubic(latido))})`, opacity:1-latido}}/>
                  )}
                </div>
                <div>
                  <div className="f-mono" style={{fontSize:34, fontWeight:700, color:'#0F172A'}}>09:14</div>
                  <div className="f-plex" style={{fontSize:22, color:'#64748B', marginTop:8, lineHeight:1.35}}>
                    Se calculan al entrar.<br/>Nada los vuelve a tocar.
                  </div>
                </div>
              </div>

              {/* Nadie te avisa, y el aviso que hay se desvanece solo */}
              <div style={{display:'flex', alignItems:'center', gap:20, marginTop:26, height:96}}>
                {belP > 0.01 && (
                  <span style={{position:'relative', opacity:clamp(belP*1.3,0,1)}}>
                    <Ico n="bell" s={58} c="#94A3B8" w={1.8}/>
                    <svg width="58" height="58" viewBox="0 0 58 58" style={{position:'absolute', left:0, top:0}}>
                      <path d="M8 50 L50 8" stroke="#EF4444" strokeWidth="4.5" strokeLinecap="round"
                            strokeDasharray="60" strokeDashoffset={60*(1-belTacha)}/>
                    </svg>
                  </span>
                )}
                {toast > 0.01 && (
                  <div style={{flex:1, display:'flex', alignItems:'center', gap:12, padding:'14px 16px',
                               background:'#fff', border:'1px solid #E2E8F0', borderLeft:'5px solid #EF4444', borderRadius:10,
                               boxShadow:'0 12px 30px rgba(15,23,42,0.14)',
                               opacity:toast, transform:`translateX(${(1-toast)*24}px)`}}>
                    <Ico n="warning" s={26} c="#EF4444" w={2.1}/>
                    <div style={{flex:1}}>
                      <div style={{width:'70%', height:12, borderRadius:4, background:'#EEF2F6'}}/>
                      <div style={{width:'45%', height:10, borderRadius:4, background:'#F4F7FA', marginTop:8}}/>
                    </div>
                  </div>
                )}
              </div>

              {/* Panel vacío y panel caído: el mismo marcado */}
              {igP > 0.01 && (
                <div style={{marginTop:10, opacity:clamp(igP*1.3,0,1), transform:`translateY(${(1-igE)*14}px)`}}>
                  <div style={{display:'flex', gap:24}}>
                    {['SIN DATOS','LA CARGA FALLÓ'].map(l=>(
                      <div key={l}>
                        <div className="f-plex" style={{fontSize:19, fontWeight:700, letterSpacing:'1.6px', color:'#94A3B8', marginBottom:9}}>{l}</div>
                        <MiniPanel/>
                      </div>
                    ))}
                  </div>
                  <div className="f-plex" style={{fontSize:23, fontWeight:600, color:'#0F172A', marginTop:16}}>
                    El mismo marcado. No se distinguen.
                  </div>
                </div>
              )}
            </div>
          )}
        </Columna>

        {/* ══════ TRES · parada no es parada en su fase ══════ */}
        <Columna i={2} n="3" titulo={<span>Estado o fase</span>}>
          {c3P > 0.01 && (
            <div style={{opacity:clamp(c3P*1.3,0,1), transform:`translateY(${(1-c3E)*14}px)`}}>
              <div style={{position:'relative', height:170}}>
                <div style={{position:'absolute', left:lerp(58, 225, fuE), top:0, textAlign:'center', width:110}}>
                  <Reloj s={110} c="#bf360c" hh={4} mm={40}/>
                  <div className="f-plex" style={{fontSize:22, fontWeight:700, color:'#bf360c', marginTop:8, opacity:1-fuE}}>Estado</div>
                </div>
                <div style={{position:'absolute', left:lerp(392, 225, fuE), top:0, textAlign:'center', width:110,
                             opacity:1-clamp((fuP-0.6)/0.4,0,1)}}>
                  <Reloj s={110} c="#e65100" hh={4} mm={40}/>
                  <div className="f-plex" style={{fontSize:22, fontWeight:700, color:'#e65100', marginTop:8, opacity:1-fuE}}>Fase</div>
                </div>
                <div style={{position:'absolute', left:0, right:0, top:126, textAlign:'center',
                             opacity:clamp((fuP-0.65)/0.35,0,1)}}>
                  <span className="f-plex" style={{fontSize:23, fontWeight:700, color:'#bf360c'}}>último cambio de estado o de fase</span>
                </div>
              </div>

              {/* La tarjeta cambia de estado y sale de la lista sin moverse de columna */}
              <div style={{display:'flex', gap:20, marginTop:20}}>
                <div style={{width:300}}>
                  <div className="f-plex" style={{fontSize:19, fontWeight:700, letterSpacing:'1.5px', color:'#94A3B8', marginBottom:10}}>NEGOCIACIÓN</div>
                  <div style={{position:'relative', background:'#fff', borderRadius:10, borderLeft:'4px solid #0288d1',
                               border:'1px solid #E2E8F0', borderLeftWidth:4, borderLeftColor:'#0288d1',
                               padding:'14px 16px', boxShadow:'0 8px 22px rgba(15,23,42,0.09)'}}>
                    <div style={{position:'absolute', right:0, top:0, bottom:0, width:3, background:'#e65100', opacity:1-colE}}/>
                    <div className="f-plex" style={{fontSize:20, fontWeight:700, color:'#0F172A', lineHeight:1.25}}>Suministro anual<br/>Envases Duero</div>
                    <div style={{display:'flex', alignItems:'center', gap:10, marginTop:12}}>
                      <span className="f-plex" style={{fontSize:17, fontWeight:600, borderRadius:99, padding:'4px 12px',
                                    color:colP > 0.35 ? '#1565c0' : '#64748B',
                                    background:colP > 0.35 ? 'rgba(21,101,192,0.12)' : '#F1F5F9',
                                    boxShadow:colP > 0.05 && colP < 0.8 ? `0 0 ${(1-Math.abs(colP-0.4)*2.5)*20}px rgba(21,101,192,0.6)` : 'none'}}>
                        {colP > 0.35 ? 'Revisión' : 'Propuesta'}
                      </span>
                    </div>
                    <div style={{display:'flex', alignItems:'center', gap:8, marginTop:12, opacity:1-colE, height:22}}>
                      <Ico n="warning" s={18} c="#e65100" w={2.2}/>
                      <span className="f-plex" style={{fontSize:18, fontWeight:700, color:'#e65100'}}>Estancada 23 días</span>
                    </div>
                  </div>
                  <div className="f-plex" style={{fontSize:20, color:'#64748B', marginTop:14}}>No se ha movido.</div>
                </div>
                <div style={{flex:1}}>
                  <div className="f-plex" style={{fontSize:19, fontWeight:700, letterSpacing:'1.5px', color:'#94A3B8', marginBottom:10}}>ESTANCADAS</div>
                  <div style={{background:'#fff', border:'1px solid #E2E8F0', borderRadius:10, overflow:'hidden'}}>
                    {[['Suministro anual - Envases Duero', true],['Segunda línea - Áridos Sil', false],['Mantenimiento anual', false]].map((r,i)=>(
                      <div key={r[0]} style={{padding:'12px 14px', borderBottom:i < 2 ? '1px solid #F1F5F9' : 'none',
                                              height:r[1] ? lerp(58, 0, colE) : 58, overflow:'hidden',
                                              opacity:r[1] ? 1-colE : 1}}>
                        <div className="f-plex" style={{fontSize:18, color:'#0F172A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{r[0]}</div>
                        <div className="f-plex" style={{fontSize:15, color:'#e65100', marginTop:3}}>Sin cambios hace {[23,21,19][i]} días</div>
                      </div>
                    ))}
                  </div>
                  <div className="f-plex" style={{fontSize:20, color:'#0F172A', fontWeight:600, marginTop:14, opacity:colE}}>
                    Y ha salido de la lista.
                  </div>
                </div>
              </div>
            </div>
          )}
        </Columna>
      </div>

      {/* ─────────── El ECO ─────────── */}
      {veloOp > 0 && <div style={{position:'absolute', inset:0, background:'#fff', opacity:veloOp}}/>}
      {u1P > 0 && (
        <div className="f-plex" style={{position:'absolute', left:0, right:0, top:390, textAlign:'center', fontSize:74, fontWeight:800,
                                        letterSpacing:'-0.03em', color:'#0F172A', opacity:u1E, transform:`translateY(${(1-u1E)*18}px)`}}>
          De los seis números, dos traen lista.
        </div>
      )}
      {u2P > 0 && (
        <div className="f-plex" style={{position:'absolute', left:0, right:0, top:504, textAlign:'center', fontSize:74, fontWeight:800,
                                        letterSpacing:'-0.03em', opacity:u2E, transform:`translateY(${(1-u2E)*18}px)`}}>
          <span className="grad-text">Esa lista es el trabajo de hoy.</span>
        </div>
      )}
      {logoP > 0 && (
        <div style={{position:'absolute', left:0, right:0, top:700, display:'flex', justifyContent:'center',
                     opacity:logoE, transform:`translateY(${(1-logoE)*12}px)`}}>
          <DinaupLogo size={44}/>
        </div>
      )}
    </SlideCanvas>
  );
}
Object.assign(window, { EscenaPN06 });
