// === Slide Motor (11s) — la tesis: el dato se teclea UNA vez ===
// "María López" se teclea UNA única vez en la ficha central. De ella brotan
// enlaces hacia cuatro ventanas (Factura, Ticket TPV, Oportunidad, Tarea) y el
// MISMO dato aparece en cada una con el pulso del enlace — sin re-teclearse.
// Cierre: un anillo rodea la ficha única con el sello "Un solo lugar · sin copias".
// Sincronía con CAPTIONS.slide_motor: 0.5-3.0 la idea · 3.0-5.8 se teclea UNA vez
// · 5.8-8.4 queda enlazado · 8.4-10.8 calidad en un solo lugar.

function SlideMotor({ t }){
  // ---------- Geometría ----------
  const CX = 960, CY = 550;            // centro de la ficha única
  const CARD_W = 440, CARD_H = 158;
  const RING_R = 270;                  // anillo final alrededor de la ficha

  // ---------- Timeline ----------
  const NAME = 'María López';
  const typeStart = 3.25, CPS = 8.5;
  const typeDone  = typeStart + NAME.length / CPS;  // ≈ 4.54
  const checkAt = 4.75;    // check verde dentro del campo
  const chipAt  = 4.95;    // píldora "TECLEADO UNA VEZ"
  const ringAt  = 8.55;    // se dibuja el anillo
  const sealAt  = 9.1;     // sello "Un solo lugar · sin copias"

  // Módulos alrededor: cada uno con su enlace (sx,sy → ex,ey, con comba "bow")
  const mods = [
    { n:'Factura',     k:'receipt', ref:'F-2026-0311', sub:'148,50 € · 12 mar',                  x:390,  y:375, sx:740,  sy:495, ex:540,  ey:383, bow: 34 },
    { n:'Ticket TPV',  k:'tpv',     ref:'T-0412',      sub:'4,80 € · mesa 3',                    x:1530, y:375, sx:1180, sy:495, ex:1380, ey:383, bow: 34 },
    { n:'Oportunidad', k:'target',  ref:'OP-208',      sub:'Reforma cafetería · 3.400 €',        x:390,  y:765, sx:740,  sy:605, ex:540,  ey:757, bow:-34 },
    { n:'Tarea',       k:'task',    ref:'TA-1108',     sub:'Llamada de seguimiento · jue 14:00', x:1530, y:765, sx:1180, sy:605, ex:1380, ey:757, bow:-34 },
  ];
  const linkAt   = (i) => 5.9 + i*0.55;    // el enlace se dibuja
  const arriveAt = (i) => linkAt(i) + 0.7; // el dato "aterriza" en el módulo
  const qualityAt = (i) => 9.45 + i*0.12;  // check de calidad por módulo

  const headerP = clamp(t/0.5, 0, 1);
  const cardP = clamp((t-0.9)/0.7, 0, 1);
  const cardE = Easing.easeOutCubic(cardP);
  const ringE = Easing.easeInOutCubic(clamp((t-ringAt)/0.65, 0, 1));
  const typing = t >= 3.0 && t < typeDone;
  const saved  = t >= checkAt;

  // Punto sobre la bezier cuadrática del enlace (para el pulso que viaja)
  const bez = (m, u) => {
    const cx = (m.sx+m.ex)/2, cy = (m.sy+m.ey)/2 + m.bow;
    const w = 1-u;
    return { x: w*w*m.sx + 2*w*u*cx + u*u*m.ex, y: w*w*m.sy + 2*w*u*cy + u*u*m.ey };
  };

  // Iconos SVG de línea (Material Symbols NO está cargado en el deck)
  const ic = (kind, size, color) => {
    const s = { stroke:color, strokeWidth:1.8, strokeLinecap:'round', strokeLinejoin:'round', fill:'none' };
    const g = {
      person:   <><circle cx="12" cy="8" r="3.4" {...s}/><path d="M5.5 19.5 A6.5 6.5 0 0 1 18.5 19.5" {...s}/></>,
      receipt:  <><path d="M6.5 3.5 H17.5 V20.5 L15.6 19 L13.8 20.5 L12 19 L10.2 20.5 L8.4 19 L6.5 20.5 Z" {...s}/><path d="M9.5 8.2 H14.5 M9.5 11.8 H13" {...s}/></>,
      tpv:      <><path d="M3.5 4.5 H6.2 L8.6 15 H17.8 L20.2 7.5 H7.2" {...s}/><circle cx="9.9" cy="18.6" r="1.6" {...s}/><circle cx="16.4" cy="18.6" r="1.6" {...s}/></>,
      target:   <><circle cx="12" cy="12" r="7.5" {...s}/><circle cx="12" cy="12" r="3" {...s}/><circle cx="12" cy="12" r="0.7" fill={color} stroke="none"/></>,
      task:     <><rect x="4" y="4.5" width="16" height="16" rx="3.5" {...s}/><path d="M8.4 12.6 L11 15.2 L15.8 9.9" {...s}/></>,
      keyboard: <><rect x="2.8" y="6.5" width="18.4" height="11.5" rx="2.2" {...s}/><path d="M6.2 10 H6.9 M9.6 10 H10.3 M13 10 H13.7 M16.4 10 H17.1 M7.5 14.2 H16.5" {...s}/></>,
      link:     <><path d="M10 13 a5 5 0 0 0 7.54 0.54 l3 -3 a5 5 0 0 0 -7.07 -7.07 l-1.72 1.71" {...s} strokeWidth="2"/><path d="M14 11 a5 5 0 0 0 -7.54 -0.54 l-3 3 a5 5 0 0 0 7.07 7.07 l1.71 -1.71" {...s} strokeWidth="2"/></>,
      shield:   <><path d="M12 3.2 L19 6 V11.4 C19 16 16.1 19.3 12 20.8 C7.9 19.3 5 16 5 11.4 V6 Z" {...s}/><path d="M9 11.9 L11.2 14.1 L15.2 9.9" {...s}/></>,
      checkCircle: <><circle cx="12" cy="12" r="8.6" {...s}/><path d="M8.4 12.3 L10.9 14.8 L15.6 9.9" {...s}/></>,
    };
    return <svg width={size} height={size} viewBox="0 0 24 24" style={{display:'block', flexShrink:0}}>{g[kind]}</svg>;
  };

  return (
    <SlideCanvas variant="dark-deep">
      {/* Header */}
      <div style={{position:'absolute',top:56,left:0,right:0,textAlign:'center',opacity:headerP,zIndex:5}}>
        <div className="f-plex" style={{fontSize:14,fontWeight:600,letterSpacing:'2px',color:'#62B4FF'}}>CÓMO FUNCIONA</div>
        <h2 className="f-plex" style={{fontSize:50,fontWeight:700,letterSpacing:'-0.03em',margin:'14px 0 0',color:'#fff'}}>
          Un solo motor. <span className="grad-text">El dato entra una vez.</span>
        </h2>
      </div>

      {/* Glow suave tras la ficha central */}
      <div style={{position:'absolute',left:CX-430,top:CY-290,width:860,height:580,background:'radial-gradient(ellipse at center, rgba(0,133,255,0.14), transparent 62%)',opacity:cardE,pointerEvents:'none'}}/>

      {/* Enlaces + pulsos + anillo (capa SVG) */}
      <svg style={{position:'absolute',inset:0,pointerEvents:'none',zIndex:4}} width="100%" height="100%" viewBox="0 0 1920 1080">
        {mods.map((m,i)=>{
          const la = linkAt(i), aa = arriveAt(i);
          const drawP = Easing.easeInOutCubic(clamp((t-la)/0.5, 0, 1));
          if (drawP <= 0) return null;
          const cx = (m.sx+m.ex)/2, cy = (m.sy+m.ey)/2 + m.bow;
          const flashE = Easing.easeOutCubic(clamp((t-aa)/0.6, 0, 1));
          const strokeOp = (t < aa ? 0.55 : 0.42 + 0.4*(1-flashE)) + 0.18*ringE;
          // Pulso que viaja del centro al módulo
          const pu = clamp((t-(la+0.22))/0.48, 0, 1);
          const showPulse = t >= la+0.22 && pu < 1;
          const pt = showPulse ? bez(m, Easing.easeInOutQuad(pu)) : null;
          // Onda de impacto al aterrizar el dato
          const rp = clamp((t-aa)/0.5, 0, 1);
          return (
            <g key={i}>
              <path d={`M ${m.sx} ${m.sy} Q ${cx} ${cy} ${m.ex} ${m.ey}`}
                stroke="#62B4FF" strokeWidth="1.5" fill="none" strokeLinecap="round"
                pathLength="1" strokeDasharray="1" strokeDashoffset={1-drawP}
                opacity={Math.min(strokeOp, 0.85)}/>
              <circle cx={m.sx} cy={m.sy} r="3" fill="#62B4FF" opacity={drawP*0.9}/>
              {showPulse && (
                <g>
                  <circle cx={pt.x} cy={pt.y} r="9" fill="#62B4FF" opacity={0.28*Math.sin(pu*Math.PI)}/>
                  <circle cx={pt.x} cy={pt.y} r="4.5" fill="#B7DFFF" opacity={Math.sin(pu*Math.PI)}/>
                </g>
              )}
              {rp > 0 && rp < 1 && (
                <circle cx={m.ex} cy={m.ey} r={lerp(5, 26, Easing.easeOutCubic(rp))}
                  fill="none" stroke="#62B4FF" strokeWidth="2" opacity={(1-rp)*0.85}/>
              )}
            </g>
          );
        })}
        {/* Anillo final: todo se recoge alrededor de la ficha única */}
        {t >= ringAt && (
          <circle cx={CX} cy={CY} r={RING_R} fill="none" stroke="#62B4FF" strokeWidth="2"
            pathLength="1" strokeDasharray="1" strokeDashoffset={1-ringE} strokeLinecap="round"
            opacity={0.55 + (t > ringAt+0.8 ? 0.10*Math.sin((t-ringAt)*1.7) : 0)}
            transform={`rotate(-90 ${CX} ${CY})`}
            style={{filter:'drop-shadow(0 0 12px rgba(0,133,255,0.5))'}}/>
        )}
      </svg>

      {/* Módulos alrededor */}
      {mods.map((m,i)=>{
        const p = clamp((t-(1.8+i*0.22))/0.55, 0, 1);
        const e = Easing.easeOutCubic(p);
        const aa = arriveAt(i);
        const linked = t >= aa;
        const flashP = clamp((t-aa)/0.5, 0, 1);
        const dP = clamp((t-aa)/0.45, 0, 1);
        const dE = Easing.easeOutBack(dP);
        const qP = clamp((t-qualityAt(i))/0.35, 0, 1);
        const qE = Easing.easeOutBack(qP);
        return (
          <div key={m.n} style={{
            position:'absolute', left:m.x-150, top:m.y-59, width:300, height:118, zIndex:6,
            background: linked ? 'rgba(255,255,255,0.075)' : 'rgba(255,255,255,0.045)',
            border:`1px solid ${linked ? `rgba(98,180,255,${0.42 + 0.4*(1-flashP)})` : 'rgba(255,255,255,0.13)'}`,
            borderRadius:14, backdropFilter:'blur(6px)',
            boxShadow: linked ? '0 14px 40px rgba(0,133,255,0.16)' : '0 14px 34px rgba(2,6,23,0.45)',
            padding:'15px 20px 0',
            opacity:clamp(p*1.25,0,1),
            transform:`translateY(${(1-e)*16}px) scale(${lerp(0.94,1,e)})`,
          }}>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              {ic(m.k, 16, linked ? '#8FCBFF' : 'rgba(255,255,255,0.55)')}
              <span className="f-plex" style={{fontSize:13.5,fontWeight:700,color:'#fff',opacity:linked?1:0.82}}>{m.n}</span>
              <span className="f-mono" style={{marginLeft:'auto',fontSize:9.5,color:'rgba(255,255,255,0.38)'}}>{m.ref}</span>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:10,marginTop:14,height:24}}>
              <span className="f-mono" style={{fontSize:9,fontWeight:600,letterSpacing:'1.5px',color:'rgba(255,255,255,0.4)'}}>CLIENTE</span>
              {linked === false && <span className="f-plex" style={{fontSize:15,color:'rgba(255,255,255,0.28)'}}>—</span>}
              {linked && (
                <span style={{display:'inline-flex',alignItems:'center',gap:7,opacity:clamp(dP*1.3,0,1),transform:`translateY(${(1-dE)*5}px) scale(${lerp(0.86,1,dE)})`,transformOrigin:'left center'}}>
                  {ic('link', 13, '#62B4FF')}
                  <span className="f-plex" style={{fontSize:15,fontWeight:700,color:'#fff'}}>{NAME}</span>
                </span>
              )}
              {qP > 0 && (
                <span style={{marginLeft:'auto',display:'inline-flex',opacity:clamp(qP*1.3,0,1),transform:`scale(${lerp(0.5,1,qE)})`}}>
                  {ic('checkCircle', 15, '#56E16A')}
                </span>
              )}
            </div>
            <div className="f-mono" style={{fontSize:10,color:'rgba(255,255,255,0.42)',marginTop:10,whiteSpace:'nowrap'}}>{m.sub}</div>
          </div>
        );
      })}

      {/* Ficha central: aquí se teclea el dato UNA vez */}
      <div style={{
        position:'absolute', left:CX-CARD_W/2, top:CY-CARD_H/2, width:CARD_W, height:CARD_H, zIndex:7,
        background:'rgba(255,255,255,0.06)',
        border:'1px solid rgba(255,255,255,0.18)',
        borderRadius:18, backdropFilter:'blur(8px)',
        boxShadow:'0 24px 70px rgba(2,6,23,0.55), 0 0 40px rgba(0,133,255,0.10)',
        padding:'20px 24px',
        opacity:clamp(cardP*1.25,0,1),
        transform:`translateY(${(1-cardE)*22}px) scale(${lerp(0.93,1,cardE)})`,
      }}>
        <div style={{display:'flex',alignItems:'center',gap:9}}>
          {ic('person', 18, '#8FCBFF')}
          <span className="f-plex" style={{fontSize:16,fontWeight:700,color:'#fff'}}>Cliente</span>
          <span className="f-mono" style={{fontSize:9.5,fontWeight:600,color:'rgba(255,255,255,0.5)',letterSpacing:'1px',padding:'3px 9px',border:'1px solid rgba(255,255,255,0.16)',borderRadius:100}}>NUEVA FICHA</span>
          <span style={{marginLeft:'auto'}}><DinaupLogo mark size={16}/></span>
        </div>
        <div className="f-mono" style={{fontSize:10,fontWeight:600,letterSpacing:'2px',color:'rgba(255,255,255,0.45)',margin:'16px 0 8px'}}>NOMBRE</div>
        <div style={{
          height:54, display:'flex', alignItems:'center', padding:'0 16px',
          background:'rgba(255,255,255,0.07)',
          border:`1px solid ${typing ? 'rgba(98,180,255,0.75)' : saved ? 'rgba(86,225,106,0.45)' : 'rgba(255,255,255,0.18)'}`,
          boxShadow: typing ? '0 0 0 3px rgba(0,133,255,0.16)' : 'none',
          borderRadius:12, transition:'border 200ms, box-shadow 200ms',
        }}>
          {t < 3.0
            ? <span className="f-plex" style={{fontSize:19,color:'rgba(255,255,255,0.25)'}}>Nombre y apellidos</span>
            : <Typewriter text={NAME} start={typeStart} cps={CPS} t={t} caret={true} style={{fontFamily:"'IBM Plex Sans',sans-serif",fontSize:20,fontWeight:600,color:'#fff'}}/>}
          {saved && (()=>{
            const chP = clamp((t-checkAt)/0.4, 0, 1);
            const chE = Easing.easeOutBack(chP);
            return (
              <span style={{marginLeft:'auto',display:'inline-flex',opacity:clamp(chP*1.3,0,1),transform:`scale(${lerp(0.4,1,chE)})`}}>
                {ic('checkCircle', 20, '#56E16A')}
              </span>
            );
          })()}
        </div>
      </div>

      {/* Píldora bajo la ficha: la diferencia entre teclear y propagarse */}
      {t >= chipAt && (()=>{
        const p = clamp((t-chipAt)/0.5, 0, 1);
        const e = Easing.easeOutBack(p);
        return (
          <div style={{position:'absolute',left:0,right:0,top:CY+CARD_H/2+18,textAlign:'center',zIndex:7,opacity:clamp(p*1.3,0,1),transform:`translateY(${(1-e)*10}px)`}}>
            <span className="f-mono" style={{display:'inline-flex',alignItems:'center',gap:8,padding:'8px 16px',background:'rgba(0,133,255,0.13)',border:'1px solid rgba(98,180,255,0.45)',borderRadius:100,fontSize:11.5,fontWeight:700,letterSpacing:'1.5px',color:'#8FCBFF',transform:`scale(${lerp(0.7,1,e)})`}}>
              {ic('keyboard', 14, '#8FCBFF')}
              TECLEADO UNA VEZ
            </span>
          </div>
        );
      })()}

      {/* Sello de calidad sobre el anillo */}
      {t >= sealAt && (()=>{
        const p = clamp((t-sealAt)/0.55, 0, 1);
        const e = Easing.easeOutBack(p);
        return (
          <div style={{position:'absolute',left:0,right:0,top:CY+RING_R-21,textAlign:'center',zIndex:8,opacity:clamp(p*1.3,0,1)}}>
            <span className="f-plex" style={{display:'inline-flex',alignItems:'center',gap:9,padding:'10px 22px',background:'rgba(11,32,26,0.95)',border:'1px solid rgba(86,225,106,0.55)',borderRadius:100,fontSize:15,fontWeight:700,letterSpacing:'-0.01em',color:'#9BEDB4',boxShadow:'0 10px 30px rgba(86,225,106,0.14)',transform:`scale(${lerp(0.6,1,e)})`}}>
              {ic('shield', 16, '#56E16A')}
              Un solo lugar · sin copias
            </span>
          </div>
        );
      })()}

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

Object.assign(window, { SlideMotor });
