// === Escena 06 — "Por proveedor" · audio real 27.98s ===
// LOCUCIÓN: "Antes de contabilizar, Dinaup agrupa las facturas por proveedor. ¿El proveedor ya
//   existe? Listas para agregar. ¿Es nuevo? Se abre su alta... y ahí se comprueba todo: el NIF,
//   contra la AEAT o el VIES. Existe, y es quien dice ser. Lo das de alta una vez... y todas
//   sus facturas entran bien, hoy y siempre. ¿Y tu parte? Tu parte es esta."
// BEATS: grupos por proveedor (existente=verde · nuevo=ámbar) · clic en AGREGAR PROVEEDOR →
//   modal de alta con verificación AEAT/VIES en vivo → crear → el grupo vira a verde.
function Escena06({ t }){
  const T = {
    win:        0.3, // "Antes de contabilizar"                → ventana
    groups0:    2.4, // "agrupa las facturas por proveedor"    → grupos
    groupStep: 0.55,                                         // (incremento, no instante)
    okPulse:    7.2, // "Listas para agregar"                  → pulso OK
    newHl:      8.9, // "Es nuevo"                             → resalta el nuevo
    cur0:       8.9,                                         // (apoyo) cursor
    cur1:       9.6,                                         // (apoyo) cursor
    clickBtn:   9.9,                                         // (apoyo) click
    modal:      10.2, // "Se abre su alta"                      → modal de alta
    fName:     12.2,                                         // (apoyo) campo nombre
    fNif:      13.6, // "el NIF"                               → campo NIF
    checkA0:   14.3, // "contra la A E A T"                    → check AEAT
    checkA1:   15.3,                                         // (apoyo) check AEAT ok
    checkV0:   16.3, // "o el VIES"                            → check VIES
    checkV1:   17.1,                                         // (apoyo) check VIES ok
    badge:     18.1, // "Existe, y es quien dice ser"          → badge verificado
    cur20:     19.5,                                         // (apoyo) cursor
    cur21:     20.2,                                         // (apoyo) cursor
    clickCrear:20.5, // "Lo das de alta una vez"               → click Crear
    modalOut:  21.0,                                         // (apoyo) cierra modal
    groupGreen:21.6,                                         // (apoyo) grupo verde
    chip6:     22.1, // "todas sus facturas entran bien"       → chip
    dim:       27.1, // "Tu parte es esta"                     → atenúa
  };
  const winP = clamp((t-T.win)/0.6, 0, 1), winE = Easing.easeOutCubic(winP);

  const GROUPS = [
    { n:'Endesa Energía S.A.',   nif:'B-81948077', docs:34, ok:true },
    { n:'Vodafone España S.A.U.',nif:'A-80907397', docs:28, ok:true },
    { n:'Ferretería La Llave',   nif:'B-46021233', docs:6,  ok:false },
  ];
  const groupP = (i)=> clamp((t-(T.groups0+i*T.groupStep))/0.45, 0, 1);
  const okPulseOn = t >= T.okPulse && t < T.okPulse+0.9;
  const okPulse = okPulseOn ? Math.sin((t-T.okPulse)/0.9*Math.PI) : 0;
  const newHlOn = t >= T.newHl && t < T.modal;

  const modalP = clamp((t-T.modal)/0.5, 0, 1) * (1 - clamp((t-T.modalOut)/0.4, 0, 1));
  const modalE = Easing.easeOutBack(clamp((t-T.modal)/0.5, 0, 1));
  const checkA = t >= T.checkA1, checkAspin = t >= T.checkA0 && !checkA;
  const checkV = t >= T.checkV1, checkVspin = t >= T.checkV0 && !checkV;
  const badgeP = clamp((t-T.badge)/0.4, 0, 1);
  const green = t >= T.groupGreen;
  const chip6P = clamp((t-T.chip6)/0.45, 0, 1);
  const dimP = clamp((t-T.dim)/1.2, 0, 1);

  // Cursor: dos tramos (al botón AGREGAR · al botón Crear del modal)
  const leg = (t0, t1, A, B, bend)=>{
    const p = clamp((t-t0)/(t1-t0), 0, 1);
    const e = Easing.easeInOutCubic(Math.pow(p, 0.82));
    const len = Math.hypot(B.x-A.x, B.y-A.y) || 1;
    const C = { x:(A.x+B.x)/2 - (B.y-A.y)/len*bend, y:(A.y+B.y)/2 + (B.x-A.x)/len*bend };
    const v = 1-e;
    return { x: v*v*A.x + 2*v*e*C.x + e*e*B.x, y: v*v*A.y + 2*v*e*C.y + e*e*B.y, p };
  };
  const BTN1 = {x:1492, y:646};              // AGREGAR PROVEEDOR (fila del grupo nuevo)
  const BTN2 = {x:1206, y:812};              // Crear proveedor (modal)
  let cur = null;
  if (t >= T.cur0 && t < T.cur20)      cur = leg(T.cur0, T.cur1, {x:1740,y:1000}, BTN1, -110);
  else if (t >= T.cur20)               cur = leg(T.cur20, T.cur21, BTN1, BTN2, 60);
  const click1 = t >= T.clickBtn && t < T.clickBtn+0.2;
  const click2 = t >= T.clickCrear && t < T.clickCrear+0.2;

  const spinner = (on)=> on ? <span style={{width:13, height:13, border:'2.5px solid rgba(0,133,255,0.2)', borderTopColor:'#0085FF', borderRadius:100, display:'inline-block', transform:`rotate(${(t*520)%360}deg)`}}/> : null;

  return (
    <SlideCanvas variant="light-soft">
      <div style={{position:'absolute', left:240, top:110, width:1440, height:860, background:'#fff', borderRadius:12, overflow:'hidden', border:'1px solid #E2E8F0', boxShadow:'0 40px 100px rgba(0,133,255,0.16), 0 10px 26px rgba(15,23,42,0.10)', opacity:winP*(1-dimP*0.5), transform:`translateY(${(1-winE)*26}px) scale(${lerp(0.975,1,winE)})`}}>
        <BrowserChrome url="play.dinaup.com/App/Pymes/FacturasRecibidas" title="Dinaup — Facturas recibidas"/>
        <DinaupAppHeader breadcrumb={["Compras","Facturas recibidas","Por proveedor"]}/>

        <div style={{padding:'18px 30px'}}>
          <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:14}}>
            <div>
              <div className="f-plex" style={{fontSize:19, fontWeight:700, color:'#0F172A'}}>Facturas por proveedor</div>
              <div style={{fontSize:12, color:'#64748B', marginTop:2}}>Antes de contabilizar, cada factura con su proveedor</div>
            </div>
            <span className="f-mono" style={{fontSize:11, color:'#64748B'}}>266 facturas · 3 proveedores</span>
          </div>

          {/* Grupos */}
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {GROUPS.map((g,i)=>{
              const p = groupP(i), e = Easing.easeOutBack(p);
              const isNew = !g.ok;
              const nowOk = g.ok || green;
              return (
                <div key={i} style={{border:`1.5px solid ${isNew&&!green ? (newHlOn?'#F59E0B':'#FCD34D') : 'rgba(16,185,129,0.35)'}`, borderRadius:12, background: isNew&&!green?'#FFFDF5':'#fff', padding:'14px 18px', opacity:clamp(p*1.3,0,1), transform:`translateY(${(1-e)*22}px)`, boxShadow: isNew&&newHlOn?'0 0 0 4px rgba(245,158,11,0.15)':'0 6px 18px rgba(15,23,42,0.05)'}}>
                  <div style={{display:'flex', alignItems:'center', gap:14}}>
                    <div style={{width:40, height:40, borderRadius:10, background: nowOk?'rgba(16,185,129,0.10)':'rgba(245,158,11,0.12)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                      {nowOk ? <ProviderLogo name={g.n.split(' ')[0]} size={24}/> : <span style={{fontSize:16}}>🏪</span>}
                    </div>
                    <div style={{minWidth:0, flex:1}}>
                      <div style={{display:'flex', alignItems:'center', gap:10}}>
                        <span className="f-plex" style={{fontSize:15.5, fontWeight:700, color:'#0F172A'}}>{g.n}</span>
                        <span className="f-mono" style={{fontSize:10, color:'#94A3B8'}}>{g.nif}</span>
                        <span className="f-mono" style={{fontSize:10.5, fontWeight:700, color:'#475569', background:'#F1F5F9', borderRadius:100, padding:'2px 10px'}}>{g.docs} doc.</span>
                      </div>
                      <div style={{marginTop:5}}>
                        {nowOk ? (
                          (isNew && chip6P > 0) ? (
                            <span className="f-mono" style={{fontSize:10.5, fontWeight:800, color:'#059669', background:'rgba(16,185,129,0.10)', border:'1px solid rgba(16,185,129,0.4)', borderRadius:100, padding:'3px 11px', display:'inline-block', opacity:clamp(chip6P*1.3,0,1), transform:`scale(${lerp(0.7,1,Easing.easeOutBack(chip6P))})`}}>✓ proveedor creado — 6 listas para agregar</span>
                          ) : !isNew ? (
                            <span className="f-mono" style={{fontSize:10.5, fontWeight:700, color:'#059669', transform:`scale(${okPulseOn?1+okPulse*0.05:1})`, display:'inline-block'}}>✓ proveedor existente · listas para agregar</span>
                          ) : null
                        ) : (
                          <span className="f-mono" style={{fontSize:10.5, fontWeight:700, color:'#B45309'}}>⚠ proveedor nuevo — necesita alta para contabilizar</span>
                        )}
                      </div>
                    </div>
                    {isNew && !green && (
                      <div style={{display:'flex', alignItems:'center', gap:7, background:'#0085FF', color:'#fff', borderRadius:9, padding:'9px 18px', fontSize:12, fontWeight:700, fontFamily:"'IBM Plex Sans',sans-serif", boxShadow: click1?'0 2px 6px rgba(0,133,255,0.4)':'0 6px 16px rgba(0,133,255,0.35)', transform: click1?'scale(0.94)':'scale(1)', flexShrink:0}}>+ AGREGAR PROVEEDOR</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Modal: Agregar proveedor (aquí vive la verificación AEAT/VIES) */}
        {modalP > 0 && (
          <React.Fragment>
            <div style={{position:'absolute', inset:0, background:'rgba(15,23,42,0.35)', opacity:modalP, zIndex:8}}/>
            <div style={{position:'absolute', left:'50%', top:'50%', transform:`translate(-50%,-50%) scale(${lerp(0.88,1,modalE)})`, width:760, background:'#fff', borderRadius:16, boxShadow:'0 50px 120px rgba(15,23,42,0.35)', opacity:modalP, zIndex:9, overflow:'hidden'}}>
              <div style={{height:46, background:'#F8FAFC', borderBottom:'1px solid #EEF2F7', display:'flex', alignItems:'center', padding:'0 20px', gap:10}}>
                <span style={{fontSize:14}}>🏪</span>
                <span className="f-plex" style={{fontSize:14, fontWeight:700, color:'#0F172A'}}>Agregar proveedor</span>
                <div style={{flex:1}}/>
                <span className="f-mono" style={{fontSize:11, color:'#94A3B8'}}>×</span>
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 285px', gap:16, padding:'18px 20px'}}>
                <div style={{display:'flex', flexDirection:'column', gap:11}}>
                  {[['Nombre fiscal','Ferretería La Llave S.L.', T.fName],['NIF','B-46021233', T.fNif],['Dirección','Pol. Ind. El Llano, nave 12 · Elche', T.fNif+0.5]].map((f,i)=>(
                    <div key={i} style={{border:'1.5px solid #E2E8F0', borderRadius:9, padding:'8px 13px'}}>
                      <div className="f-mono" style={{fontSize:8.5, letterSpacing:'1px', color:'#94A3B8', textTransform:'uppercase', marginBottom:2}}>{f[0]}</div>
                      <div className="f-plex" style={{fontSize:14, fontWeight:600, color:'#0F172A', minHeight:20}}>
                        <Typewriter text={f[1]} start={f[2]} cps={34} t={t}/>
                      </div>
                    </div>
                  ))}
                  <div className="f-mono" style={{fontSize:9.5, color:'#94A3B8', fontStyle:'italic'}}>datos extraídos de sus 6 facturas</div>
                </div>

                {/* Verificación en vivo */}
                <div style={{background:'#FBFDFF', border:'1px solid #EEF2F7', borderRadius:11, padding:'13px 15px'}}>
                  <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:11}}>
                    <span className="f-plex" style={{fontSize:12.5, fontWeight:700, color:'#0F172A'}}>Verificación</span>
                    {badgeP > 0 && <span className="f-mono" style={{fontSize:10.5, fontWeight:800, color:'#059669', background:'rgba(16,185,129,0.12)', border:'1.5px solid rgba(16,185,129,0.5)', borderRadius:100, padding:'3px 10px', opacity:clamp(badgeP*1.3,0,1), transform:`scale(${lerp(0.7,1,Easing.easeOutBack(badgeP))})`}}>✓ verificado</span>}
                  </div>
                  <div style={{display:'flex', flexDirection:'column', gap:8}}>
                    <div style={{display:'flex', alignItems:'center', gap:10, background:'#fff', border:`1px solid ${checkA?'rgba(16,185,129,0.4)':'#E2E8F0'}`, borderRadius:8, padding:'8px 11px'}}>
                      {checkA ? <span style={{width:18, height:18, borderRadius:100, background:'#10B981', color:'#fff', fontSize:10, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center'}}>✓</span> : spinner(checkAspin) || <span style={{width:18, height:18, borderRadius:100, border:'2px solid #E2E8F0', display:'inline-block'}}/>}
                      <div>
                        <div className="f-plex" style={{fontSize:11.5, fontWeight:600, color:'#0F172A'}}>Censo AEAT</div>
                        <div className="f-mono" style={{fontSize:8.5, color:'#94A3B8'}}>{checkAspin?'comprobando NIF…':checkA?'NIF válido · alta en censo':'—'}</div>
                      </div>
                    </div>
                    <div style={{display:'flex', alignItems:'center', gap:10, background:'#fff', border:`1px solid ${checkV?'rgba(16,185,129,0.4)':'#E2E8F0'}`, borderRadius:8, padding:'8px 11px'}}>
                      {checkV ? <span style={{width:18, height:18, borderRadius:100, background:'#10B981', color:'#fff', fontSize:10, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center'}}>✓</span> : spinner(checkVspin) || <span style={{width:18, height:18, borderRadius:100, border:'2px solid #E2E8F0', display:'inline-block'}}/>}
                      <div>
                        <div className="f-plex" style={{fontSize:11.5, fontWeight:600, color:'#0F172A'}}>Registro VIES</div>
                        <div className="f-mono" style={{fontSize:8.5, color:'#94A3B8'}}>{checkVspin?'comprobando…':checkV?'operador válido':'—'}</div>
                      </div>
                    </div>
                    <div className="f-mono" style={{fontSize:9, color:'#64748B', marginTop:3}}>existe, y es quien dice ser</div>
                  </div>
                </div>
              </div>
              <div style={{display:'flex', justifyContent:'flex-end', gap:10, padding:'0 20px 18px'}}>
                <div style={{padding:'10px 20px', border:'1.5px solid #E2E8F0', borderRadius:100, fontSize:12.5, fontWeight:700, color:'#64748B', fontFamily:"'IBM Plex Sans',sans-serif"}}>Cancelar</div>
                <div style={{display:'flex', alignItems:'center', gap:8, background: badgeP>0?'linear-gradient(180deg,#10B981,#059669)':'#CBD5E1', color:'#fff', borderRadius:100, padding:'10px 22px', fontSize:12.5, fontWeight:700, fontFamily:"'IBM Plex Sans',sans-serif", boxShadow: badgeP>0?'0 8px 20px rgba(16,185,129,0.35)':'none', transform: click2?'scale(0.94)':'scale(1)'}}>✓ Crear proveedor</div>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>

      {cur && <CineCursor x={cur.x} y={cur.y} clicking={click1 || click2}/>}

    </SlideCanvas>
  );
}
Object.assign(window, { Escena06 });
