// === Escena 03 — "Cierre Este Mes" (VALLE) ===
// La lista fácil: fecha estimada dentro del mes en curso, ordenada por esa fecha (Dashboard:226-229).
// Importe solo si es mayor que cero (:86) e insignia solo si hay probabilidad (:90) — las dos filas
// incompletas están ahí para probarlo. El marcador cuenta las 7; la lista enseña 5 y pagina (:78).
// El estado vacío entra POR SUSTITUCIÓN: es la otra rama del if (Dashboard:76 / :99).
function EscenaPN03({ t }){
  // LOCUCIÓN (audio/escena-03.mp3): la primera de las dos listas → cierre este mes → dentro del mes
  // en curso → lo más cerca arriba → pausa → título y fecha → importe en verde → la insignia →
  // el número las cuenta todas → cinco y pagina → no se queda muda → calendario / silencio.
  const T = {
    entra:0.3,       // "La primera de las dos listas" -> la tarjeta «Cierre Este Mes» al frente
    cabecera:2.9,    // "Cierre este mes" -> cabecera + icono event_upcoming
    mes:7.2,         // "cae dentro del mes en curso" -> calendario de agosto, sombreado entero
    cerca:9.4,       // "Lo más cerca, arriba" -> los 5 días se encienden y baja la flecha
    diaStep:0.13,     // (incremento entre los 5 días que se encienden)
    filas:12.7,      // "su título y su fecha" -> las 5 filas entran en cascada
    filaStep:0.14,    // (incremento de la cascada de filas)
    importes:14.4,   // "el importe en verde" -> los importes aterrizan; Áridos Sil se queda vacía
    insignias:17.1,  // "La insignia del porcentaje" -> las insignias; Metalúrgica Bierzo no llega
    cuentaTodas:22.9,// "las cuenta todas" -> halo sobre el 7 de la píldora
    pagina:25.1,     // "te enseña cinco y pagina" -> foco en el paginador
    vacio:29.0,      // "no se queda muda" -> la lista SE SUSTITUYE por el texto de vacío
    vacioDur:1.15,    // (cuánto dura la sustitución antes de que vuelva la lista)
    calendario:30.8, // "Esa te la marca el calendario" -> sello de calendario sobre la tarjeta
    silencio:32.9,   // "La otra te la marca el silencio" -> se atenúa; entra la de estancadas
  };

  const PX = [110, 475, 840, 1066, 1358, 1594];
  const PW = [345, 345, 206,  272,  216,  216];
  const PILLS = [
    { k:'payments',       tit:'Pipeline Total',  col:'#2e7d32', val:'231.700 €' },
    { k:'balance',        tit:'Ponderado',       col:'#1565c0', val:'103.400 €' },
    { k:'handshake',      tit:'Abiertas',        col:'#6a1b9a', val:'31' },
    { k:'event_upcoming', tit:'Cierre Este Mes', col:'#e65100', val:'7' },
    { k:'warning',        tit:'Estancadas',      col:'#bf360c', val:'9' },
    { k:'event_busy',     tit:'Sin evento',      col:'#ff6f00', val:'12' },
  ];

  const CIERRE = [
    { tit:'Reforma de nave - Talleres Ordás',       cap:'Cierre: 18/08/2026', imp:'21.500 €', pct:'70%' },
    { tit:'Ampliación de línea - Cerámicas Vall',   cap:'Cierre: 21/08/2026', imp:'12.900 €', pct:'50%' },
    { tit:'Lote de repuestos - Metalúrgica Bierzo', cap:'Cierre: 25/08/2026', imp:'6.400 €',  pct:null  },
    { tit:'Renovación de contrato - Áridos Sil',    cap:'Cierre: 27/08/2026', imp:null,       pct:'40%' },
    { tit:'Cambio de bombas - Envases Duero',       cap:'Cierre: 29/08/2026', imp:'9.800 €',  pct:'60%' },
  ];
  const ESTANCADAS = [
    { tit:'Suministro anual - Envases Duero',       cap:'Sin cambios hace 23 días', imp:'18.400 €' },
    { tit:'Segunda línea - Áridos Sil',             cap:'Sin cambios hace 21 días', imp:'26.000 €' },
    { tit:'Mantenimiento anual - Cerámicas Vall',   cap:'Sin cambios hace 19 días', imp:'4.900 €'  },
    { tit:'Cambio de compresores - Talleres Ordás', cap:'Sin cambios hace 17 días', imp:'7.200 €'  },
    { tit:'Repuesto de bomba - Metalúrgica Bierzo', cap:'Sin cambios hace 16 días', imp:'3.100 €'  },
  ];
  // Agosto de 2026 empieza en sábado; las cinco fechas de la lista, en naranja
  const SEMANAS = [[0,0,0,0,0,1,2],[3,4,5,6,7,8,9],[10,11,12,13,14,15,16],[17,18,19,20,21,22,23],[24,25,26,27,28,29,30],[31,0,0,0,0,0,0]];
  const DIAS = [18,21,25,27,29];

  const Ico = ({ n, s=24, c='#0F172A', w=2 })=>{
    const P = {
      event_upcoming:<><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"/><path d="M12 18.5 V13 M9.6 15.2 L12 12.8 L14.4 15.2"/></>,
      event_busy:<><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"/><path d="M9.5 13.5 L14.5 18.5 M14.5 13.5 L9.5 18.5"/></>,
      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"/></>,
      payments:<><rect x="2.2" y="7.6" width="15.6" height="10.8" rx="2"/><circle cx="10" cy="13" r="2.5"/><path d="M6 5.2 H19.8 A2 2 0 0 1 21.8 7.2 V15.4"/></>,
      balance:<><path d="M12 4 V20 M6.5 20 H17.5 M3.6 8.4 H20.4"/><path d="M3.6 8.4 L1.2 14.4 H6 Z"/><path d="M20.4 8.4 L18 14.4 H22.8 Z"/></>,
      handshake:<><path d="M12.4 9.2 L9.6 6.4 A2 2 0 0 0 6.8 6.4 L2.6 10.6 A2 2 0 0 0 2.6 13.4 L4.6 15.4"/><path d="M11.6 9.2 L14.4 6.4 A2 2 0 0 1 17.2 6.4 L21.4 10.6 A2 2 0 0 1 21.4 13.4 L19.4 15.4"/><path d="M7.6 12.6 L11 16 A1.8 1.8 0 0 0 13.6 16 L16.6 12.8"/></>,
      calendar:<><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"/></>,
    };
    return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round">{P[n]}</svg>;
  };

  // ── Progresos ──
  const enP = clamp((t-T.entra)/0.75,0,1), enE = Easing.easeOutBack(enP);
  const cabP = clamp((t-T.cabecera)/0.5,0,1);
  const calIn  = clamp((t-T.mes)/0.55,0,1);
  const calOut = clamp((t-T.filas+0.5)/0.5,0,1);
  const cal = clamp(calIn - calOut, 0, 1);
  const mesShade = Easing.easeOutCubic(clamp((t-T.mes)/0.9,0,1));
  const flechaP = Easing.easeInOutCubic(clamp((t-T.cerca)/1.0,0,1));
  const haloP = t >= T.cuentaTodas && t < T.cuentaTodas+1.6 ? Math.sin((t-T.cuentaTodas)/1.6*Math.PI) : 0;
  const notaIn  = clamp((t-T.cuentaTodas)/0.5,0,1);
  const notaOut = clamp((t-T.vacio+0.4)/0.5,0,1);
  const nota = clamp(notaIn - notaOut, 0, 1);
  const pagFoco = t >= T.pagina && t < T.pagina+1.8 ? Math.sin((t-T.pagina)/1.8*Math.PI) : 0;
  const vaIn  = clamp((t-T.vacio)/0.3,0,1);
  const vaOut = clamp((t-T.vacio-T.vacioDur)/0.3,0,1);
  const vacio = clamp(vaIn - vaOut, 0, 1);
  const selloE = Easing.easeOutBack(clamp((t-T.calendario)/0.55,0,1));
  const silP = clamp((t-T.silencio)/0.8,0,1), silE = Easing.easeOutCubic(silP);

  const opIzq = enE * lerp(1, 0.30, silE);
  const opDer = lerp(0.16, 0.62, silE);

  // ── Píldora compacta ──
  const Pildora = ({ p, i })=>{
    const foco = i === 3 ? clamp((t-T.cuentaTodas)/0.4,0,1)*(1-clamp((t-T.vacio)/0.5,0,1)) : 0;
    return (
      <div style={{position:'absolute', left:PX[i]-80, top:152, width:PW[i], height:120,
                   display:'flex', alignItems:'center', gap:14, padding:'0 20px', boxSizing:'border-box',
                   background:'#fff', border:'1px solid #E2E8F0', borderRadius:14,
                   opacity:lerp(0.38, 1, foco),
                   boxShadow:0 < haloP && i === 3 ? `0 0 ${haloP*46}px rgba(230,81,0,0.55)` : '0 2px 8px rgba(15,23,42,0.04)'}}>
        <Ico n={p.k} s={54} c={p.col} w={1.7}/>
        <div style={{lineHeight:1.1, minWidth:0}}>
          <div className="f-plex" style={{fontSize:48, fontWeight:800, color:p.col, letterSpacing:'-0.02em', whiteSpace:'nowrap'}}>{p.val}</div>
          <div className="f-plex" style={{fontSize:22, color:'#64748B', marginTop:7, whiteSpace:'nowrap'}}>{p.tit}</div>
        </div>
      </div>
    );
  };

  // ── Fila de «Cierre Este Mes». La FECHA entra primero (viene del calendario) y el título
  //    después: es lo que hace legible «lo más cerca, arriba» antes de que haya filas ──
  const FilaCierre = ({ r, i })=>{
    const p = clamp((t-T.filas-i*T.filaStep)/0.5,0,1), e = Easing.easeOutCubic(p);
    const fP = clamp((t-T.cerca-i*T.diaStep)/0.5,0,1), fE = Easing.easeOutCubic(fP);
    const impP = clamp((t-T.importes-i*0.09)/0.45,0,1);
    const pctP = clamp((t-T.insignias-i*0.09)/0.45,0,1);
    return (
      <div style={{display:'flex', alignItems:'center', gap:16, height:84, padding:'0 26px 0 48px',
                   borderBottom:i < 4 ? '1px solid #F1F5F9' : 'none',
                   opacity:clamp(Math.max(e, fP)*1.25,0,1)}}>
        <div style={{flex:1, minWidth:0, lineHeight:1.25}}>
          <div className="f-plex" style={{fontSize:27, fontWeight:600, color:'#0F172A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
                                          opacity:clamp(e*1.25,0,1), transform:`translateY(${(1-e)*10}px)`}}>{r.tit}</div>
          <div className="f-plex" style={{fontSize:20, color:0 < p ? '#94A3B8' : '#e65100', marginTop:4, fontWeight:0 < p ? 400 : 700,
                                          opacity:fP, transform:`translateY(${(1-fE)*10}px)`}}>{r.cap}</div>
        </div>
        {r.imp && (
          <span className="f-plex" style={{fontSize:28, fontWeight:700, color:'#2e7d32', whiteSpace:'nowrap',
                                           opacity:impP, transform:`translateY(${(1-Easing.easeOutBack(impP))*10}px)`}}>{r.imp}</span>
        )}
        <span style={{width:76, display:'flex', justifyContent:'flex-end'}}>
          {r.pct && (
            <span className="f-plex" style={{fontSize:20, fontWeight:700, color:'#1565c0',
                                             border:'1.4px solid rgba(21,101,192,0.4)', borderRadius:99, padding:'3px 12px',
                                             opacity:pctP, transform:`scale(${lerp(0.6,1,Easing.easeOutBack(pctP))})`}}>{r.pct}</span>
          )}
        </span>
      </div>
    );
  };

  const FilaEst = ({ r, i })=>(
    <div style={{display:'flex', alignItems:'center', gap:16, height:84, padding:'0 26px',
                 borderBottom:i < 4 ? '1px solid #F1F5F9' : 'none'}}>
      <div style={{flex:1, minWidth:0, lineHeight:1.25}}>
        <div className="f-plex" style={{fontSize:27, fontWeight:600, color:'#0F172A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{r.tit}</div>
        <div className="f-plex" style={{fontSize:20, color:'#e65100', marginTop:4}}>{r.cap}</div>
      </div>
      <span className="f-plex" style={{fontSize:28, fontWeight:700, color:'#2e7d32', whiteSpace:'nowrap'}}>{r.imp}</span>
    </div>
  );

  const Pager = ({ foco })=>(
    <div style={{display:'flex', alignItems:'center', justifyContent:'center', gap:10, height:56, borderTop:'1px solid #F1F5F9',
                 opacity:lerp(0.45, 1, clamp((t-T.pagina)/0.5,0,1))}}>
      <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>‹</span>
      <span className="f-plex" style={{fontSize:21, fontWeight:700, color:'#fff', background:'#94A3B8', borderRadius:6, padding:'2px 10px'}}>1</span>
      <span className="f-plex" style={{fontSize:21, fontWeight:700, color:'#64748B', borderRadius:6, padding:'2px 10px',
                                       background:0 < foco ? 'rgba(230,81,0,0.14)' : 'transparent',
                                       boxShadow:0 < foco ? `0 0 ${foco*24}px rgba(230,81,0,0.5)` : 'none'}}>2</span>
      <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>›</span>
    </div>
  );

  return (
    <SlideCanvas variant="light">
      <DemoHeader t={t} eyebrow="LA PRIMERA LISTA" title={<span>Fecha estimada dentro del mes</span>}/>

      <div style={{position:'absolute', left:80, top:130, width:1760, height:890,
                   borderRadius:18, border:'1px solid #E2E8F0', background:'#F6F8FB',
                   boxShadow:'0 34px 84px rgba(15,23,42,0.13)', overflow:'hidden'}}>
        <BrowserChrome url="play.dinaup.com/App/CRM" title="CRM — Dinaup"/>
        <DinaupAppHeader breadcrumb={["CRM","Inicio"]} company="Suministros del Norte, S.L." initials="NP"/>

        {PILLS.map((p,i)=> <Pildora key={p.tit} p={p} i={i}/>)}

        {/* ── «Cierre Este Mes»: la protagonista ── */}
        <div style={{position:'absolute', left:30, top:296, width:838,
                     background:'#fff', borderRadius:16, overflow:'hidden',
                     border:`${cabP > 0.3 ? 2 : 1}px solid ${cabP > 0.3 ? 'rgba(230,81,0,0.45)' : '#E2E8F0'}`,
                     opacity:opIzq, transform:`translateY(${(1-enE)*30}px)`,
                     boxShadow:`0 ${lerp(18,4,silE)}px ${lerp(52,16,silE)}px rgba(15,23,42,${lerp(0.14,0.05,silE)})`}}>
          <div style={{position:'relative', display:'flex', alignItems:'center', gap:13, padding:'21px 26px', borderBottom:'1px solid #EEF2F6'}}>
            <Ico n="event_upcoming" s={27} c="#e65100" w={2}/>
            <span className="f-plex" style={{fontSize:29, fontWeight:700, color:'#0F172A'}}>Cierre Este Mes</span>
            {/* Sello: esta te la marca el calendario */}
            {selloE > 0.01 && (
              <span style={{marginLeft:'auto', display:'inline-flex', alignItems:'center', gap:10, padding:'8px 16px',
                            background:'rgba(230,81,0,0.10)', border:'1.4px solid rgba(230,81,0,0.35)', borderRadius:99,
                            transform:`scale(${lerp(0.6,1,selloE)})`, opacity:clamp(selloE*1.3,0,1)}}>
                <Ico n="calendar" s={22} c="#e65100" w={2}/>
                <span className="f-plex" style={{fontSize:21, fontWeight:700, color:'#e65100'}}>la marca el calendario</span>
              </span>
            )}
          </div>
          <div style={{position:'relative', height:420}}>
            <div style={{position:'absolute', inset:0, opacity:1-vacio}}>
              {CIERRE.map((r,i)=> <FilaCierre key={r.tit} r={r} i={i}/>)}
              {/* Lo más cerca, arriba: la flecha baja por la columna de fechas */}
              {flechaP > 0 && (
                <svg width="34" height="376" viewBox="0 0 34 376" style={{position:'absolute', left:12, top:24}}>
                  <path d="M17 6 V352" stroke="#e65100" strokeWidth="4" strokeLinecap="round"
                        strokeDasharray="346" strokeDashoffset={346*(1-flechaP)}/>
                  <path d="M8 340 L17 352 L26 340" stroke="#e65100" strokeWidth="4" fill="none" strokeLinecap="round" strokeLinejoin="round"
                        opacity={clamp((flechaP-0.82)/0.18,0,1)}/>
                </svg>
              )}
            </div>
            <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', padding:'0 60px',
                         opacity:vacio}}>
              <span className="f-plex" style={{fontSize:28, color:'#64748B', textAlign:'center', lineHeight:1.4}}>
                No hay oportunidades con cierre estimado este mes
              </span>
            </div>
          </div>
          <Pager foco={pagFoco}/>
        </div>

        {/* ── «Oportunidades Estancadas»: espera en penumbra ── */}
        <div style={{position:'absolute', left:892, top:296, width:838,
                     background:'#fff', borderRadius:16, overflow:'hidden',
                     border:`${silP > 0.2 ? 2 : 1}px solid ${silP > 0.2 ? 'rgba(191,54,12,0.5)' : '#E2E8F0'}`,
                     opacity:opDer,
                     boxShadow:silP > 0.2 ? `0 18px 50px rgba(191,54,12,${silE*0.18})` : 'none'}}>
          <div style={{display:'flex', alignItems:'center', gap:13, padding:'21px 26px', borderBottom:'1px solid #EEF2F6'}}>
            <Ico n="warning" s={27} c="#bf360c" w={2}/>
            <span className="f-plex" style={{fontSize:29, fontWeight:700, color:'#0F172A'}}>Oportunidades Estancadas</span>
          </div>
          <div style={{height:420}}>
            {ESTANCADAS.map((r,i)=> <FilaEst key={r.tit} r={r} i={i}/>)}
          </div>
          <div style={{display:'flex', alignItems:'center', justifyContent:'center', gap:10, height:56, borderTop:'1px solid #F1F5F9'}}>
            <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>‹</span>
            <span className="f-plex" style={{fontSize:21, fontWeight:700, color:'#fff', background:'#94A3B8', borderRadius:6, padding:'2px 10px'}}>1</span>
            <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>2</span>
            <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>›</span>
          </div>
        </div>
      </div>

      {/* ─────────── El mes en curso: agosto entero, y las cinco fechas ─────────── */}
      {cal > 0.01 && (
        <div style={{position:'absolute', left:1010, top:452, width:760, opacity:cal,
                     transform:`translateY(${(1-Easing.easeOutCubic(cal))*14}px)`}}>
          <div style={{background:'#fff', borderRadius:18, border:'1px solid #E2E8F0',
                       boxShadow:'0 30px 74px rgba(15,23,42,0.18)', padding:'26px 30px 30px'}}>
            <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between'}}>
              <span className="f-plex" style={{fontSize:28, fontWeight:700, color:'#0F172A'}}>Agosto 2026</span>
              <span className="f-plex" style={{fontSize:21, color:'#94A3B8'}}>el mes en curso</span>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6, marginTop:18}}>
              {['L','M','X','J','V','S','D'].map(d=>(
                <div key={d} className="f-plex" style={{fontSize:19, color:'#CBD5E1', textAlign:'center', fontWeight:700}}>{d}</div>
              ))}
              {SEMANAS.map((sem,si)=> sem.map((d,di)=>{
                if (d === 0) return <div key={si+'-'+di}/>;
                const idx = DIAS.indexOf(d);
                const on = 0 <= idx ? clamp((t-T.cerca-idx*T.diaStep)/0.4,0,1) : 0;
                const sh = clamp(mesShade*31 - (d-1), 0, 1);
                return (
                  <div key={si+'-'+di} className="f-plex" style={{
                    height:48, display:'flex', alignItems:'center', justifyContent:'center', borderRadius:9,
                    fontSize:22, fontWeight:0 < on ? 800 : 500,
                    color:0 < on ? '#fff' : (d === 13 ? '#0F172A' : '#64748B'),
                    background:0 < on ? `rgba(230,81,0,${on})` : `rgba(148,163,184,${0.16*sh})`,
                    border:d === 13 ? '2px solid #CBD5E1' : '2px solid transparent',
                    transform:`scale(${lerp(1, 1.06, Easing.easeOutBack(on))})`,
                  }}>{d}</div>
                );
              }))}
            </div>
          </div>
        </div>
      )}

      {/* ─────────── El número las cuenta todas; la lista enseña cinco ─────────── */}
      {nota > 0.01 && (
        <div style={{position:'absolute', left:1010, top:520, width:760, opacity:nota,
                     transform:`translateY(${(1-Easing.easeOutCubic(nota))*14}px)`}}>
          <div style={{background:'#fff', borderRadius:18, border:'1px solid #E2E8F0',
                       boxShadow:'0 30px 74px rgba(15,23,42,0.18)', padding:'34px 38px'}}>
            <div style={{display:'flex', alignItems:'center', gap:26}}>
              <div style={{textAlign:'center'}}>
                <div className="f-plex" style={{fontSize:96, fontWeight:800, color:'#e65100', lineHeight:1}}>7</div>
                <div className="f-plex" style={{fontSize:22, color:'#64748B', marginTop:8}}>en el marcador</div>
              </div>
              <div style={{width:1, height:110, background:'#E2E8F0'}}/>
              <div style={{textAlign:'center'}}>
                <div className="f-plex" style={{fontSize:96, fontWeight:800, color:'#94A3B8', lineHeight:1}}>5</div>
                <div className="f-plex" style={{fontSize:22, color:'#64748B', marginTop:8}}>en la primera página</div>
              </div>
              <div style={{flex:1}}/>
              <div className="f-plex" style={{fontSize:26, color:'#334155', lineHeight:1.4, maxWidth:280}}>
                El número cuenta la colección entera. La lista pagina de cinco en cinco.
              </div>
            </div>
          </div>
        </div>
      )}
    </SlideCanvas>
  );
}
Object.assign(window, { EscenaPN03 });
