// act5-closing.jsx — Escena cierre (206-211, 5s): neural-hub Sophia + logo
//
// Per JP spec (Pieza 4):
//   · Cerebro central = foto real sophia_v2_leadership.png con violet ring + glow
//   · 2 anillos pulsantes
//   · Líneas SVG neurales chips↔centro con gradient + feGaussianBlur glow + traveling pulse
//   · 9 chips estáticos con micro-drift (no rotación)
//   · Logo EasyPro Plus + tagline en sección inferior

function Act5Closing() {
  const { localTime, duration } = useSprite();
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const tc = i18n.closing || {};
  const mods = i18n.modules || {};
  const t = localTime;

  // Phase orchestration
  // 0.0-1.2  chips + photo fade in
  // 1.0-2.2  neural lines draw + pulses start
  // 2.2-3.4  hold con pulses + photo ring breathing
  // 2.6-4.2  logo + tagline fade in
  // 4.2-5.0  final hold

  const hubOpacity   = clamp(t / 1.2, 0, 1);
  const linesOpacity = clamp((t - 1.0) / 1.2, 0, 1);
  const logoOpacity  = clamp((t - 2.6) / 1.4, 0, 1);
  const logoScale    = 0.94 + 0.06 * Easing.easeOutBack(clamp((t - 2.6) / 1.4, 0, 1));

  // Hub geometry (upper portion of canvas, leaving lower 40% for logo+tagline)
  const cx = 640, cy = 232;
  const HUB_R = 70;          // photo radius
  const CHIP_R = 200;         // chip orbit radius

  // 9 modules — uniformly spaced (40° each) starting from 270° (top).
  // Names come from i18n so the toggle ES/EN swaps them live.
  const chips = [
    { name: mods.credit      || 'Credit',      color: '#FF3B30', angle: 270 }, // top
    { name: mods.migracion   || 'Migración',   color: '#FF9500', angle: 310 },
    { name: mods.explain     || 'Explain',     color: '#8b5cf6', angle: 350 },
    { name: mods.business    || 'Business',    color: '#FF9500', angle:  30 },
    { name: mods.legal       || 'Legal',       color: '#5856D6', angle:  70 },
    { name: mods.event_hub   || 'Event Hub',   color: '#FF2D55', angle: 110 },
    { name: mods.marketplace || 'Marketplace', color: '#6e6e73', angle: 150 },
    { name: mods.insurance   || 'Insurance',   color: '#5AC8FA', angle: 190 },
    { name: mods.taxes       || 'Taxes',       color: '#007AFF', angle: 230 },
  ];

  // Compute chip positions + tiny drift (sub-pixel, gives subtle "alive" feel)
  const chipPositions = chips.map((c, i) => {
    const rad = c.angle * Math.PI / 180;
    const baseX = cx + Math.cos(rad) * CHIP_R;
    const baseY = cy + Math.sin(rad) * CHIP_R;
    // Micro-drift: each chip wobbles ~2px on different sine phases
    const driftX = Math.sin(t * 0.6 + i * 0.7) * 2.0;
    const driftY = Math.cos(t * 0.5 + i * 1.1) * 2.0;
    return { ...c, x: baseX + driftX, y: baseY + driftY, baseX, baseY };
  });

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: 'radial-gradient(ellipse at 50% 36%, #14111c 0%, #07060b 70%)',
      overflow: 'hidden',
    }}>
      {/* Soft aurora glow behind the hub */}
      <div style={{
        position: 'absolute',
        left: cx, top: cy,
        transform: 'translate(-50%, -50%)',
        width: 620, height: 460,
        background: 'radial-gradient(ellipse at center, rgba(139, 92, 246, 0.22) 0%, rgba(74, 139, 255, 0.10) 40%, transparent 70%)',
        opacity: hubOpacity,
        pointerEvents: 'none',
      }} />

      {/* SVG neural lines (under chips + photo) */}
      <svg
        style={{
          position: 'absolute', inset: 0,
          width: '100%', height: '100%',
          pointerEvents: 'none',
          opacity: linesOpacity,
        }}
        viewBox="0 0 1280 720"
        preserveAspectRatio="none"
      >
        <defs>
          {/* Glow filter for the neural lines + pulses */}
          <filter id="closing-neural-glow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="1.6" result="blur" />
            <feMerge>
              <feMergeNode in="blur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
          {/* Per-line gradient: chip color → violet near center */}
          {chipPositions.map((p, i) => (
            <linearGradient
              key={'g' + i}
              id={`closing-line-${i}`}
              x1={p.baseX} y1={p.baseY}
              x2={cx} y2={cy}
              gradientUnits="userSpaceOnUse"
            >
              <stop offset="0%"   stopColor={p.color}  stopOpacity="0.85" />
              <stop offset="55%"  stopColor="#8b5cf6"  stopOpacity="0.65" />
              <stop offset="100%" stopColor="#4a8bff"  stopOpacity="0.85" />
            </linearGradient>
          ))}
        </defs>

        {/* Lines from each chip toward the photo (stop short of the photo radius) */}
        {chipPositions.map((p, i) => {
          // Shorten the line on both ends so it doesn't poke into the chip pill or the photo
          const dx = cx - p.baseX, dy = cy - p.baseY;
          const len = Math.hypot(dx, dy);
          const ux = dx / len, uy = dy / len;
          const x1 = p.baseX + ux * 28;   // start 28px outward from chip toward center
          const y1 = p.baseY + uy * 28;
          const x2 = cx - ux * (HUB_R + 6);
          const y2 = cy - uy * (HUB_R + 6);
          return (
            <line
              key={'l' + i}
              x1={x1} y1={y1} x2={x2} y2={y2}
              stroke={`url(#closing-line-${i})`}
              strokeWidth="1.4"
              strokeLinecap="round"
              filter="url(#closing-neural-glow)"
            />
          );
        })}

        {/* Traveling pulses — data flowing from chips toward the brain */}
        {chipPositions.map((p, i) => {
          const dx = cx - p.baseX, dy = cy - p.baseY;
          const len = Math.hypot(dx, dy);
          const ux = dx / len, uy = dy / len;
          const x1 = p.baseX + ux * 28;
          const y1 = p.baseY + uy * 28;
          const x2 = cx - ux * (HUB_R + 6);
          const y2 = cy - uy * (HUB_R + 6);
          // Pulse cycles every 2.4s, staggered per chip
          const cycle = 2.4;
          const phase = ((t - 1.0 + i * 0.18) % cycle) / cycle; // 0..1
          if (phase < 0 || phase > 1) return null;
          const ease = Easing.easeInOutCubic(clamp(phase, 0, 1));
          const px = x1 + (x2 - x1) * ease;
          const py = y1 + (y2 - y1) * ease;
          const opacity = Math.sin(phase * Math.PI) * 0.95;
          return (
            <circle
              key={'p' + i}
              cx={px} cy={py} r={3.6}
              fill={p.color}
              opacity={opacity * linesOpacity}
              filter="url(#closing-neural-glow)"
            />
          );
        })}
      </svg>

      {/* Sophia photo center — 2 pulsing rings + glow + violet border */}
      <div style={{
        position: 'absolute',
        left: cx, top: cy,
        transform: `translate(-50%, -50%) scale(${0.92 + 0.08 * hubOpacity})`,
        opacity: hubOpacity,
        transition: 'opacity 400ms, transform 600ms cubic-bezier(0.22, 1, 0.36, 1)',
      }}>
        {/* Outer pulsing ring */}
        <div style={{
          position: 'absolute',
          left: '50%', top: '50%',
          width: HUB_R * 2 + 22, height: HUB_R * 2 + 22,
          marginLeft: -(HUB_R + 11), marginTop: -(HUB_R + 11),
          borderRadius: '50%',
          border: '1.5px solid rgba(167, 139, 250, 0.45)',
          animation: 'sol-closing-ring 2.6s ease-out infinite',
          pointerEvents: 'none',
        }} />
        {/* Inner pulsing ring (delayed 1.3s for offset rhythm) */}
        <div style={{
          position: 'absolute',
          left: '50%', top: '50%',
          width: HUB_R * 2 + 8, height: HUB_R * 2 + 8,
          marginLeft: -(HUB_R + 4), marginTop: -(HUB_R + 4),
          borderRadius: '50%',
          border: '1.5px solid rgba(167, 139, 250, 0.7)',
          animation: 'sol-closing-ring 2.6s ease-out infinite 1.3s',
          pointerEvents: 'none',
        }} />

        {/* Photo */}
        <div style={{
          width: HUB_R * 2, height: HUB_R * 2,
          borderRadius: '50%',
          overflow: 'hidden',
          border: '2px solid rgba(167, 139, 250, 0.95)',
          boxShadow: '0 0 36px rgba(139, 92, 246, 0.55), 0 0 72px rgba(74, 139, 255, 0.22), inset 0 0 0 1px rgba(255,255,255,0.08)',
          background: '#1a1a2e',
          position: 'relative',
        }}>
          <img
            src="../static/avatar_sophia/sophia_v2_leadership.png"
            alt="Sophia"
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          />
        </div>

        {/* SOPHIA · AI label below photo */}
        <div style={{
          position: 'absolute',
          left: '50%', top: 'calc(100% + 12px)',
          transform: 'translateX(-50%)',
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          fontSize: 11, color: '#a78bfa',
          letterSpacing: 0.28, textTransform: 'uppercase',
          fontWeight: 700, whiteSpace: 'nowrap',
        }}>{tc.sophia_label || 'SOPHIA · AI'}</div>
      </div>

      {/* Module chips around the hub */}
      {chipPositions.map((p, i) => (
        <div key={p.name} style={{
          position: 'absolute',
          left: p.x, top: p.y,
          transform: 'translate(-50%, -50%)',
          opacity: hubOpacity,
          padding: '6px 14px',
          borderRadius: 999,
          background: 'rgba(20, 20, 30, 0.75)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          border: `1px solid ${p.color}66`,
          color: p.color,
          fontSize: 12.5,
          fontWeight: 600,
          letterSpacing: -0.005,
          whiteSpace: 'nowrap',
          boxShadow: `0 4px 16px ${p.color}33, 0 0 0 1px ${p.color}22 inset`,
          willChange: 'transform',
        }}>{p.name}</div>
      ))}

      {/* Logo + tagline — bottom section */}
      <div style={{
        position: 'absolute',
        left: '50%', top: 560,
        transform: `translate(-50%, 0) scale(${logoScale})`,
        opacity: logoOpacity,
        textAlign: 'center',
        willChange: 'transform, opacity',
      }}>
        <div style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 16,
          marginBottom: 14,
        }}>
          <img
            src="../static/logo-mark.png"
            alt="EasyPro Plus"
            style={{
              width: 56, height: 56,
              filter: 'drop-shadow(0 6px 22px rgba(0, 122, 255, 0.55)) drop-shadow(0 0 18px rgba(74, 139, 255, 0.32))',
            }}
          />
          <div style={{
            fontSize: 44,
            fontWeight: 600,
            letterSpacing: -0.028,
            color: '#fff',
            lineHeight: 1,
          }}>
            EasyPro <span style={{
              background: 'linear-gradient(120deg, #7a3cff, #5a6dff, #2257ff)',
              WebkitBackgroundClip: 'text',
              backgroundClip: 'text',
              color: 'transparent',
            }}>Plus</span>
          </div>
        </div>
        <div style={{
          fontSize: 18,
          fontWeight: 400,
          color: 'rgba(255,255,255,0.88)',
          letterSpacing: -0.012,
          lineHeight: 1.4,
          marginBottom: 6,
        }}>
          {tc.tagline || 'Una sola plataforma. Todos tus módulos. Cero re-captura.'}
        </div>
        <div style={{
          fontSize: 11,
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          color: 'rgba(167, 139, 250, 0.85)',
          letterSpacing: 0.18,
          textTransform: 'uppercase',
          fontWeight: 600,
        }}>
          {tc.powered || 'Powered by Sophia'}
        </div>
      </div>

      <style>{`
        @keyframes sol-closing-ring {
          0%   { transform: scale(1);    opacity: 0.75; }
          100% { transform: scale(1.55); opacity: 0;    }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { Act5Closing });
