/* Integration showcase — continuous sync animation.
   Two panels (Your HR Platform → Colleague Pulse) with a steady stream of
   data packets crossing between them. No hard scene reset; everything is
   driven from a monotonically-increasing `t` that never wraps. */

function ScreenIntegration({ playing = false }) {
  const [t, setT] = useStateFS(0);

  React.useEffect(() => {
    if (!playing) { setT(0); return; }
    let start = performance.now();
    let raf;
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  // Roster of fake employees that cycle through the feed.
  const EMPLOYEES = [
    { name: 'Avery Stone',    role: 'Repairs Operative',     patch: 'Patch South'  },
    { name: 'Jordan Vale',    role: 'Housing Officer',       patch: 'Patch North'  },
    { name: 'Riley Marsh',    role: 'Income Officer',        patch: 'Central'      },
    { name: 'Quinn Holloway', role: 'Contact Centre',        patch: 'HQ'           },
    { name: 'Sage Whitcombe', role: 'Tenancy Sustainment',   patch: 'Patch East'   },
    { name: 'Casey Pemberton',role: 'Caretaker',             patch: 'Patch West'   },
    { name: 'Morgan Caldwell',role: 'Surveyor',              patch: 'Patch South'  },
    { name: 'Drew Ashby',     role: 'Repairs Operative',     patch: 'Patch North'  },
    { name: 'Reese Lockwood', role: 'Housing Officer',       patch: 'Central'      },
    { name: 'Harper Linden',  role: 'Contact Centre',        patch: 'HQ'           },
  ];
  const L = EMPLOYEES.length;

  // ── Feed timing — a new employee arrives in the right panel every INTERVAL s.
  const INTERVAL = 2.2;
  const tick = t / INTERVAL;
  const topIdx = Math.floor(tick);
  const frac = tick - topIdx; // 0 → 1 over each interval

  // 4 slots, top → bottom. Top slot is the one currently arriving.
  const slots = [0, 1, 2, 3].map((i) => {
    const empIdx = ((topIdx - i) % L + L) % L;
    return EMPLOYEES[empIdx];
  });

  // Counter ticks up by one each time a new arrival lands in the feed.
  // Starts in the realistic mid-size-HA range.
  const baseCount = 287;
  const synced = baseCount + (playing ? topIdx : 0);

  // ── Sync-channel particles. Small initial-avatar tokens travelling left →
  // right. Each particle's phase loops independently and they're well-spaced
  // so labels never overlap.
  const PARTICLE_INITIALS = ['AS', 'JV', 'RM', 'QH'];
  const PARTICLE_COUNT = PARTICLE_INITIALS.length;
  const SPEED = 0.45; // full traversals per second
  const particles = Array.from({ length: PARTICLE_COUNT }, (_, i) => {
    const phase = ((t * SPEED) + i / PARTICLE_COUNT) % 1;
    return {
      phase,
      initials: PARTICLE_INITIALS[i],
      x: phase,
      opacity: Math.sin(phase * Math.PI),
    };
  });

  return (
    <FSFrame label="Sync · your HR platform → Colleague Pulse">
      <div className="relative w-full h-full bg-slate-50/60 overflow-hidden select-none">
        {/* Two-panel layout */}
        <div className="absolute inset-0 px-4 sm:px-5 py-4 flex items-stretch gap-3">
          {/* ── Left: Your HR Platform ──────────────────────────────── */}
          <div className="flex-1 rounded-lg bg-white border border-slate-200 flex flex-col overflow-hidden">
            <div className="px-3 py-2 border-b border-slate-100 flex items-center gap-2">
              <span className="inline-flex items-center justify-center h-5 w-5 rounded-md bg-slate-900 text-white shrink-0">
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <ellipse cx="12" cy="5" rx="9" ry="3" />
                  <path d="M3 5v6c0 1.7 4 3 9 3s9-1.3 9-3V5" />
                  <path d="M3 11v6c0 1.7 4 3 9 3s9-1.3 9-3v-6" />
                </svg>
              </span>
              <div className="min-w-0">
                <div className="text-[10px] uppercase tracking-wider font-semibold text-slate-500">HR Platform</div>
                <div className="text-[11px] font-semibold text-slate-900 truncate">Your existing system</div>
              </div>
              <div className="ml-auto inline-flex items-center gap-1 text-[9px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-100 px-1.5 py-0.5 rounded">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                Connected
              </div>
            </div>
            <div className="px-2.5 py-2 grid grid-cols-3 text-[9px] uppercase tracking-wider font-semibold text-slate-400 border-b border-slate-100">
              <div>Employee</div>
              <div>Role</div>
              <div>Location</div>
            </div>
            <div className="flex-1 overflow-hidden">
              {/* Static employee table — represents the HR-side snapshot. */}
              {EMPLOYEES.slice(0, 6).map((e, i) => (
                <div key={e.name} className="px-2.5 py-1.5 grid grid-cols-3 text-[10px] border-b border-slate-50">
                  <div className="font-semibold text-slate-800 truncate">{e.name}</div>
                  <div className="text-slate-600 truncate">{e.role}</div>
                  <div className="text-slate-500 truncate">{e.patch}</div>
                </div>
              ))}
              <div className="px-2.5 py-1.5 text-[9px] text-slate-400 italic">+ {(synced - 6).toLocaleString()} more</div>
            </div>
          </div>

          {/* ── Center: Sync channel ────────────────────────────────── */}
          <div className="w-[15%] relative flex flex-col items-center justify-center">
            {/* Dotted track */}
            <div className="absolute inset-y-0 left-1/2 -translate-x-1/2 flex flex-col justify-center">
              <div className="h-px w-full" />
            </div>
            <div className="absolute top-1/2 left-0 right-0 h-px -translate-y-1/2 border-t-2 border-dashed border-blue-200" />

            {/* Moving particles — small avatar tokens. */}
            {particles.map((p, i) => (
              <div
                key={i}
                className="absolute top-1/2"
                style={{
                  left: `${p.x * 100}%`,
                  transform: `translate(-50%, -50%)`,
                  opacity: p.opacity,
                  transition: 'none',
                }}
              >
                <div className="h-5 w-5 rounded-full bg-gradient-to-br from-blue-500 to-blue-700 text-white text-[8px] font-bold flex items-center justify-center shadow-md ring-2 ring-white">
                  {p.initials}
                </div>
              </div>
            ))}

            {/* Channel label */}
            <div className="absolute top-2 left-1/2 -translate-x-1/2 text-[9px] uppercase tracking-wider font-semibold text-slate-400 whitespace-nowrap">
              syncing
            </div>
          </div>

          {/* ── Right: Colleague Pulse ──────────────────────────────── */}
          <div className="flex-1 rounded-lg bg-white border border-slate-200 flex flex-col overflow-hidden">
            <div className="px-3 py-2 border-b border-slate-100 flex items-center gap-2">
              <img
                src="assets/colleague-pulse-logo.png"
                alt="Colleague Pulse"
                className="h-4 w-auto shrink-0"
                draggable="false"
              />
              <div className="ml-auto inline-flex items-center gap-1 text-[9px] font-semibold text-blue-700 bg-blue-50 border border-blue-100 px-1.5 py-0.5 rounded">
                <span className="h-1.5 w-1.5 rounded-full bg-blue-500" style={{ animation: 'sint-pulse 1.4s ease-in-out infinite' }} />
                Live sync
              </div>
            </div>
            <div className="px-3 py-2 flex items-baseline gap-1.5 border-b border-slate-100">
              <div className="text-[18px] font-bold text-slate-900 tabular-nums leading-none">
                {synced.toLocaleString()}
              </div>
              <div className="text-[10px] text-slate-500">employees synced</div>
            </div>
            <div className="px-2.5 py-1 text-[9px] uppercase tracking-wider font-semibold text-slate-400">
              Recent arrivals
            </div>
            <div className="flex-1 overflow-hidden">
              {slots.map((emp, i) => {
                // Top slot animates in; bottom slot animates out.
                let opacity = 1;
                let translateY = 0;
                let scale = 1;
                if (i === 0) {
                  opacity = playing ? frac : 1;
                  translateY = (1 - (playing ? frac : 1)) * -10;
                  scale = 0.96 + (playing ? frac : 1) * 0.04;
                } else if (i === 3) {
                  opacity = playing ? 1 - frac : 1;
                }
                return (
                  <div
                    key={`${topIdx}-${i}`}
                    className="px-2.5 py-1.5 border-b border-slate-50"
                    style={{
                      opacity,
                      transform: `translateY(${translateY}px) scale(${scale})`,
                      transformOrigin: 'left center',
                      transition: 'none',
                    }}
                  >
                    <div className="flex items-center gap-2">
                      <div className="h-5 w-5 rounded-full bg-gradient-to-br from-blue-500 to-blue-700 text-white text-[8px] font-bold flex items-center justify-center shrink-0">
                        {emp.name.split(' ').map(n => n[0]).join('')}
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="text-[10px] font-semibold text-slate-900 leading-tight truncate">{emp.name}</div>
                        <div className="text-[9px] text-slate-500 leading-tight truncate">{emp.role} · {emp.patch}</div>
                      </div>
                      {i === 0 && (
                        <span className="text-[8px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-100 px-1 py-px rounded shrink-0">
                          New
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <style>{`
          @keyframes sint-pulse {
            0%, 100% { transform: scale(1);    opacity: 1; }
            50%      { transform: scale(1.4);  opacity: 0.55; }
          }
        `}</style>
      </div>
    </FSFrame>
  );
}
