@air-jam/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +87 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/chunk-XSXI3RIS.js +72 -0
  4. package/dist/chunk-XSXI3RIS.js.map +1 -0
  5. package/dist/index.cjs +3514 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +1529 -0
  8. package/dist/index.d.ts +1529 -0
  9. package/dist/index.js +3366 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/protocol.cjs +85 -0
  12. package/dist/protocol.cjs.map +1 -0
  13. package/dist/protocol.d.cts +242 -0
  14. package/dist/protocol.d.ts +242 -0
  15. package/dist/protocol.js +3 -0
  16. package/dist/protocol.js.map +1 -0
  17. package/package.json +81 -0
  18. package/src/AirJamClient.ts +775 -0
  19. package/src/audio/audio-manager.ts +395 -0
  20. package/src/audio/hooks.tsx +140 -0
  21. package/src/audio/index.ts +3 -0
  22. package/src/audio/volume-store.ts +77 -0
  23. package/src/components/air-jam-overlay.tsx +456 -0
  24. package/src/components/controller-shell.tsx +329 -0
  25. package/src/components/qr-scanner-dialog.tsx +373 -0
  26. package/src/components/ui/alert.tsx +66 -0
  27. package/src/components/ui/avatar.tsx +46 -0
  28. package/src/components/ui/badge.tsx +47 -0
  29. package/src/components/ui/button.tsx +61 -0
  30. package/src/components/ui/card.tsx +92 -0
  31. package/src/components/ui/slider.tsx +61 -0
  32. package/src/components/ui/tabs.tsx +64 -0
  33. package/src/components/volume-controls.tsx +93 -0
  34. package/src/constants.ts +45 -0
  35. package/src/context/air-jam-context.tsx +478 -0
  36. package/src/context/index.ts +2 -0
  37. package/src/context/socket-manager.ts +98 -0
  38. package/src/events.ts +151 -0
  39. package/src/hooks/use-air-jam-controller.ts +608 -0
  40. package/src/hooks/use-air-jam-host.ts +624 -0
  41. package/src/hooks/use-air-jam-shell.ts +343 -0
  42. package/src/hooks/use-fullscreen.ts +108 -0
  43. package/src/hooks/use-get-input.ts +97 -0
  44. package/src/hooks/use-send-signal.ts +164 -0
  45. package/src/index.ts +33 -0
  46. package/src/internal/input-manager.ts +362 -0
  47. package/src/protocol.ts +331 -0
  48. package/src/state/connection-store.ts +84 -0
  49. package/src/styles.css +128 -0
  50. package/src/types/browser.ts +42 -0
  51. package/src/utils/cn.ts +4 -0
  52. package/src/utils/ids.ts +31 -0
  53. package/src/utils/index.ts +1 -0
  54. package/src/utils/mode.ts +13 -0
  55. package/src/utils/network-ip.ts +145 -0
  56. package/src/utils/url-builder.ts +170 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,3514 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var zustand = require('zustand');
5
+ var shallow = require('zustand/react/shallow');
6
+ var socket_ioClient = require('socket.io-client');
7
+ var jsxRuntime = require('react/jsx-runtime');
8
+ var howler = require('howler');
9
+ var lucideReact = require('lucide-react');
10
+ var QRCode = require('qrcode');
11
+ var classVarianceAuthority = require('class-variance-authority');
12
+ var clsx = require('clsx');
13
+ var tailwindMerge = require('tailwind-merge');
14
+ var reactSlot = require('@radix-ui/react-slot');
15
+ var TabsPrimitive = require('@radix-ui/react-tabs');
16
+ var SliderPrimitive = require('@radix-ui/react-slider');
17
+ var html5Qrcode = require('html5-qrcode');
18
+ var zod = require('zod');
19
+
20
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
22
+
23
+ function _interopNamespace(e) {
24
+ if (e && e.__esModule) return e;
25
+ var n = Object.create(null);
26
+ if (e) {
27
+ Object.keys(e).forEach(function (k) {
28
+ if (k !== 'default') {
29
+ var d = Object.getOwnPropertyDescriptor(e, k);
30
+ Object.defineProperty(n, k, d.get ? d : {
31
+ enumerable: true,
32
+ get: function () { return e[k]; }
33
+ });
34
+ }
35
+ });
36
+ }
37
+ n.default = e;
38
+ return Object.freeze(n);
39
+ }
40
+
41
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
42
+ var QRCode__default = /*#__PURE__*/_interopDefault(QRCode);
43
+ var TabsPrimitive__namespace = /*#__PURE__*/_interopNamespace(TabsPrimitive);
44
+ var SliderPrimitive__namespace = /*#__PURE__*/_interopNamespace(SliderPrimitive);
45
+
46
+ // src/context/air-jam-context.tsx
47
+
48
+ // src/constants.ts
49
+ var DEFAULT_SERVER_PORT = 4e3;
50
+ var DEFAULT_CONTROLLER_PATH = "/joypad";
51
+ var INPUT_DEBOUNCE_MS = 200;
52
+ var TOGGLE_DEBOUNCE_MS = 300;
53
+ var SOCKET_CONFIG = {
54
+ /**
55
+ * Ping interval in milliseconds
56
+ */
57
+ PING_INTERVAL: 2e3,
58
+ /**
59
+ * Ping timeout in milliseconds
60
+ */
61
+ PING_TIMEOUT: 5e3
62
+ };
63
+ var DEFAULT_MAX_PLAYERS = 8;
64
+
65
+ // src/internal/input-manager.ts
66
+ var InputManager = class {
67
+ inputBuffer = /* @__PURE__ */ new Map();
68
+ latchState = /* @__PURE__ */ new Map();
69
+ config;
70
+ roomId;
71
+ constructor(config = {}, roomId) {
72
+ this.config = config;
73
+ this.roomId = roomId;
74
+ }
75
+ /**
76
+ * Handles incoming input events from the socket.
77
+ * Should be called when 'server:input' event is received.
78
+ */
79
+ handleInput(payload) {
80
+ if (this.roomId && payload.roomId !== this.roomId) {
81
+ return;
82
+ }
83
+ this.inputBuffer.set(payload.controllerId, payload.input);
84
+ }
85
+ /**
86
+ * Gets input for a specific controller.
87
+ * Returns validated and typed input if schema is provided, otherwise raw Record.
88
+ * If latching is configured, applies latching logic.
89
+ */
90
+ getInput(controllerId) {
91
+ const rawInput = this.inputBuffer.get(controllerId);
92
+ if (!rawInput) {
93
+ return void 0;
94
+ }
95
+ let validatedInput = rawInput;
96
+ if (this.config.schema) {
97
+ const result = this.config.schema.safeParse(rawInput);
98
+ if (!result.success) {
99
+ console.warn(
100
+ `[InputManager] Invalid input for controller ${controllerId}:`,
101
+ result.error
102
+ );
103
+ return void 0;
104
+ }
105
+ validatedInput = result.data;
106
+ }
107
+ if (this.config.latch) {
108
+ return this.getLatched(
109
+ controllerId,
110
+ validatedInput
111
+ );
112
+ }
113
+ return validatedInput;
114
+ }
115
+ /**
116
+ * Clears input state for a controller (e.g., when player leaves).
117
+ */
118
+ clearInput(controllerId) {
119
+ this.inputBuffer.delete(controllerId);
120
+ this.latchState.delete(controllerId);
121
+ }
122
+ /**
123
+ * Updates the room ID filter.
124
+ */
125
+ setRoomId(roomId) {
126
+ this.roomId = roomId;
127
+ }
128
+ /**
129
+ * Internal method to apply latching logic.
130
+ */
131
+ getLatched(controllerId, rawInput) {
132
+ const { booleanFields = [], vectorFields = [] } = this.config.latch;
133
+ const state = this.latchState.get(controllerId);
134
+ const rawHash = JSON.stringify(rawInput);
135
+ const rawChanged = rawHash !== state?.lastRawHash;
136
+ if (!rawChanged && state) {
137
+ const resetLatched = { ...rawInput };
138
+ const resetLatchedRecord = resetLatched;
139
+ const actualRawRecord2 = rawInput;
140
+ for (const field of booleanFields) {
141
+ const rawValue = actualRawRecord2[field];
142
+ resetLatchedRecord[field] = rawValue ?? false;
143
+ }
144
+ for (const field of vectorFields) {
145
+ const rawValue = actualRawRecord2[field];
146
+ if (rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) {
147
+ const rawVec = rawValue;
148
+ if (typeof rawVec.x === "number" && typeof rawVec.y === "number") {
149
+ resetLatchedRecord[field] = rawVec;
150
+ } else {
151
+ resetLatchedRecord[field] = { x: 0, y: 0 };
152
+ }
153
+ } else {
154
+ resetLatchedRecord[field] = { x: 0, y: 0 };
155
+ }
156
+ }
157
+ this.latchState.set(controllerId, {
158
+ raw: rawInput,
159
+ latched: resetLatched,
160
+ lastRawHash: rawHash
161
+ });
162
+ return resetLatched;
163
+ }
164
+ const prevLatched = state?.latched ?? {};
165
+ const latched = { ...rawInput };
166
+ const latchedRecord = latched;
167
+ const actualRawRecord = rawInput;
168
+ const prevLatchedRecord = prevLatched;
169
+ for (const field of booleanFields) {
170
+ const rawValue = actualRawRecord[field];
171
+ const prevValue = prevLatchedRecord[field];
172
+ if (typeof rawValue === "boolean") {
173
+ latchedRecord[field] = rawValue || prevValue === true;
174
+ }
175
+ }
176
+ for (const field of vectorFields) {
177
+ const rawValue = actualRawRecord[field];
178
+ const prevValue = prevLatchedRecord[field];
179
+ if (rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) {
180
+ const rawVec = rawValue;
181
+ const prevVec = prevValue;
182
+ if (typeof rawVec.x === "number" && typeof rawVec.y === "number") {
183
+ const isRawActive = rawVec.x !== 0 || rawVec.y !== 0;
184
+ const isPrevActive = prevVec && typeof prevVec.x === "number" && typeof prevVec.y === "number" && (prevVec.x !== 0 || prevVec.y !== 0);
185
+ if (isRawActive) {
186
+ latchedRecord[field] = rawVec;
187
+ } else if (isPrevActive) {
188
+ latchedRecord[field] = prevVec;
189
+ } else {
190
+ latchedRecord[field] = { x: 0, y: 0 };
191
+ }
192
+ }
193
+ }
194
+ }
195
+ this.latchState.set(controllerId, {
196
+ raw: rawInput,
197
+ latched,
198
+ lastRawHash: rawHash
199
+ });
200
+ return latched;
201
+ }
202
+ };
203
+ var createAirJamStore = () => zustand.create((set) => ({
204
+ role: null,
205
+ roomId: null,
206
+ controllerId: null,
207
+ connectionStatus: "idle",
208
+ mode: "standalone",
209
+ gameState: "paused",
210
+ stateMessage: void 0,
211
+ players: [],
212
+ lastError: void 0,
213
+ registeredRoomId: null,
214
+ setRole: (role) => set({ role }),
215
+ setRoomId: (roomId) => set({ roomId }),
216
+ setControllerId: (controllerId) => set({ controllerId }),
217
+ setStatus: (connectionStatus) => set({ connectionStatus }),
218
+ setMode: (mode) => set({ mode }),
219
+ setGameState: (gameState) => set({ gameState }),
220
+ setStateMessage: (stateMessage) => set({ stateMessage }),
221
+ toggleGameState: () => set((state) => ({
222
+ gameState: state.gameState === "paused" ? "playing" : "paused"
223
+ })),
224
+ setError: (message) => set({ lastError: message }),
225
+ upsertPlayer: (player) => set((state) => {
226
+ const existingIndex = state.players.findIndex(
227
+ (entry) => entry.id === player.id
228
+ );
229
+ if (existingIndex >= 0) {
230
+ const nextPlayers = [...state.players];
231
+ nextPlayers[existingIndex] = player;
232
+ return { players: nextPlayers };
233
+ }
234
+ return { players: [...state.players, player] };
235
+ }),
236
+ removePlayer: (playerId) => set((state) => ({
237
+ players: state.players.filter((player) => player.id !== playerId)
238
+ })),
239
+ resetPlayers: () => set({ players: [] }),
240
+ resetGameState: () => set({ gameState: "paused", stateMessage: void 0 }),
241
+ setRegisteredRoomId: (roomId) => set({ registeredRoomId: roomId })
242
+ }));
243
+ var SocketManager = class {
244
+ sockets = {};
245
+ serverUrl;
246
+ constructor(serverUrl) {
247
+ this.serverUrl = this.resolveServerUrl(serverUrl);
248
+ }
249
+ /**
250
+ * Get or create a socket for the specified role.
251
+ * Sockets are lazily created and cached per role.
252
+ */
253
+ getSocket(role) {
254
+ const existing = this.sockets[role];
255
+ if (existing) {
256
+ return existing;
257
+ }
258
+ const socket = socket_ioClient.io(this.serverUrl, {
259
+ autoConnect: false,
260
+ transports: ["websocket"],
261
+ query: { role }
262
+ });
263
+ this.sockets[role] = socket;
264
+ return socket;
265
+ }
266
+ /**
267
+ * Disconnect a socket by role.
268
+ * NOTE: We intentionally do NOT delete the socket from cache.
269
+ * This ensures all hooks using getSocket() get the same instance,
270
+ * even during React Strict Mode remounts. The socket can be reconnected
271
+ * by calling socket.connect() again.
272
+ */
273
+ disconnect(role) {
274
+ const socket = this.sockets[role];
275
+ if (socket) {
276
+ socket.disconnect();
277
+ }
278
+ }
279
+ /**
280
+ * Disconnect all sockets managed by this instance
281
+ */
282
+ disconnectAll() {
283
+ for (const role of Object.keys(this.sockets)) {
284
+ this.disconnect(role);
285
+ }
286
+ }
287
+ /**
288
+ * Get the resolved server URL
289
+ */
290
+ getServerUrl() {
291
+ return this.serverUrl;
292
+ }
293
+ /**
294
+ * Resolve server URL with fallbacks
295
+ */
296
+ resolveServerUrl(explicit) {
297
+ if (explicit) {
298
+ return this.normalizeOrigin(explicit);
299
+ }
300
+ if (typeof window !== "undefined") {
301
+ const url = new URL(window.location.href);
302
+ url.port = String(DEFAULT_SERVER_PORT);
303
+ return url.origin;
304
+ }
305
+ return `http://localhost:${DEFAULT_SERVER_PORT}`;
306
+ }
307
+ normalizeOrigin(origin) {
308
+ if (!origin.includes("://")) {
309
+ return `http://${origin}`;
310
+ }
311
+ return origin;
312
+ }
313
+ };
314
+ var AirJamContext = React.createContext(null);
315
+ var getViteEnv = () => {
316
+ try {
317
+ const meta = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) });
318
+ if (meta && typeof meta.env === "object") {
319
+ return meta.env;
320
+ }
321
+ } catch {
322
+ }
323
+ return void 0;
324
+ };
325
+ var getEnvServerUrl = () => {
326
+ const viteEnv = getViteEnv();
327
+ if (viteEnv?.VITE_AIR_JAM_SERVER_URL) {
328
+ return viteEnv.VITE_AIR_JAM_SERVER_URL;
329
+ }
330
+ if (typeof process !== "undefined" && process.env) {
331
+ const nextUrl = process.env.NEXT_PUBLIC_AIR_JAM_SERVER_URL;
332
+ if (nextUrl) return nextUrl;
333
+ }
334
+ return void 0;
335
+ };
336
+ var getEnvApiKey = () => {
337
+ const viteEnv = getViteEnv();
338
+ if (viteEnv?.VITE_AIR_JAM_API_KEY) {
339
+ return viteEnv.VITE_AIR_JAM_API_KEY;
340
+ }
341
+ if (typeof process !== "undefined" && process.env) {
342
+ const nextKey = process.env.NEXT_PUBLIC_AIR_JAM_API_KEY;
343
+ if (nextKey) return nextKey;
344
+ }
345
+ return void 0;
346
+ };
347
+ var AirJamProvider = ({
348
+ children,
349
+ serverUrl,
350
+ apiKey,
351
+ controllerPath = DEFAULT_CONTROLLER_PATH,
352
+ maxPlayers = DEFAULT_MAX_PLAYERS,
353
+ publicHost,
354
+ input
355
+ }) => {
356
+ const config = React.useMemo(
357
+ () => ({
358
+ serverUrl: serverUrl ?? getEnvServerUrl(),
359
+ apiKey: apiKey ?? getEnvApiKey(),
360
+ controllerPath,
361
+ maxPlayers,
362
+ publicHost
363
+ }),
364
+ [serverUrl, apiKey, controllerPath, maxPlayers, publicHost]
365
+ );
366
+ const inputManager = React.useMemo(() => {
367
+ if (!input) {
368
+ return null;
369
+ }
370
+ return new InputManager(input);
371
+ }, [input]);
372
+ const store = React.useMemo(() => createAirJamStore(), []);
373
+ const socketManager = React.useMemo(
374
+ () => new SocketManager(config.serverUrl),
375
+ // Only recreate if serverUrl changes - intentionally omitting config
376
+ [config.serverUrl]
377
+ );
378
+ React.useEffect(() => {
379
+ return () => {
380
+ socketManager.disconnectAll();
381
+ };
382
+ }, [socketManager]);
383
+ const getSocket = React.useCallback(
384
+ (role) => socketManager.getSocket(role),
385
+ [socketManager]
386
+ );
387
+ const disconnectSocket = React.useCallback(
388
+ (role) => socketManager.disconnect(role),
389
+ [socketManager]
390
+ );
391
+ const contextValue = React.useMemo(
392
+ () => ({
393
+ config,
394
+ store,
395
+ socketManager,
396
+ getSocket,
397
+ disconnectSocket,
398
+ inputManager
399
+ }),
400
+ [config, store, socketManager, getSocket, disconnectSocket, inputManager]
401
+ );
402
+ return /* @__PURE__ */ jsxRuntime.jsx(AirJamContext.Provider, { value: contextValue, children });
403
+ };
404
+ var useAirJamContext = () => {
405
+ const context = React.useContext(AirJamContext);
406
+ if (!context) {
407
+ throw new Error(
408
+ "useAirJamContext must be used within an AirJamProvider. Wrap your app or component tree with <AirJamProvider>."
409
+ );
410
+ }
411
+ return context;
412
+ };
413
+ var useAirJamConfig = () => {
414
+ return useAirJamContext().config;
415
+ };
416
+ var useAirJamState = (selector) => {
417
+ const { store } = useAirJamContext();
418
+ return zustand.useStore(store, shallow.useShallow(selector));
419
+ };
420
+ var useAirJamSocket = (role) => {
421
+ const { getSocket } = useAirJamContext();
422
+ return React.useMemo(() => getSocket(role), [getSocket, role]);
423
+ };
424
+ var STORAGE_KEY = "air-jam-volume-settings";
425
+ var loadFromStorage = () => {
426
+ if (typeof window === "undefined") return {};
427
+ try {
428
+ const stored = localStorage.getItem(STORAGE_KEY);
429
+ if (stored) {
430
+ const parsed = JSON.parse(stored);
431
+ return {
432
+ masterVolume: parsed.masterVolume ?? 1,
433
+ musicVolume: parsed.musicVolume ?? 0.8,
434
+ sfxVolume: parsed.sfxVolume ?? 1
435
+ };
436
+ }
437
+ } catch {
438
+ }
439
+ return {};
440
+ };
441
+ var saveToStorage = (state) => {
442
+ if (typeof window === "undefined") return;
443
+ try {
444
+ localStorage.setItem(
445
+ STORAGE_KEY,
446
+ JSON.stringify({
447
+ masterVolume: state.masterVolume,
448
+ musicVolume: state.musicVolume,
449
+ sfxVolume: state.sfxVolume
450
+ })
451
+ );
452
+ } catch {
453
+ }
454
+ };
455
+ var initialValues = loadFromStorage();
456
+ var useVolumeStore = zustand.create((set, get) => ({
457
+ masterVolume: initialValues.masterVolume ?? 1,
458
+ musicVolume: initialValues.musicVolume ?? 0.8,
459
+ sfxVolume: initialValues.sfxVolume ?? 1,
460
+ setMasterVolume: (volume) => {
461
+ const clamped = Math.max(0, Math.min(1, volume));
462
+ set({ masterVolume: clamped });
463
+ saveToStorage({ ...get(), masterVolume: clamped });
464
+ },
465
+ setMusicVolume: (volume) => {
466
+ const clamped = Math.max(0, Math.min(1, volume));
467
+ set({ musicVolume: clamped });
468
+ saveToStorage({ ...get(), musicVolume: clamped });
469
+ },
470
+ setSfxVolume: (volume) => {
471
+ const clamped = Math.max(0, Math.min(1, volume));
472
+ set({ sfxVolume: clamped });
473
+ saveToStorage({ ...get(), sfxVolume: clamped });
474
+ },
475
+ getEffectiveVolume: (category) => {
476
+ const { masterVolume, musicVolume, sfxVolume } = get();
477
+ const categoryVolume = category === "music" ? musicVolume : sfxVolume;
478
+ return masterVolume * categoryVolume;
479
+ }
480
+ }));
481
+
482
+ // src/audio/audio-manager.ts
483
+ function detectSoundCategory(config) {
484
+ if (config.category) {
485
+ return config.category;
486
+ }
487
+ if (config.loop && config.html5) {
488
+ return "music";
489
+ }
490
+ return "sfx";
491
+ }
492
+ var AudioManager = class {
493
+ sounds = /* @__PURE__ */ new Map();
494
+ categories = /* @__PURE__ */ new Map();
495
+ manifest = {};
496
+ _muted = false;
497
+ socket = null;
498
+ roomId = null;
499
+ activeSoundIds = /* @__PURE__ */ new Map();
500
+ volumeUnsubscribe = null;
501
+ constructor(manifest) {
502
+ const initialState = useVolumeStore.getState();
503
+ const updateAllSounds = (state) => {
504
+ this.activeSoundIds.forEach((info, howlSoundId) => {
505
+ const sound = this.sounds.get(info.soundId);
506
+ if (sound) {
507
+ const config = this.manifest[info.soundId];
508
+ const baseVolume = config?.volume ?? 1;
509
+ const effectiveVolume = state.getEffectiveVolume(info.category);
510
+ const finalVolume = baseVolume * effectiveVolume;
511
+ sound.volume(finalVolume, howlSoundId);
512
+ }
513
+ });
514
+ this.sounds.forEach((sound, soundId) => {
515
+ const category = this.categories.get(soundId) ?? "sfx";
516
+ const config = this.manifest[soundId];
517
+ const baseVolume = config?.volume ?? 1;
518
+ const effectiveVolume = state.getEffectiveVolume(category);
519
+ const newVolume = baseVolume * effectiveVolume;
520
+ sound.volume(newVolume);
521
+ });
522
+ };
523
+ this.volumeUnsubscribe = useVolumeStore.subscribe(updateAllSounds);
524
+ if (manifest) {
525
+ this.load(manifest);
526
+ updateAllSounds(initialState);
527
+ }
528
+ }
529
+ /**
530
+ * Cleanup method to unsubscribe from volume changes
531
+ */
532
+ destroy() {
533
+ if (this.volumeUnsubscribe) {
534
+ this.volumeUnsubscribe();
535
+ this.volumeUnsubscribe = null;
536
+ }
537
+ }
538
+ /**
539
+ * Get the category for a sound (with auto-detection)
540
+ */
541
+ getCategory(soundId) {
542
+ return this.categories.get(soundId) ?? "sfx";
543
+ }
544
+ setSocket(socket, roomId) {
545
+ this.socket = socket;
546
+ if (roomId) this.roomId = roomId;
547
+ }
548
+ /**
549
+ * Initialize audio context (must be called on user interaction)
550
+ */
551
+ init() {
552
+ if (howler.Howler.ctx && howler.Howler.ctx.state === "suspended") {
553
+ howler.Howler.ctx.resume();
554
+ }
555
+ }
556
+ /**
557
+ * Check if audio context is ready to play sounds
558
+ */
559
+ isReady() {
560
+ return howler.Howler.ctx !== null && howler.Howler.ctx.state === "running";
561
+ }
562
+ load(manifest) {
563
+ this.manifest = { ...this.manifest, ...manifest };
564
+ const volumeStore = useVolumeStore.getState();
565
+ Object.entries(manifest).forEach(([key, config]) => {
566
+ if (this.sounds.has(key)) return;
567
+ const category = detectSoundCategory(config);
568
+ this.categories.set(key, category);
569
+ const baseVolume = config.volume ?? 1;
570
+ const effectiveVolume = volumeStore.getEffectiveVolume(category);
571
+ const initialVolume = baseVolume * effectiveVolume;
572
+ const sound = new howler.Howl({
573
+ src: config.src,
574
+ volume: initialVolume,
575
+ // Use effective volume from the start
576
+ loop: config.loop ?? false,
577
+ html5: config.html5 ?? false,
578
+ sprite: config.sprite,
579
+ preload: true
580
+ });
581
+ this.sounds.set(key, sound);
582
+ });
583
+ }
584
+ play(id, options) {
585
+ const {
586
+ remote = false,
587
+ target,
588
+ volume,
589
+ loop,
590
+ sprite,
591
+ pitch
592
+ } = options || {};
593
+ if (remote) {
594
+ this.playRemote(id, target, volume, loop);
595
+ return null;
596
+ } else {
597
+ return this.playLocal(id, volume, loop, sprite, pitch);
598
+ }
599
+ }
600
+ playLocal(id, volume, loop, sprite, pitch) {
601
+ const sound = this.sounds.get(id);
602
+ if (!sound) {
603
+ console.warn(`Sound "${id}" not found`);
604
+ return null;
605
+ }
606
+ const category = this.getCategory(id);
607
+ const config = this.manifest[id];
608
+ const baseVolume = config?.volume ?? 1;
609
+ const volumeStore = useVolumeStore.getState();
610
+ const effectiveVolume = volumeStore.getEffectiveVolume(category);
611
+ const finalVolume = volume !== void 0 ? volume * effectiveVolume : baseVolume * effectiveVolume;
612
+ const soundId = sound.play(sprite);
613
+ this.activeSoundIds.set(soundId, { soundId: id, category });
614
+ sound.once("end", () => {
615
+ this.activeSoundIds.delete(soundId);
616
+ });
617
+ sound.volume(finalVolume, soundId);
618
+ if (loop !== void 0) sound.loop(loop, soundId);
619
+ if (pitch !== void 0) sound.rate(pitch, soundId);
620
+ return soundId;
621
+ }
622
+ playRemote(id, target, volume, loop) {
623
+ if (!this.socket || !this.roomId) return;
624
+ if (this.isHost()) {
625
+ this.socket.emit("host:play_sound", {
626
+ roomId: this.roomId,
627
+ targetControllerId: target,
628
+ // If undefined, broadcasts to all
629
+ soundId: id,
630
+ volume,
631
+ loop
632
+ });
633
+ } else {
634
+ this.socket.emit("controller:play_sound", {
635
+ roomId: this.roomId,
636
+ soundId: id,
637
+ volume,
638
+ loop
639
+ });
640
+ }
641
+ }
642
+ isHost() {
643
+ const query = this.socket?.io?.opts?.query;
644
+ return query && typeof query === "object" && "role" in query && query.role === "host" || false;
645
+ }
646
+ /**
647
+ * Play a sound at a specific 3D position
648
+ */
649
+ playSpatial(id, pos, sprite) {
650
+ const soundId = this.playLocal(id, void 0, void 0, sprite);
651
+ if (soundId !== null) {
652
+ const sound = this.sounds.get(id);
653
+ if (sound) {
654
+ sound.pos(pos.x, pos.y, pos.z, soundId);
655
+ sound.pannerAttr(
656
+ {
657
+ panningModel: "HRTF",
658
+ refDistance: 1,
659
+ maxDistance: 1e3,
660
+ rolloffFactor: 1,
661
+ distanceModel: "inverse"
662
+ },
663
+ soundId
664
+ );
665
+ }
666
+ }
667
+ return soundId;
668
+ }
669
+ stop(id, soundId) {
670
+ if (id) {
671
+ const sound = this.sounds.get(id);
672
+ sound?.stop(soundId);
673
+ if (soundId !== void 0) {
674
+ this.activeSoundIds.delete(soundId);
675
+ } else {
676
+ this.activeSoundIds.forEach((info, howlSoundId) => {
677
+ if (info.soundId === id) {
678
+ this.activeSoundIds.delete(howlSoundId);
679
+ }
680
+ });
681
+ }
682
+ } else {
683
+ howler.Howler.stop();
684
+ this.activeSoundIds.clear();
685
+ }
686
+ }
687
+ volume(vol, id, soundId) {
688
+ if (id) {
689
+ const sound = this.sounds.get(id);
690
+ if (sound) {
691
+ if (soundId !== void 0) {
692
+ sound.volume(vol, soundId);
693
+ } else {
694
+ sound.volume(vol);
695
+ }
696
+ }
697
+ } else {
698
+ howler.Howler.volume(vol);
699
+ }
700
+ }
701
+ mute(muted, id, soundId) {
702
+ if (id) {
703
+ const sound = this.sounds.get(id);
704
+ sound?.mute(muted, soundId);
705
+ } else {
706
+ this._muted = muted;
707
+ howler.Howler.mute(muted);
708
+ }
709
+ }
710
+ isMuted() {
711
+ return this._muted;
712
+ }
713
+ /**
714
+ * Update the listener position for spatial audio
715
+ */
716
+ setListenerPos(x, y, z2) {
717
+ howler.Howler.pos(x, y, z2);
718
+ }
719
+ /**
720
+ * Update the listener orientation for spatial audio
721
+ */
722
+ setListenerOrientation(x, y, z2, xUp, yUp, zUp) {
723
+ howler.Howler.orientation(x, y, z2, xUp, yUp, zUp);
724
+ }
725
+ };
726
+ var createAudioManager = (manifest) => new AudioManager(manifest);
727
+ var managerCache = /* @__PURE__ */ new WeakMap();
728
+ var globalInitialized = false;
729
+ function useAudio(manifest) {
730
+ const { store, getSocket } = useAirJamContext();
731
+ const roomId = zustand.useStore(store, (state) => state.roomId);
732
+ const role = zustand.useStore(store, (state) => state.role);
733
+ const initRef = React.useRef(false);
734
+ let manager = managerCache.get(manifest);
735
+ if (!manager) {
736
+ manager = new AudioManager(manifest);
737
+ managerCache.set(manifest, manager);
738
+ }
739
+ React.useEffect(() => {
740
+ if (role && roomId) {
741
+ const socket = getSocket(role);
742
+ manager.setSocket(socket, roomId);
743
+ }
744
+ }, [manager, role, roomId, getSocket]);
745
+ React.useEffect(() => {
746
+ if (initRef.current || globalInitialized) return;
747
+ const handleInteraction = () => {
748
+ manager.init();
749
+ globalInitialized = true;
750
+ initRef.current = true;
751
+ window.removeEventListener("click", handleInteraction);
752
+ window.removeEventListener("touchstart", handleInteraction);
753
+ window.removeEventListener("keydown", handleInteraction);
754
+ };
755
+ window.addEventListener("click", handleInteraction);
756
+ window.addEventListener("touchstart", handleInteraction);
757
+ window.addEventListener("keydown", handleInteraction);
758
+ return () => {
759
+ window.removeEventListener("click", handleInteraction);
760
+ window.removeEventListener("touchstart", handleInteraction);
761
+ window.removeEventListener("keydown", handleInteraction);
762
+ };
763
+ }, [manager]);
764
+ return manager;
765
+ }
766
+ var LegacyAudioContext = React.createContext(null);
767
+ var AudioProvider = ({
768
+ children,
769
+ manager
770
+ }) => {
771
+ const { store, getSocket } = useAirJamContext();
772
+ const roomId = zustand.useStore(store, (state) => state.roomId);
773
+ const role = zustand.useStore(store, (state) => state.role);
774
+ React.useEffect(() => {
775
+ if (role && roomId) {
776
+ const socket = getSocket(role);
777
+ manager.setSocket(socket, roomId);
778
+ }
779
+ }, [manager, role, roomId, getSocket]);
780
+ React.useEffect(() => {
781
+ const handleInteraction = () => {
782
+ manager.init();
783
+ window.removeEventListener("click", handleInteraction);
784
+ window.removeEventListener("touchstart", handleInteraction);
785
+ window.removeEventListener("keydown", handleInteraction);
786
+ };
787
+ window.addEventListener("click", handleInteraction);
788
+ window.addEventListener("touchstart", handleInteraction);
789
+ window.addEventListener("keydown", handleInteraction);
790
+ return () => {
791
+ window.removeEventListener("click", handleInteraction);
792
+ window.removeEventListener("touchstart", handleInteraction);
793
+ window.removeEventListener("keydown", handleInteraction);
794
+ };
795
+ }, [manager]);
796
+ return /* @__PURE__ */ jsxRuntime.jsx(LegacyAudioContext.Provider, { value: manager, children });
797
+ };
798
+ var useAudioLegacy = () => {
799
+ const manager = React.useContext(LegacyAudioContext);
800
+ if (!manager) {
801
+ throw new Error("useAudioLegacy must be used within an AudioProvider");
802
+ }
803
+ return manager;
804
+ };
805
+ var useAudioManager = (manifest) => {
806
+ const managerRef = React.useRef(null);
807
+ if (!managerRef.current) {
808
+ managerRef.current = new AudioManager(manifest);
809
+ }
810
+ return managerRef.current;
811
+ };
812
+ var cn = (...inputs) => tailwindMerge.twMerge(clsx.clsx(inputs));
813
+ var alertVariants = classVarianceAuthority.cva(
814
+ "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
815
+ {
816
+ variants: {
817
+ variant: {
818
+ default: "bg-card text-card-foreground",
819
+ destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
820
+ }
821
+ },
822
+ defaultVariants: {
823
+ variant: "default"
824
+ }
825
+ }
826
+ );
827
+ function Alert({
828
+ className,
829
+ variant,
830
+ ...props
831
+ }) {
832
+ return /* @__PURE__ */ jsxRuntime.jsx(
833
+ "div",
834
+ {
835
+ "data-slot": "alert",
836
+ role: "alert",
837
+ className: cn(alertVariants({ variant }), className),
838
+ ...props
839
+ }
840
+ );
841
+ }
842
+ function AlertDescription({
843
+ className,
844
+ ...props
845
+ }) {
846
+ return /* @__PURE__ */ jsxRuntime.jsx(
847
+ "div",
848
+ {
849
+ "data-slot": "alert-description",
850
+ className: cn(
851
+ "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
852
+ className
853
+ ),
854
+ ...props
855
+ }
856
+ );
857
+ }
858
+ var Avatar = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
859
+ "div",
860
+ {
861
+ ref,
862
+ className: cn(
863
+ "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
864
+ className
865
+ ),
866
+ ...props
867
+ }
868
+ ));
869
+ Avatar.displayName = "Avatar";
870
+ var AvatarImage = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
871
+ "img",
872
+ {
873
+ ref,
874
+ className: cn("aspect-square h-full w-full", className),
875
+ ...props
876
+ }
877
+ ));
878
+ AvatarImage.displayName = "AvatarImage";
879
+ var AvatarFallback = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
880
+ "div",
881
+ {
882
+ ref,
883
+ className: cn(
884
+ "bg-muted flex h-full w-full items-center justify-center rounded-full",
885
+ className
886
+ ),
887
+ ...props
888
+ }
889
+ ));
890
+ AvatarFallback.displayName = "AvatarFallback";
891
+ var badgeVariants = classVarianceAuthority.cva(
892
+ "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
893
+ {
894
+ variants: {
895
+ variant: {
896
+ default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
897
+ secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
898
+ destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
899
+ outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
900
+ }
901
+ },
902
+ defaultVariants: {
903
+ variant: "default"
904
+ }
905
+ }
906
+ );
907
+ function Badge({
908
+ className,
909
+ variant,
910
+ asChild = false,
911
+ ...props
912
+ }) {
913
+ const Comp = asChild ? reactSlot.Slot : "span";
914
+ return /* @__PURE__ */ jsxRuntime.jsx(
915
+ Comp,
916
+ {
917
+ "data-slot": "badge",
918
+ className: cn(badgeVariants({ variant }), className),
919
+ ...props
920
+ }
921
+ );
922
+ }
923
+ var buttonVariants = classVarianceAuthority.cva(
924
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
925
+ {
926
+ variants: {
927
+ variant: {
928
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
929
+ destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
930
+ outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
931
+ secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
932
+ ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
933
+ link: "text-primary underline-offset-4 hover:underline"
934
+ },
935
+ size: {
936
+ default: "h-9 px-4 py-2 has-[>svg]:px-3",
937
+ sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
938
+ lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
939
+ icon: "size-9",
940
+ "icon-sm": "size-8",
941
+ "icon-lg": "size-10"
942
+ }
943
+ },
944
+ defaultVariants: {
945
+ variant: "default",
946
+ size: "default"
947
+ }
948
+ }
949
+ );
950
+ function Button({
951
+ className,
952
+ variant,
953
+ size,
954
+ asChild = false,
955
+ ...props
956
+ }) {
957
+ const Comp = asChild ? reactSlot.Slot : "button";
958
+ return /* @__PURE__ */ jsxRuntime.jsx(
959
+ Comp,
960
+ {
961
+ "data-slot": "button",
962
+ className: cn(buttonVariants({ variant, size, className })),
963
+ ...props
964
+ }
965
+ );
966
+ }
967
+ function Card({ className, ...props }) {
968
+ return /* @__PURE__ */ jsxRuntime.jsx(
969
+ "div",
970
+ {
971
+ "data-slot": "card",
972
+ className: cn(
973
+ "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
974
+ className
975
+ ),
976
+ ...props
977
+ }
978
+ );
979
+ }
980
+ function CardHeader({ className, ...props }) {
981
+ return /* @__PURE__ */ jsxRuntime.jsx(
982
+ "div",
983
+ {
984
+ "data-slot": "card-header",
985
+ className: cn(
986
+ "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
987
+ className
988
+ ),
989
+ ...props
990
+ }
991
+ );
992
+ }
993
+ function CardTitle({ className, ...props }) {
994
+ return /* @__PURE__ */ jsxRuntime.jsx(
995
+ "div",
996
+ {
997
+ "data-slot": "card-title",
998
+ className: cn("leading-none font-semibold", className),
999
+ ...props
1000
+ }
1001
+ );
1002
+ }
1003
+ function CardDescription({ className, ...props }) {
1004
+ return /* @__PURE__ */ jsxRuntime.jsx(
1005
+ "div",
1006
+ {
1007
+ "data-slot": "card-description",
1008
+ className: cn("text-muted-foreground text-sm", className),
1009
+ ...props
1010
+ }
1011
+ );
1012
+ }
1013
+ function CardContent({ className, ...props }) {
1014
+ return /* @__PURE__ */ jsxRuntime.jsx(
1015
+ "div",
1016
+ {
1017
+ "data-slot": "card-content",
1018
+ className: cn("px-6", className),
1019
+ ...props
1020
+ }
1021
+ );
1022
+ }
1023
+ function Tabs({
1024
+ className,
1025
+ ...props
1026
+ }) {
1027
+ return /* @__PURE__ */ jsxRuntime.jsx(
1028
+ TabsPrimitive__namespace.Root,
1029
+ {
1030
+ "data-slot": "tabs",
1031
+ className: cn("flex flex-col gap-2", className),
1032
+ ...props
1033
+ }
1034
+ );
1035
+ }
1036
+ function TabsList({
1037
+ className,
1038
+ ...props
1039
+ }) {
1040
+ return /* @__PURE__ */ jsxRuntime.jsx(
1041
+ TabsPrimitive__namespace.List,
1042
+ {
1043
+ "data-slot": "tabs-list",
1044
+ className: cn(
1045
+ "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1046
+ className
1047
+ ),
1048
+ ...props
1049
+ }
1050
+ );
1051
+ }
1052
+ function TabsTrigger({
1053
+ className,
1054
+ ...props
1055
+ }) {
1056
+ return /* @__PURE__ */ jsxRuntime.jsx(
1057
+ TabsPrimitive__namespace.Trigger,
1058
+ {
1059
+ "data-slot": "tabs-trigger",
1060
+ className: cn(
1061
+ "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
1062
+ className
1063
+ ),
1064
+ ...props
1065
+ }
1066
+ );
1067
+ }
1068
+ function TabsContent({
1069
+ className,
1070
+ ...props
1071
+ }) {
1072
+ return /* @__PURE__ */ jsxRuntime.jsx(
1073
+ TabsPrimitive__namespace.Content,
1074
+ {
1075
+ "data-slot": "tabs-content",
1076
+ className: cn("flex-1 outline-none", className),
1077
+ ...props
1078
+ }
1079
+ );
1080
+ }
1081
+ function Slider({
1082
+ className,
1083
+ defaultValue,
1084
+ value,
1085
+ min = 0,
1086
+ max = 100,
1087
+ ...props
1088
+ }) {
1089
+ const _values = React__namespace.useMemo(
1090
+ () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1091
+ [value, defaultValue, min, max]
1092
+ );
1093
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1094
+ SliderPrimitive__namespace.Root,
1095
+ {
1096
+ "data-slot": "slider",
1097
+ defaultValue,
1098
+ value,
1099
+ min,
1100
+ max,
1101
+ className: cn(
1102
+ "relative flex w-full cursor-pointer touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
1103
+ className
1104
+ ),
1105
+ ...props,
1106
+ children: [
1107
+ /* @__PURE__ */ jsxRuntime.jsx(
1108
+ SliderPrimitive__namespace.Track,
1109
+ {
1110
+ "data-slot": "slider-track",
1111
+ className: cn(
1112
+ "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
1113
+ ),
1114
+ children: /* @__PURE__ */ jsxRuntime.jsx(
1115
+ SliderPrimitive__namespace.Range,
1116
+ {
1117
+ "data-slot": "slider-range",
1118
+ className: cn(
1119
+ "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
1120
+ )
1121
+ }
1122
+ )
1123
+ }
1124
+ ),
1125
+ Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsxRuntime.jsx(
1126
+ SliderPrimitive__namespace.Thumb,
1127
+ {
1128
+ "data-slot": "slider-thumb",
1129
+ className: "border-primary ring-ring/50 block size-4 shrink-0 cursor-pointer rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
1130
+ },
1131
+ index
1132
+ ))
1133
+ ]
1134
+ }
1135
+ );
1136
+ }
1137
+ function VolumeControls({ className, compact }) {
1138
+ const {
1139
+ masterVolume,
1140
+ musicVolume,
1141
+ sfxVolume,
1142
+ setMasterVolume,
1143
+ setMusicVolume,
1144
+ setSfxVolume
1145
+ } = useVolumeStore();
1146
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1147
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1148
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Volume2, { className: "text-muted-foreground h-4 w-4" }),
1149
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: "Volume" })
1150
+ ] }),
1151
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1152
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1153
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1154
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1155
+ Math.round(masterVolume * 100),
1156
+ "%"
1157
+ ] })
1158
+ ] }),
1159
+ /* @__PURE__ */ jsxRuntime.jsx(
1160
+ Slider,
1161
+ {
1162
+ value: [masterVolume * 100],
1163
+ onValueChange: (values) => setMasterVolume(values[0] / 100),
1164
+ min: 0,
1165
+ max: 100,
1166
+ step: 1,
1167
+ className: "w-full",
1168
+ "aria-label": "Master volume"
1169
+ }
1170
+ )
1171
+ ] }),
1172
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1173
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1174
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1175
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Music, { className: "text-muted-foreground h-3 w-3" }),
1176
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1177
+ ] }),
1178
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1179
+ Math.round(musicVolume * 100),
1180
+ "%"
1181
+ ] })
1182
+ ] }),
1183
+ /* @__PURE__ */ jsxRuntime.jsx(
1184
+ Slider,
1185
+ {
1186
+ value: [musicVolume * 100],
1187
+ onValueChange: (values) => setMusicVolume(values[0] / 100),
1188
+ min: 0,
1189
+ max: 100,
1190
+ step: 1,
1191
+ className: "w-full",
1192
+ "aria-label": "Music volume"
1193
+ }
1194
+ )
1195
+ ] }),
1196
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1197
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1198
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1199
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Headphones, { className: "text-muted-foreground h-3 w-3" }),
1200
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1201
+ ] }),
1202
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1203
+ Math.round(sfxVolume * 100),
1204
+ "%"
1205
+ ] })
1206
+ ] }),
1207
+ /* @__PURE__ */ jsxRuntime.jsx(
1208
+ Slider,
1209
+ {
1210
+ value: [sfxVolume * 100],
1211
+ onValueChange: (values) => setSfxVolume(values[0] / 100),
1212
+ min: 0,
1213
+ max: 100,
1214
+ step: 1,
1215
+ className: "w-full",
1216
+ "aria-label": "SFX volume"
1217
+ }
1218
+ )
1219
+ ] })
1220
+ ] });
1221
+ }
1222
+ var statusCopy = {
1223
+ idle: "Idle",
1224
+ connecting: "Waiting for server\u2026",
1225
+ connected: "Ready for controllers",
1226
+ disconnected: "Disconnected",
1227
+ reconnecting: "Reconnecting\u2026"
1228
+ };
1229
+ var getPlayerAvatarUrl = (playerId) => {
1230
+ return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
1231
+ playerId
1232
+ )}`;
1233
+ };
1234
+ var AirJamOverlay = ({
1235
+ roomId,
1236
+ joinUrl,
1237
+ connectionStatus,
1238
+ players,
1239
+ lastError,
1240
+ gameState,
1241
+ onTogglePlayPause,
1242
+ isChildMode = false
1243
+ }) => {
1244
+ const [qrUrl, setQrUrl] = React.useState(null);
1245
+ const [qrError, setQrError] = React.useState(null);
1246
+ React.useEffect(() => {
1247
+ if (isChildMode) return;
1248
+ let mounted = true;
1249
+ QRCode__default.default.toDataURL(joinUrl, {
1250
+ margin: 1,
1251
+ color: {
1252
+ dark: "#0f172a",
1253
+ light: "#ffffff"
1254
+ },
1255
+ width: 320
1256
+ }).then((value) => {
1257
+ if (mounted) {
1258
+ setQrUrl(value);
1259
+ setQrError(null);
1260
+ }
1261
+ }).catch((err) => {
1262
+ if (mounted) {
1263
+ setQrError(err.message);
1264
+ }
1265
+ });
1266
+ return () => {
1267
+ mounted = false;
1268
+ };
1269
+ }, [joinUrl, isChildMode]);
1270
+ const connectionVariant = React.useMemo(() => {
1271
+ switch (connectionStatus) {
1272
+ case "connected":
1273
+ return "default";
1274
+ case "connecting":
1275
+ case "reconnecting":
1276
+ return "secondary";
1277
+ default:
1278
+ return "destructive";
1279
+ }
1280
+ }, [connectionStatus]);
1281
+ if (isChildMode) return null;
1282
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1283
+ !isChildMode && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-99999", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mx-auto w-full", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between px-4 py-2", children: [
1284
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1285
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs tracking-[0.18em] uppercase", children: "Room" }),
1286
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-foreground text-lg font-semibold", children: roomId })
1287
+ ] }) }),
1288
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
1289
+ players.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center -space-x-2", children: [
1290
+ players.slice(0, 4).map((player) => /* @__PURE__ */ jsxRuntime.jsx(
1291
+ Avatar,
1292
+ {
1293
+ className: "h-8 w-8 border-2",
1294
+ style: {
1295
+ borderColor: player.color || "hsl(var(--border))"
1296
+ },
1297
+ children: /* @__PURE__ */ jsxRuntime.jsx(
1298
+ AvatarImage,
1299
+ {
1300
+ src: getPlayerAvatarUrl(player.id),
1301
+ alt: player.label
1302
+ }
1303
+ )
1304
+ },
1305
+ player.id
1306
+ )),
1307
+ players.length > 4 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "border-background bg-muted flex h-8 w-8 items-center justify-center rounded-full border-2 text-xs font-medium", children: [
1308
+ "+",
1309
+ players.length - 4
1310
+ ] })
1311
+ ] }),
1312
+ onTogglePlayPause && /* @__PURE__ */ jsxRuntime.jsx(
1313
+ Button,
1314
+ {
1315
+ type: "button",
1316
+ variant: "ghost",
1317
+ size: "icon",
1318
+ onClick: onTogglePlayPause,
1319
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
1320
+ className: "h-8 w-8",
1321
+ children: gameState === "playing" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "h-4 w-4" })
1322
+ }
1323
+ )
1324
+ ] })
1325
+ ] }) }) }),
1326
+ gameState === "paused" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-none fixed inset-0 z-99998 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-auto w-full max-w-2xl", children: /* @__PURE__ */ jsxRuntime.jsx(Card, { className: "bg-card/20 flex h-[80vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxRuntime.jsxs(
1327
+ Tabs,
1328
+ {
1329
+ defaultValue: isChildMode ? "settings" : "room-code",
1330
+ className: "flex h-full w-full flex-col gap-0",
1331
+ children: [
1332
+ /* @__PURE__ */ jsxRuntime.jsxs(TabsList, { className: "border-border grid w-full shrink-0 grid-cols-2 rounded-none border-b bg-transparent p-0", children: [
1333
+ !isChildMode && /* @__PURE__ */ jsxRuntime.jsxs(
1334
+ TabsTrigger,
1335
+ {
1336
+ value: "room-code",
1337
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1338
+ children: [
1339
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.QrCode, { className: "h-4 w-4" }),
1340
+ "Room Code"
1341
+ ]
1342
+ }
1343
+ ),
1344
+ isChildMode && /* @__PURE__ */ jsxRuntime.jsxs(
1345
+ TabsTrigger,
1346
+ {
1347
+ value: "info",
1348
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1349
+ children: [
1350
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.MonitorSmartphone, { className: "h-4 w-4" }),
1351
+ "Platform"
1352
+ ]
1353
+ }
1354
+ ),
1355
+ /* @__PURE__ */ jsxRuntime.jsxs(
1356
+ TabsTrigger,
1357
+ {
1358
+ value: "settings",
1359
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1360
+ children: [
1361
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Settings, { className: "h-4 w-4" }),
1362
+ "Settings"
1363
+ ]
1364
+ }
1365
+ )
1366
+ ] }),
1367
+ !isChildMode && /* @__PURE__ */ jsxRuntime.jsx(
1368
+ TabsContent,
1369
+ {
1370
+ value: "room-code",
1371
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1372
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6 pb-6", children: [
1373
+ /* @__PURE__ */ jsxRuntime.jsxs(CardHeader, { className: "pt-6 text-center", children: [
1374
+ /* @__PURE__ */ jsxRuntime.jsx(CardTitle, { className: "text-4xl font-bold tracking-wider", children: roomId }),
1375
+ /* @__PURE__ */ jsxRuntime.jsx(
1376
+ Badge,
1377
+ {
1378
+ variant: connectionVariant,
1379
+ className: "mx-auto mt-3",
1380
+ children: statusCopy[connectionStatus]
1381
+ }
1382
+ )
1383
+ ] }),
1384
+ /* @__PURE__ */ jsxRuntime.jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1385
+ /* @__PURE__ */ jsxRuntime.jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
1386
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-center font-mono text-xs break-all", children: joinUrl }),
1387
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-border bg-card w-48 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsxRuntime.jsx(
1388
+ "img",
1389
+ {
1390
+ src: qrUrl,
1391
+ alt: `Join room ${roomId}`,
1392
+ className: "w-full rounded bg-white"
1393
+ }
1394
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-muted-foreground flex h-48 items-center justify-center text-sm", children: qrError ? `QR failed: ${qrError}` : "Generating QR code\u2026" }) }),
1395
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full", children: players.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground py-4 text-center text-sm", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
1396
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
1397
+ "Connected Players (",
1398
+ players.length,
1399
+ ")"
1400
+ ] }),
1401
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxRuntime.jsxs(
1402
+ "li",
1403
+ {
1404
+ className: "flex flex-col items-center gap-2",
1405
+ children: [
1406
+ /* @__PURE__ */ jsxRuntime.jsx(
1407
+ "img",
1408
+ {
1409
+ src: getPlayerAvatarUrl(player.id),
1410
+ alt: player.label,
1411
+ className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1412
+ style: {
1413
+ borderColor: player.color || "hsl(var(--border))"
1414
+ }
1415
+ }
1416
+ ),
1417
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center gap-0.5", children: [
1418
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }),
1419
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground font-mono text-xs", children: player.id.slice(0, 8) })
1420
+ ] })
1421
+ ]
1422
+ },
1423
+ player.id
1424
+ )) })
1425
+ ] }) }),
1426
+ lastError && /* @__PURE__ */ jsxRuntime.jsx(Alert, { variant: "destructive", className: "w-full", children: /* @__PURE__ */ jsxRuntime.jsx(AlertDescription, { children: lastError }) }),
1427
+ onTogglePlayPause && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxRuntime.jsxs(
1428
+ Button,
1429
+ {
1430
+ type: "button",
1431
+ onClick: onTogglePlayPause,
1432
+ size: "lg",
1433
+ children: [
1434
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "mr-2 h-5 w-5" }),
1435
+ "Start Game"
1436
+ ]
1437
+ }
1438
+ ) })
1439
+ ] }) })
1440
+ ] })
1441
+ }
1442
+ ),
1443
+ isChildMode && /* @__PURE__ */ jsxRuntime.jsx(
1444
+ TabsContent,
1445
+ {
1446
+ value: "info",
1447
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1448
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6 pb-6", children: [
1449
+ /* @__PURE__ */ jsxRuntime.jsxs(CardHeader, { className: "pt-6 text-center", children: [
1450
+ /* @__PURE__ */ jsxRuntime.jsx(CardTitle, { className: "text-2xl font-bold tracking-wider", children: "Connected to Platform" }),
1451
+ /* @__PURE__ */ jsxRuntime.jsx(CardDescription, { className: "mt-2", children: "This game is running inside the Air Jam Platform." })
1452
+ ] }),
1453
+ /* @__PURE__ */ jsxRuntime.jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1454
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
1455
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
1456
+ "Connected Players (",
1457
+ players.length,
1458
+ ")"
1459
+ ] }),
1460
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxRuntime.jsxs(
1461
+ "li",
1462
+ {
1463
+ className: "flex flex-col items-center gap-2",
1464
+ children: [
1465
+ /* @__PURE__ */ jsxRuntime.jsx(
1466
+ "img",
1467
+ {
1468
+ src: getPlayerAvatarUrl(player.id),
1469
+ alt: player.label,
1470
+ className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1471
+ style: {
1472
+ borderColor: player.color || "hsl(var(--border))"
1473
+ }
1474
+ }
1475
+ ),
1476
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col items-center gap-0.5", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }) })
1477
+ ]
1478
+ },
1479
+ player.id
1480
+ )) })
1481
+ ] }) }),
1482
+ onTogglePlayPause && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxRuntime.jsxs(
1483
+ Button,
1484
+ {
1485
+ type: "button",
1486
+ onClick: onTogglePlayPause,
1487
+ size: "lg",
1488
+ children: [
1489
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "mr-2 h-5 w-5" }),
1490
+ "Resume Game"
1491
+ ]
1492
+ }
1493
+ ) })
1494
+ ] }) })
1495
+ ] })
1496
+ }
1497
+ ),
1498
+ /* @__PURE__ */ jsxRuntime.jsx(
1499
+ TabsContent,
1500
+ {
1501
+ value: "settings",
1502
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1503
+ children: /* @__PURE__ */ jsxRuntime.jsx(CardContent, { className: "pt-6 pb-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
1504
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntime.jsx(VolumeControls, {}) }),
1505
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 border-t pt-4", children: [
1506
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: "Connection" }),
1507
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
1508
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1509
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Status" }),
1510
+ /* @__PURE__ */ jsxRuntime.jsx(Badge, { variant: connectionVariant, children: statusCopy[connectionStatus] })
1511
+ ] }),
1512
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1513
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Room ID" }),
1514
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-mono text-sm", children: roomId })
1515
+ ] }),
1516
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1517
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Players" }),
1518
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: players.length })
1519
+ ] })
1520
+ ] })
1521
+ ] }),
1522
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 border-t pt-4", children: [
1523
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: "Display" }),
1524
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1525
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Game State" }),
1526
+ /* @__PURE__ */ jsxRuntime.jsx(Badge, { variant: "outline", className: "capitalize", children: gameState })
1527
+ ] }) })
1528
+ ] })
1529
+ ] }) })
1530
+ }
1531
+ )
1532
+ ]
1533
+ }
1534
+ ) }) }) })
1535
+ ] });
1536
+ };
1537
+ var useFullscreen = () => {
1538
+ const [isFullscreen, setIsFullscreen] = React.useState(false);
1539
+ React.useEffect(() => {
1540
+ const handleFullscreenChange = () => {
1541
+ const doc = document;
1542
+ setIsFullscreen(
1543
+ !!(document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement)
1544
+ );
1545
+ };
1546
+ document.addEventListener("fullscreenchange", handleFullscreenChange);
1547
+ document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
1548
+ document.addEventListener("mozfullscreenchange", handleFullscreenChange);
1549
+ document.addEventListener("msfullscreenchange", handleFullscreenChange);
1550
+ return () => {
1551
+ document.removeEventListener("fullscreenchange", handleFullscreenChange);
1552
+ document.removeEventListener(
1553
+ "webkitfullscreenchange",
1554
+ handleFullscreenChange
1555
+ );
1556
+ document.removeEventListener(
1557
+ "mozfullscreenchange",
1558
+ handleFullscreenChange
1559
+ );
1560
+ document.removeEventListener(
1561
+ "msfullscreenchange",
1562
+ handleFullscreenChange
1563
+ );
1564
+ };
1565
+ }, []);
1566
+ const exitFullscreen = React.useCallback(async () => {
1567
+ try {
1568
+ const doc = document;
1569
+ if (document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement) {
1570
+ if (document.exitFullscreen) {
1571
+ await document.exitFullscreen();
1572
+ } else if (doc.webkitExitFullscreen) {
1573
+ await doc.webkitExitFullscreen();
1574
+ } else if (doc.mozCancelFullScreen) {
1575
+ await doc.mozCancelFullScreen();
1576
+ } else if (doc.msExitFullscreen) {
1577
+ await doc.msExitFullscreen();
1578
+ }
1579
+ }
1580
+ } catch (error) {
1581
+ console.error("Error exiting fullscreen:", error);
1582
+ }
1583
+ }, []);
1584
+ const enterFullscreen = React.useCallback(async (element) => {
1585
+ try {
1586
+ const elem = element || document.documentElement;
1587
+ if (elem.requestFullscreen) {
1588
+ await elem.requestFullscreen();
1589
+ } else if (elem.webkitRequestFullscreen) {
1590
+ await elem.webkitRequestFullscreen();
1591
+ } else if (elem.mozRequestFullScreen) {
1592
+ await elem.mozRequestFullScreen();
1593
+ } else if (elem.msRequestFullscreen) {
1594
+ await elem.msRequestFullscreen();
1595
+ }
1596
+ } catch (error) {
1597
+ console.error("Error entering fullscreen:", error);
1598
+ }
1599
+ }, []);
1600
+ const toggleFullscreen = React.useCallback(
1601
+ async (element) => {
1602
+ if (isFullscreen) {
1603
+ await exitFullscreen();
1604
+ } else {
1605
+ await enterFullscreen(element);
1606
+ }
1607
+ },
1608
+ [isFullscreen, exitFullscreen, enterFullscreen]
1609
+ );
1610
+ return {
1611
+ isFullscreen,
1612
+ enterFullscreen,
1613
+ exitFullscreen,
1614
+ toggleFullscreen
1615
+ };
1616
+ };
1617
+
1618
+ // src/utils/mode.ts
1619
+ var detectRunMode = () => {
1620
+ if (typeof window === "undefined") {
1621
+ return "standalone";
1622
+ }
1623
+ try {
1624
+ return window.self !== window.top ? "platform" : "standalone";
1625
+ } catch {
1626
+ return "platform";
1627
+ }
1628
+ };
1629
+ var roomCodeSchema = zod.z.string().trim().min(4).max(8).regex(/^[A-Z0-9]+$/, { message: "room code must contain only A-Z or 0-9" });
1630
+ var controllerInputSchema = zod.z.object({
1631
+ roomId: roomCodeSchema,
1632
+ controllerId: zod.z.string().min(3),
1633
+ input: zod.z.record(zod.z.string(), zod.z.unknown())
1634
+ // Arbitrary JSON object - developers define their own structure
1635
+ });
1636
+ var controllerStateSchema = zod.z.object({
1637
+ roomId: roomCodeSchema,
1638
+ state: zod.z.object({
1639
+ orientation: zod.z.enum(["portrait", "landscape"]).optional(),
1640
+ message: zod.z.string().optional(),
1641
+ gameState: zod.z.enum(["paused", "playing"]).optional()
1642
+ })
1643
+ });
1644
+ var hostRegistrationSchema = zod.z.object({
1645
+ roomId: roomCodeSchema,
1646
+ maxPlayers: zod.z.number().int().min(1).max(16).default(8),
1647
+ apiKey: zod.z.string().optional(),
1648
+ mode: zod.z.enum(["master", "child"]).default("child"),
1649
+ controllerUrl: zod.z.string().url().optional()
1650
+ });
1651
+ var controllerJoinSchema = zod.z.object({
1652
+ roomId: roomCodeSchema,
1653
+ controllerId: zod.z.string().min(3),
1654
+ nickname: zod.z.string().trim().min(1).max(24).optional()
1655
+ });
1656
+ var controllerLeaveSchema = zod.z.object({
1657
+ roomId: roomCodeSchema,
1658
+ controllerId: zod.z.string().min(3)
1659
+ });
1660
+ var controllerSystemSchema = zod.z.object({
1661
+ roomId: roomCodeSchema,
1662
+ command: zod.z.enum(["exit", "ready", "toggle_pause"])
1663
+ });
1664
+ var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
1665
+ ErrorCode2["ROOM_NOT_FOUND"] = "ROOM_NOT_FOUND";
1666
+ ErrorCode2["ROOM_FULL"] = "ROOM_FULL";
1667
+ ErrorCode2["INVALID_API_KEY"] = "INVALID_API_KEY";
1668
+ ErrorCode2["UNAUTHORIZED"] = "UNAUTHORIZED";
1669
+ ErrorCode2["INVALID_TOKEN"] = "INVALID_TOKEN";
1670
+ ErrorCode2["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
1671
+ ErrorCode2["CONNECTION_FAILED"] = "CONNECTION_FAILED";
1672
+ ErrorCode2["ALREADY_CONNECTED"] = "ALREADY_CONNECTED";
1673
+ ErrorCode2["INVALID_PAYLOAD"] = "INVALID_PAYLOAD";
1674
+ ErrorCode2["INVALID_ROOM_CODE"] = "INVALID_ROOM_CODE";
1675
+ ErrorCode2["INTERNAL_SERVER_ERROR"] = "INTERNAL_SERVER_ERROR";
1676
+ ErrorCode2["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
1677
+ ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
1678
+ return ErrorCode2;
1679
+ })(ErrorCode || {});
1680
+ var hostRegisterSystemSchema = zod.z.object({
1681
+ roomId: roomCodeSchema,
1682
+ apiKey: zod.z.string().optional()
1683
+ });
1684
+ var systemLaunchGameSchema = zod.z.object({
1685
+ roomId: roomCodeSchema,
1686
+ gameId: zod.z.string(),
1687
+ gameUrl: zod.z.string().url()
1688
+ });
1689
+ var hostJoinAsChildSchema = zod.z.object({
1690
+ roomId: roomCodeSchema,
1691
+ joinToken: zod.z.string()
1692
+ });
1693
+ var AIRJAM_PROXY_PREFIX = "AIRJAM_";
1694
+
1695
+ // src/utils/network-ip.ts
1696
+ var isVirtualNetwork = (ip) => {
1697
+ if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
1698
+ return true;
1699
+ }
1700
+ if (ip.startsWith("172.17.")) {
1701
+ return true;
1702
+ }
1703
+ if (ip.startsWith("172.18.") || ip.startsWith("172.19.")) {
1704
+ return true;
1705
+ }
1706
+ if (ip.startsWith("169.254.")) {
1707
+ return true;
1708
+ }
1709
+ return false;
1710
+ };
1711
+ var scoreIp = (ip) => {
1712
+ if (ip.startsWith("192.168.")) {
1713
+ const parts = ip.split(".");
1714
+ const thirdOctet = parseInt(parts[2] || "0", 10);
1715
+ if (thirdOctet < 64) {
1716
+ return 100 - thirdOctet;
1717
+ }
1718
+ return 10;
1719
+ }
1720
+ if (ip.startsWith("10.")) {
1721
+ return 50;
1722
+ }
1723
+ if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
1724
+ return 30;
1725
+ }
1726
+ return 0;
1727
+ };
1728
+ var getLocalNetworkIp = () => {
1729
+ return new Promise((resolve) => {
1730
+ if (typeof window === "undefined" || typeof RTCPeerConnection === "undefined") {
1731
+ resolve(null);
1732
+ return;
1733
+ }
1734
+ const pc = new RTCPeerConnection({
1735
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
1736
+ });
1737
+ const candidates = [];
1738
+ let candidateGatheringComplete = false;
1739
+ const resolveOnce = (ip) => {
1740
+ pc.close();
1741
+ resolve(ip);
1742
+ };
1743
+ const timeout = setTimeout(() => {
1744
+ if (candidateGatheringComplete) {
1745
+ pickBestCandidate();
1746
+ } else {
1747
+ setTimeout(() => {
1748
+ pickBestCandidate();
1749
+ }, 500);
1750
+ }
1751
+ }, 3e3);
1752
+ const pickBestCandidate = () => {
1753
+ if (candidates.length === 0) {
1754
+ resolveOnce(null);
1755
+ return;
1756
+ }
1757
+ candidates.sort((a, b) => b.score - a.score);
1758
+ const best = candidates[0];
1759
+ clearTimeout(timeout);
1760
+ resolveOnce(best.ip);
1761
+ };
1762
+ pc.onicecandidate = (event) => {
1763
+ if (event.candidate) {
1764
+ const candidate = event.candidate.candidate;
1765
+ const match = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
1766
+ if (match) {
1767
+ const ip = match[1];
1768
+ if (ip === "127.0.0.1") {
1769
+ return;
1770
+ }
1771
+ const isPrivate = ip.startsWith("192.168.") || ip.startsWith("10.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
1772
+ if (isPrivate && !isVirtualNetwork(ip)) {
1773
+ const score = scoreIp(ip);
1774
+ candidates.push({ ip, score });
1775
+ }
1776
+ }
1777
+ } else {
1778
+ candidateGatheringComplete = true;
1779
+ setTimeout(() => {
1780
+ pickBestCandidate();
1781
+ }, 200);
1782
+ }
1783
+ };
1784
+ pc.createDataChannel("");
1785
+ pc.createOffer().then((offer) => pc.setLocalDescription(offer)).catch(() => {
1786
+ clearTimeout(timeout);
1787
+ resolveOnce(null);
1788
+ });
1789
+ });
1790
+ };
1791
+
1792
+ // src/utils/url-builder.ts
1793
+ var UrlBuilder = class {
1794
+ cachedLocalIp = null;
1795
+ ipDetectionPromise = null;
1796
+ /**
1797
+ * Get the local network IP address with caching.
1798
+ * First call triggers detection, subsequent calls return cached value.
1799
+ */
1800
+ async getLocalIp() {
1801
+ if (this.cachedLocalIp !== null) {
1802
+ return this.cachedLocalIp;
1803
+ }
1804
+ if (this.ipDetectionPromise !== null) {
1805
+ return this.ipDetectionPromise;
1806
+ }
1807
+ this.ipDetectionPromise = getLocalNetworkIp().then((ip) => {
1808
+ this.cachedLocalIp = ip;
1809
+ this.ipDetectionPromise = null;
1810
+ return ip;
1811
+ });
1812
+ return this.ipDetectionPromise;
1813
+ }
1814
+ /**
1815
+ * Clear the cached IP address.
1816
+ * Useful for testing or when network changes are detected.
1817
+ */
1818
+ clearCache() {
1819
+ this.cachedLocalIp = null;
1820
+ this.ipDetectionPromise = null;
1821
+ }
1822
+ /**
1823
+ * Normalize a URL for mobile access.
1824
+ * Replaces localhost with the local network IP.
1825
+ */
1826
+ async normalizeForMobile(url) {
1827
+ if (typeof window === "undefined") return url;
1828
+ try {
1829
+ const urlObj = new URL(url);
1830
+ if (urlObj.hostname === "localhost" || urlObj.hostname === "127.0.0.1") {
1831
+ const localIp = await this.getLocalIp();
1832
+ if (localIp) {
1833
+ urlObj.hostname = localIp;
1834
+ return urlObj.toString();
1835
+ }
1836
+ urlObj.hostname = window.location.hostname;
1837
+ return urlObj.toString();
1838
+ }
1839
+ return url;
1840
+ } catch {
1841
+ return url;
1842
+ }
1843
+ }
1844
+ /**
1845
+ * Build a controller URL with room code.
1846
+ * Automatically uses local IP when running on localhost.
1847
+ */
1848
+ async buildControllerUrl(roomId, options) {
1849
+ const path = options?.path || DEFAULT_CONTROLLER_PATH;
1850
+ if (options?.host) {
1851
+ const url2 = new URL(path, this.normalizeOrigin(options.host));
1852
+ url2.searchParams.set("room", roomId);
1853
+ return url2.toString();
1854
+ }
1855
+ let base;
1856
+ if (typeof window === "undefined") {
1857
+ base = `http://localhost:${DEFAULT_SERVER_PORT}`;
1858
+ } else {
1859
+ const currentUrl = new URL(window.location.href);
1860
+ if (!this.isLocalhost(currentUrl.hostname)) {
1861
+ base = currentUrl.origin;
1862
+ } else {
1863
+ const localIp = await this.getLocalIp();
1864
+ if (localIp) {
1865
+ const port = currentUrl.port;
1866
+ base = port ? `http://${localIp}:${port}` : `http://${localIp}`;
1867
+ } else {
1868
+ base = currentUrl.origin;
1869
+ }
1870
+ }
1871
+ }
1872
+ const url = new URL(path, base);
1873
+ url.searchParams.set("room", roomId);
1874
+ return url.toString();
1875
+ }
1876
+ /**
1877
+ * Resolve the server URL.
1878
+ * Uses explicit URL if provided, otherwise infers from window location.
1879
+ */
1880
+ resolveServerUrl(explicit) {
1881
+ if (explicit) {
1882
+ return this.normalizeOrigin(explicit);
1883
+ }
1884
+ if (typeof window !== "undefined") {
1885
+ const url = new URL(window.location.href);
1886
+ url.port = String(DEFAULT_SERVER_PORT);
1887
+ return url.origin;
1888
+ }
1889
+ return `http://localhost:${DEFAULT_SERVER_PORT}`;
1890
+ }
1891
+ /**
1892
+ * Check if a hostname is localhost.
1893
+ */
1894
+ isLocalhost(hostname) {
1895
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1896
+ }
1897
+ /**
1898
+ * Normalize an origin string to ensure it has a protocol.
1899
+ */
1900
+ normalizeOrigin(origin) {
1901
+ if (!origin.includes("://")) {
1902
+ return `http://${origin}`;
1903
+ }
1904
+ return origin;
1905
+ }
1906
+ };
1907
+ var urlBuilder = new UrlBuilder();
1908
+ var extractRoomCode = (text) => {
1909
+ try {
1910
+ const url = new URL(text);
1911
+ const roomParam = url.searchParams.get("room");
1912
+ if (roomParam) {
1913
+ const parsed2 = roomCodeSchema.safeParse(roomParam.toUpperCase());
1914
+ if (parsed2.success) {
1915
+ return parsed2.data;
1916
+ }
1917
+ }
1918
+ } catch {
1919
+ }
1920
+ const parsed = roomCodeSchema.safeParse(text.trim().toUpperCase());
1921
+ if (parsed.success) {
1922
+ return parsed.data;
1923
+ }
1924
+ return null;
1925
+ };
1926
+ var QRScannerDialog = ({
1927
+ isOpen,
1928
+ onClose,
1929
+ onScan,
1930
+ currentRoomId
1931
+ }) => {
1932
+ const [code, setCode] = React.useState("");
1933
+ const [isCameraAvailable, setIsCameraAvailable] = React.useState(false);
1934
+ const [joinUrl, setJoinUrl] = React.useState("");
1935
+ const [copied, setCopied] = React.useState(false);
1936
+ const scannerRef = React.useRef(null);
1937
+ const inputRef = React.useRef(null);
1938
+ const prevIsOpenRef = React.useRef(false);
1939
+ React.useEffect(() => {
1940
+ if (isOpen && !prevIsOpenRef.current) {
1941
+ const initialCode = currentRoomId || "";
1942
+ setTimeout(() => {
1943
+ setIsCameraAvailable(false);
1944
+ setCode(initialCode);
1945
+ inputRef.current?.focus();
1946
+ inputRef.current?.select();
1947
+ }, 0);
1948
+ }
1949
+ prevIsOpenRef.current = isOpen;
1950
+ }, [isOpen, currentRoomId]);
1951
+ React.useEffect(() => {
1952
+ const buildUrl = async () => {
1953
+ const trimmed = code.trim().toUpperCase();
1954
+ const parsed = roomCodeSchema.safeParse(trimmed);
1955
+ if (parsed.success) {
1956
+ try {
1957
+ const url = await urlBuilder.buildControllerUrl(parsed.data);
1958
+ setJoinUrl(url);
1959
+ } catch {
1960
+ setJoinUrl("");
1961
+ }
1962
+ } else {
1963
+ setJoinUrl("");
1964
+ }
1965
+ };
1966
+ buildUrl();
1967
+ }, [code]);
1968
+ React.useEffect(() => {
1969
+ if (!isOpen) {
1970
+ setTimeout(() => {
1971
+ setIsCameraAvailable(false);
1972
+ }, 0);
1973
+ if (scannerRef.current) {
1974
+ const scanner = scannerRef.current;
1975
+ scanner.stop().catch(() => {
1976
+ }).finally(() => {
1977
+ try {
1978
+ scanner.clear();
1979
+ } catch {
1980
+ }
1981
+ });
1982
+ scannerRef.current = null;
1983
+ }
1984
+ }
1985
+ }, [isOpen]);
1986
+ React.useEffect(() => {
1987
+ if (!isOpen) {
1988
+ return;
1989
+ }
1990
+ const containerId = "qr-reader";
1991
+ let scanner = null;
1992
+ let scannerRunning = false;
1993
+ let mounted = true;
1994
+ const startScanning = async () => {
1995
+ try {
1996
+ const container = document.getElementById(containerId);
1997
+ if (!container) {
1998
+ return;
1999
+ }
2000
+ const rect = container.getBoundingClientRect();
2001
+ if (rect.width === 0 || rect.height === 0) {
2002
+ return;
2003
+ }
2004
+ scanner = new html5Qrcode.Html5Qrcode(containerId);
2005
+ scannerRef.current = scanner;
2006
+ let cameraId = null;
2007
+ try {
2008
+ const devices = await html5Qrcode.Html5Qrcode.getCameras();
2009
+ if (devices && devices.length > 0) {
2010
+ const backCamera = devices.find(
2011
+ (d) => d.label.toLowerCase().includes("back") || d.label.toLowerCase().includes("rear")
2012
+ );
2013
+ const envCamera = devices.find((d) => {
2014
+ const label = d.label.toLowerCase();
2015
+ return label.includes("environment") || label.includes("facing back");
2016
+ });
2017
+ cameraId = (envCamera || backCamera || devices[0])?.id || null;
2018
+ }
2019
+ } catch {
2020
+ }
2021
+ const config = cameraId ? { deviceId: { exact: cameraId } } : { facingMode: "environment" };
2022
+ await scanner.start(
2023
+ config,
2024
+ {
2025
+ fps: 10,
2026
+ qrbox: (viewfinderWidth, viewfinderHeight) => {
2027
+ const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
2028
+ const qrboxSize = Math.min(250, minEdge * 0.8);
2029
+ return {
2030
+ width: qrboxSize,
2031
+ height: qrboxSize
2032
+ };
2033
+ },
2034
+ aspectRatio: 1
2035
+ },
2036
+ (decodedText) => {
2037
+ if (!mounted) return;
2038
+ const roomCode = extractRoomCode(decodedText);
2039
+ if (roomCode) {
2040
+ setCode(roomCode);
2041
+ scannerRunning = false;
2042
+ scanner?.stop().catch(() => {
2043
+ }).finally(() => {
2044
+ if (mounted) {
2045
+ setIsCameraAvailable(false);
2046
+ }
2047
+ });
2048
+ }
2049
+ },
2050
+ () => {
2051
+ }
2052
+ );
2053
+ scannerRunning = true;
2054
+ if (mounted) {
2055
+ setIsCameraAvailable(true);
2056
+ }
2057
+ } catch {
2058
+ if (mounted) {
2059
+ setIsCameraAvailable(false);
2060
+ }
2061
+ if (scanner) {
2062
+ try {
2063
+ scanner.clear();
2064
+ } catch {
2065
+ }
2066
+ }
2067
+ scannerRef.current = null;
2068
+ }
2069
+ };
2070
+ const timeoutId = setTimeout(() => {
2071
+ startScanning();
2072
+ }, 200);
2073
+ return () => {
2074
+ mounted = false;
2075
+ clearTimeout(timeoutId);
2076
+ if (scanner && scannerRunning) {
2077
+ scanner.stop().catch(() => {
2078
+ }).finally(() => {
2079
+ try {
2080
+ scanner?.clear();
2081
+ } catch {
2082
+ }
2083
+ });
2084
+ } else if (scanner) {
2085
+ try {
2086
+ scanner.clear();
2087
+ } catch {
2088
+ }
2089
+ }
2090
+ scannerRef.current = null;
2091
+ };
2092
+ }, [isOpen]);
2093
+ const handleSubmit = () => {
2094
+ const trimmed = code.trim().toUpperCase();
2095
+ const parsed = roomCodeSchema.safeParse(trimmed);
2096
+ if (parsed.success) {
2097
+ onScan(parsed.data);
2098
+ onClose();
2099
+ }
2100
+ };
2101
+ const handleInputFocus = (e) => {
2102
+ e.target.select();
2103
+ };
2104
+ const handleInputChange = (e) => {
2105
+ setCode(e.target.value.toUpperCase());
2106
+ setCopied(false);
2107
+ };
2108
+ const handleCopyUrl = async () => {
2109
+ if (!joinUrl) return;
2110
+ try {
2111
+ await navigator.clipboard.writeText(joinUrl);
2112
+ setCopied(true);
2113
+ setTimeout(() => setCopied(false), 2e3);
2114
+ } catch {
2115
+ const textArea = document.createElement("textarea");
2116
+ textArea.value = joinUrl;
2117
+ textArea.style.position = "fixed";
2118
+ textArea.style.opacity = "0";
2119
+ document.body.appendChild(textArea);
2120
+ textArea.select();
2121
+ try {
2122
+ document.execCommand("copy");
2123
+ setCopied(true);
2124
+ setTimeout(() => setCopied(false), 2e3);
2125
+ } catch {
2126
+ }
2127
+ document.body.removeChild(textArea);
2128
+ }
2129
+ };
2130
+ if (!isOpen) {
2131
+ return null;
2132
+ }
2133
+ const isValid = code.trim().length > 0;
2134
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background fixed inset-0 z-50 flex flex-col items-center justify-center", children: [
2135
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-1 flex-col items-center justify-center", children: [
2136
+ isCameraAvailable && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "relative flex aspect-square w-full items-center justify-center overflow-hidden p-6", children: /* @__PURE__ */ jsxRuntime.jsx(
2137
+ "div",
2138
+ {
2139
+ id: "qr-reader",
2140
+ className: "h-full w-full overflow-hidden rounded-lg bg-black"
2141
+ }
2142
+ ) }),
2143
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full max-w-md px-6", children: /* @__PURE__ */ jsxRuntime.jsx(
2144
+ "input",
2145
+ {
2146
+ ref: inputRef,
2147
+ type: "text",
2148
+ value: code,
2149
+ onChange: handleInputChange,
2150
+ onFocus: handleInputFocus,
2151
+ onKeyDown: (e) => {
2152
+ if (e.key === "Enter" && isValid) {
2153
+ handleSubmit();
2154
+ }
2155
+ },
2156
+ placeholder: "Enter room code",
2157
+ className: "border-border bg-background focus:ring-primary focus:border-primary w-full rounded-lg border-2 px-6 py-4 text-center font-mono text-2xl focus:ring-2 focus:outline-none",
2158
+ autoComplete: "off",
2159
+ autoCapitalize: "characters"
2160
+ }
2161
+ ) }),
2162
+ joinUrl && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-4 w-full max-w-md px-6 pb-2", children: /* @__PURE__ */ jsxRuntime.jsx(
2163
+ "button",
2164
+ {
2165
+ type: "button",
2166
+ onClick: handleCopyUrl,
2167
+ className: "text-muted-foreground hover:text-foreground bg-muted/50 hover:bg-muted w-full rounded-lg px-4 py-3 text-center font-mono text-xs break-all transition-colors",
2168
+ children: copied ? "\u2713 Copied!" : joinUrl
2169
+ }
2170
+ ) })
2171
+ ] }),
2172
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex w-full max-w-md gap-4 px-6 pb-6", children: [
2173
+ /* @__PURE__ */ jsxRuntime.jsx(
2174
+ Button,
2175
+ {
2176
+ type: "button",
2177
+ variant: "outline",
2178
+ onClick: onClose,
2179
+ className: "flex-1 py-6",
2180
+ children: "Cancel"
2181
+ }
2182
+ ),
2183
+ /* @__PURE__ */ jsxRuntime.jsx(
2184
+ Button,
2185
+ {
2186
+ type: "button",
2187
+ onClick: handleSubmit,
2188
+ disabled: !isValid,
2189
+ className: "flex-1 py-6",
2190
+ children: "Connect"
2191
+ }
2192
+ )
2193
+ ] })
2194
+ ] });
2195
+ };
2196
+ var getPlayerAvatarUrl2 = (playerId) => {
2197
+ return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
2198
+ playerId
2199
+ )}`;
2200
+ };
2201
+ var describeStatus = (status) => {
2202
+ switch (status) {
2203
+ case "connected":
2204
+ return "Connected to host";
2205
+ case "connecting":
2206
+ return "Connecting\u2026";
2207
+ case "reconnecting":
2208
+ return "Trying to reconnect\u2026";
2209
+ case "disconnected":
2210
+ return "Disconnected";
2211
+ case "idle":
2212
+ default:
2213
+ return "Idle";
2214
+ }
2215
+ };
2216
+ var orientationMatches = (required) => {
2217
+ if (required === "any") return true;
2218
+ if (typeof window === "undefined" || !window.matchMedia) return true;
2219
+ const matcher = window.matchMedia(`(orientation: ${required})`);
2220
+ return matcher.matches;
2221
+ };
2222
+ var ControllerShell = ({
2223
+ roomId,
2224
+ connectionStatus,
2225
+ requiredOrientation = "landscape",
2226
+ children,
2227
+ gameState = "paused",
2228
+ onTogglePlayPause,
2229
+ onReconnect,
2230
+ onRefresh,
2231
+ customActions
2232
+ }) => {
2233
+ const isChildMode = React.useMemo(() => detectRunMode() === "platform", []);
2234
+ const [isOrientationOk, setOrientationOk] = React.useState(
2235
+ () => orientationMatches(requiredOrientation)
2236
+ );
2237
+ const [isScannerOpen, setIsScannerOpen] = React.useState(false);
2238
+ const { isFullscreen, toggleFullscreen } = useFullscreen();
2239
+ const { store } = useAirJamContext();
2240
+ const { controllerId, players } = zustand.useStore(
2241
+ store,
2242
+ shallow.useShallow(
2243
+ (state) => ({
2244
+ controllerId: state.controllerId,
2245
+ players: state.players
2246
+ })
2247
+ )
2248
+ );
2249
+ const currentPlayer = React.useMemo(() => {
2250
+ if (!controllerId) return null;
2251
+ const found = players.find((p) => p.id === controllerId);
2252
+ if (!found && connectionStatus === "connected" && players.length > 0) ;
2253
+ return found || null;
2254
+ }, [controllerId, players, connectionStatus]);
2255
+ React.useEffect(() => {
2256
+ if (requiredOrientation === "any") {
2257
+ return;
2258
+ }
2259
+ const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
2260
+ const handleChange = () => setOrientationOk(media.matches);
2261
+ handleChange();
2262
+ media.addEventListener("change", handleChange);
2263
+ return () => media.removeEventListener("change", handleChange);
2264
+ }, [requiredOrientation]);
2265
+ const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
2266
+ const statusDotColor = React.useMemo(() => {
2267
+ switch (connectionStatus) {
2268
+ case "connected":
2269
+ return "bg-green-500";
2270
+ case "connecting":
2271
+ case "reconnecting":
2272
+ return "bg-yellow-500";
2273
+ case "disconnected":
2274
+ default:
2275
+ return "bg-red-500";
2276
+ }
2277
+ }, [connectionStatus]);
2278
+ if (isChildMode) {
2279
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none", children: /* @__PURE__ */ jsxRuntime.jsxs("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: [
2280
+ !orientationOk && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background/95 absolute inset-0 z-50 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2281
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2282
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2283
+ "This game is best experienced in ",
2284
+ requiredOrientation,
2285
+ " ",
2286
+ "orientation."
2287
+ ] })
2288
+ ] }),
2289
+ /* @__PURE__ */ jsxRuntime.jsx(
2290
+ "div",
2291
+ {
2292
+ className: cn(
2293
+ "h-full w-full select-none",
2294
+ !orientationOk && "pointer-events-none opacity-30"
2295
+ ),
2296
+ children
2297
+ }
2298
+ )
2299
+ ] }) });
2300
+ }
2301
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2302
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: "pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2", children: [
2303
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2304
+ typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", title: describeStatus(connectionStatus), children: [
2305
+ /* @__PURE__ */ jsxRuntime.jsx(
2306
+ Avatar,
2307
+ {
2308
+ className: "h-8 w-8 border-2",
2309
+ style: {
2310
+ borderColor: currentPlayer?.color || "hsl(var(--border))"
2311
+ },
2312
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2313
+ AvatarImage,
2314
+ {
2315
+ src: getPlayerAvatarUrl2(
2316
+ currentPlayer?.id || controllerId || ""
2317
+ ),
2318
+ alt: currentPlayer?.label || "Player"
2319
+ }
2320
+ )
2321
+ }
2322
+ ),
2323
+ /* @__PURE__ */ jsxRuntime.jsx(
2324
+ "span",
2325
+ {
2326
+ className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2327
+ "aria-hidden": "true"
2328
+ }
2329
+ ),
2330
+ /* @__PURE__ */ jsxRuntime.jsx(
2331
+ "span",
2332
+ {
2333
+ className: cn(
2334
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2335
+ statusDotColor,
2336
+ connectionStatus === "connected" && "animate-pulse"
2337
+ ),
2338
+ "aria-label": describeStatus(connectionStatus)
2339
+ }
2340
+ )
2341
+ ] }),
2342
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2343
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2344
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2345
+ ] })
2346
+ ] }),
2347
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2348
+ customActions,
2349
+ onRefresh && roomId && /* @__PURE__ */ jsxRuntime.jsx(
2350
+ Button,
2351
+ {
2352
+ type: "button",
2353
+ variant: "outline",
2354
+ size: "icon",
2355
+ onClick: onRefresh,
2356
+ disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2357
+ "aria-label": "Reconnect",
2358
+ title: "Reconnect to room",
2359
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2360
+ lucideReact.RefreshCw,
2361
+ {
2362
+ className: cn(
2363
+ "h-5 w-5",
2364
+ (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
2365
+ )
2366
+ }
2367
+ )
2368
+ }
2369
+ ),
2370
+ onReconnect && /* @__PURE__ */ jsxRuntime.jsx(
2371
+ Button,
2372
+ {
2373
+ type: "button",
2374
+ variant: "outline",
2375
+ size: "icon",
2376
+ onClick: () => setIsScannerOpen(true),
2377
+ "aria-label": "Scan QR code to reconnect",
2378
+ title: "Scan QR code to reconnect",
2379
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.QrCode, { className: "h-5 w-5" })
2380
+ }
2381
+ ),
2382
+ onTogglePlayPause && /* @__PURE__ */ jsxRuntime.jsx(
2383
+ Button,
2384
+ {
2385
+ type: "button",
2386
+ variant: "outline",
2387
+ size: "icon",
2388
+ onClick: onTogglePlayPause,
2389
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2390
+ title: gameState === "playing" ? "Pause" : "Play",
2391
+ children: gameState === "playing" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "h-5 w-5" })
2392
+ }
2393
+ ),
2394
+ /* @__PURE__ */ jsxRuntime.jsx(
2395
+ Button,
2396
+ {
2397
+ type: "button",
2398
+ variant: "outline",
2399
+ size: "icon",
2400
+ onClick: () => toggleFullscreen(),
2401
+ "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2402
+ title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2403
+ children: isFullscreen ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Maximize, { className: "h-5 w-5" })
2404
+ }
2405
+ )
2406
+ ] })
2407
+ ] }),
2408
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-none fixed right-4 bottom-4 z-50", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pointer-events-auto", children: /* @__PURE__ */ jsxRuntime.jsx(VolumeControls, { compact: true }) }) }),
2409
+ /* @__PURE__ */ jsxRuntime.jsx("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-card/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2410
+ !orientationOk && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm", children: [
2411
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2412
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2413
+ "This game is best experienced in ",
2414
+ requiredOrientation,
2415
+ " ",
2416
+ "orientation."
2417
+ ] })
2418
+ ] }),
2419
+ /* @__PURE__ */ jsxRuntime.jsx(
2420
+ "div",
2421
+ {
2422
+ className: cn(
2423
+ "h-full w-full select-none",
2424
+ !orientationOk && "pointer-events-none opacity-30"
2425
+ ),
2426
+ children
2427
+ }
2428
+ )
2429
+ ] }) }),
2430
+ onReconnect && /* @__PURE__ */ jsxRuntime.jsx(
2431
+ QRScannerDialog,
2432
+ {
2433
+ isOpen: isScannerOpen,
2434
+ onClose: () => setIsScannerOpen(false),
2435
+ onScan: (roomCode) => {
2436
+ onReconnect(roomCode);
2437
+ setIsScannerOpen(false);
2438
+ },
2439
+ currentRoomId: roomId
2440
+ }
2441
+ )
2442
+ ] });
2443
+ };
2444
+
2445
+ // src/events.ts
2446
+ var HostEvents = {
2447
+ /**
2448
+ * Register as a master host (standalone mode)
2449
+ */
2450
+ REGISTER: "host:register",
2451
+ /**
2452
+ * Register as the system/arcade master host
2453
+ */
2454
+ REGISTER_SYSTEM: "host:registerSystem",
2455
+ /**
2456
+ * Join as a child host (game launched from arcade)
2457
+ */
2458
+ JOIN_AS_CHILD: "host:joinAsChild"
2459
+ };
2460
+ var ControllerEvents = {
2461
+ /**
2462
+ * Controller joins a room
2463
+ */
2464
+ JOIN: "controller:join",
2465
+ /**
2466
+ * Controller sends input
2467
+ */
2468
+ INPUT: "controller:input",
2469
+ /**
2470
+ * Controller leaves a room
2471
+ */
2472
+ LEAVE: "controller:leave",
2473
+ /**
2474
+ * Controller sends game state update
2475
+ */
2476
+ STATE: "controller:state",
2477
+ /**
2478
+ * Controller sends system command
2479
+ */
2480
+ SYSTEM: "controller:system"
2481
+ };
2482
+ var SystemEvents = {
2483
+ /**
2484
+ * Arcade launches a game
2485
+ */
2486
+ LAUNCH_GAME: "system:launchGame",
2487
+ /**
2488
+ * Arcade closes a game
2489
+ */
2490
+ CLOSE_GAME: "system:closeGame"
2491
+ };
2492
+ var ServerEvents = {
2493
+ /**
2494
+ * Welcome message with room/controller info
2495
+ */
2496
+ WELCOME: "server:welcome",
2497
+ /**
2498
+ * Room is ready
2499
+ */
2500
+ ROOM_READY: "server:roomReady",
2501
+ /**
2502
+ * Controller joined notification
2503
+ */
2504
+ CONTROLLER_JOINED: "server:controllerJoined",
2505
+ /**
2506
+ * Controller left notification
2507
+ */
2508
+ CONTROLLER_LEFT: "server:controllerLeft",
2509
+ /**
2510
+ * Host left notification
2511
+ */
2512
+ HOST_LEFT: "server:hostLeft",
2513
+ /**
2514
+ * Server error
2515
+ */
2516
+ ERROR: "server:error",
2517
+ /**
2518
+ * Play sound on client
2519
+ */
2520
+ PLAY_SOUND: "server:playSound"
2521
+ };
2522
+ var ClientEvents = {
2523
+ /**
2524
+ * Load a game UI in the controller iframe
2525
+ */
2526
+ LOAD_UI: "client:loadUi",
2527
+ /**
2528
+ * Unload the game UI from the controller iframe
2529
+ */
2530
+ UNLOAD_UI: "client:unloadUi",
2531
+ /**
2532
+ * Update game state display
2533
+ */
2534
+ STATE: "client:state"
2535
+ };
2536
+ var ChildEvents = {
2537
+ /**
2538
+ * Server requests child to close
2539
+ */
2540
+ CLOSE: "child:close"
2541
+ };
2542
+ var Events = {
2543
+ Host: HostEvents,
2544
+ Controller: ControllerEvents,
2545
+ System: SystemEvents,
2546
+ Server: ServerEvents,
2547
+ Client: ClientEvents,
2548
+ Child: ChildEvents
2549
+ };
2550
+
2551
+ // src/utils/ids.ts
2552
+ var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
2553
+ var generateRoomCode = () => {
2554
+ const array = new Uint32Array(4);
2555
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
2556
+ crypto.getRandomValues(array);
2557
+ } else {
2558
+ for (let i = 0; i < array.length; i += 1) {
2559
+ array[i] = Math.floor(Math.random() * alphabet.length);
2560
+ }
2561
+ }
2562
+ const code = Array.from(
2563
+ array,
2564
+ (value) => alphabet[value % alphabet.length]
2565
+ ).join("");
2566
+ return roomCodeSchema.parse(code);
2567
+ };
2568
+ var generateControllerId = () => {
2569
+ const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
2570
+ const random = alphabet[Math.floor(Math.random() * alphabet.length)];
2571
+ return `C${random}${stamp}`;
2572
+ };
2573
+
2574
+ // src/hooks/use-air-jam-controller.ts
2575
+ var getRoomFromLocation = () => {
2576
+ if (typeof window === "undefined") {
2577
+ return null;
2578
+ }
2579
+ const params = new URLSearchParams(window.location.search);
2580
+ const code = params.get("room");
2581
+ return code ? code.toUpperCase() : null;
2582
+ };
2583
+ var useAirJamController = (options = {}) => {
2584
+ const { store, getSocket, disconnectSocket } = useAirJamContext();
2585
+ const nicknameRef = React.useRef(options.nickname ?? "");
2586
+ const subControllerParams = React.useMemo(() => {
2587
+ if (typeof window === "undefined") return null;
2588
+ const params = new URLSearchParams(window.location.search);
2589
+ const room = params.get("aj_room");
2590
+ const controllerId2 = params.get("aj_controller_id");
2591
+ if (room && controllerId2) {
2592
+ return { room, controllerId: controllerId2 };
2593
+ }
2594
+ return null;
2595
+ }, []);
2596
+ const parsedRoomId = React.useMemo(() => {
2597
+ const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
2598
+ if (!code) return null;
2599
+ try {
2600
+ return roomCodeSchema.parse(code.toUpperCase());
2601
+ } catch {
2602
+ return null;
2603
+ }
2604
+ }, [options.roomId, subControllerParams]);
2605
+ const controllerId = React.useMemo(() => {
2606
+ if (subControllerParams?.controllerId) {
2607
+ return subControllerParams.controllerId;
2608
+ }
2609
+ if (options.controllerId) {
2610
+ return options.controllerId;
2611
+ }
2612
+ if (typeof window !== "undefined") {
2613
+ const params = new URLSearchParams(window.location.search);
2614
+ const urlControllerId = params.get("controllerId");
2615
+ if (urlControllerId) return urlControllerId;
2616
+ }
2617
+ return generateControllerId();
2618
+ }, [options.controllerId, subControllerParams]);
2619
+ const onStateRef = React.useRef(
2620
+ options.onState
2621
+ );
2622
+ React.useEffect(() => {
2623
+ onStateRef.current = options.onState;
2624
+ }, [options.onState]);
2625
+ const connectionState = zustand.useStore(
2626
+ store,
2627
+ shallow.useShallow((state) => ({
2628
+ connectionStatus: state.connectionStatus,
2629
+ lastError: state.lastError,
2630
+ controllerId: state.controllerId,
2631
+ players: state.players,
2632
+ gameState: state.gameState,
2633
+ stateMessage: state.stateMessage
2634
+ }))
2635
+ );
2636
+ const [reconnectKey, setReconnectKey] = React.useState(0);
2637
+ const reconnect = React.useCallback(() => {
2638
+ if (!parsedRoomId) return;
2639
+ disconnectSocket("controller");
2640
+ setReconnectKey((prev) => prev + 1);
2641
+ }, [parsedRoomId, disconnectSocket]);
2642
+ const isChildMode = React.useMemo(() => {
2643
+ if (typeof window === "undefined") return false;
2644
+ const params = new URLSearchParams(window.location.search);
2645
+ return params.get("airjam_mode") === "child";
2646
+ }, []);
2647
+ const shouldConnect = React.useMemo(() => {
2648
+ if (options.forceConnect) return true;
2649
+ if (subControllerParams) return true;
2650
+ if (typeof window !== "undefined") {
2651
+ const params = new URLSearchParams(window.location.search);
2652
+ return params.get("airjam_force_connect") === "true";
2653
+ }
2654
+ return false;
2655
+ }, [options.forceConnect, subControllerParams]);
2656
+ const canConnect = React.useMemo(
2657
+ () => !isChildMode || shouldConnect,
2658
+ [isChildMode, shouldConnect]
2659
+ );
2660
+ const socket = React.useMemo(
2661
+ () => canConnect && parsedRoomId ? getSocket("controller") : null,
2662
+ [canConnect, parsedRoomId, getSocket]
2663
+ );
2664
+ React.useEffect(() => {
2665
+ if (!socket) return;
2666
+ const handleSignal = (signal) => {
2667
+ if (signal.type !== "HAPTIC") return;
2668
+ if (typeof navigator === "undefined" || !navigator.vibrate) return;
2669
+ const payload = signal.payload;
2670
+ switch (payload.pattern) {
2671
+ case "light":
2672
+ navigator.vibrate(10);
2673
+ break;
2674
+ case "medium":
2675
+ navigator.vibrate(30);
2676
+ break;
2677
+ case "heavy":
2678
+ navigator.vibrate([50, 20, 50]);
2679
+ break;
2680
+ case "success":
2681
+ navigator.vibrate([10, 30, 10]);
2682
+ break;
2683
+ case "failure":
2684
+ navigator.vibrate([50, 50, 50, 50]);
2685
+ break;
2686
+ case "custom":
2687
+ if (Array.isArray(payload.sequence)) {
2688
+ navigator.vibrate(payload.sequence);
2689
+ } else if (typeof payload.sequence === "number") {
2690
+ navigator.vibrate(payload.sequence);
2691
+ }
2692
+ break;
2693
+ }
2694
+ };
2695
+ socket.on("server:signal", handleSignal);
2696
+ return () => {
2697
+ socket.off("server:signal", handleSignal);
2698
+ };
2699
+ }, [socket]);
2700
+ React.useEffect(() => {
2701
+ const storeState = store.getState();
2702
+ storeState.setMode(detectRunMode());
2703
+ storeState.setRole("controller");
2704
+ storeState.setRoomId(parsedRoomId);
2705
+ storeState.setStatus(parsedRoomId ? "connecting" : "idle");
2706
+ storeState.setError(void 0);
2707
+ if (!canConnect) {
2708
+ storeState.setStatus("connected");
2709
+ const handleMessage = (event) => {
2710
+ if (event.source !== window.parent) return;
2711
+ const data = event.data;
2712
+ if (data?.type === "AIRJAM_STATE") {
2713
+ const payload = data.payload;
2714
+ if (payload.gameState) storeState.setGameState(payload.gameState);
2715
+ if (payload.message !== void 0)
2716
+ storeState.setStateMessage(payload.message);
2717
+ onStateRef.current?.(payload);
2718
+ }
2719
+ };
2720
+ window.addEventListener("message", handleMessage);
2721
+ window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
2722
+ return () => {
2723
+ window.removeEventListener("message", handleMessage);
2724
+ storeState.setStatus("disconnected");
2725
+ };
2726
+ }
2727
+ if (!parsedRoomId || !socket || !controllerId) {
2728
+ storeState.setStatus("idle");
2729
+ return;
2730
+ }
2731
+ storeState.setControllerId(controllerId);
2732
+ const handleConnect = () => {
2733
+ store.getState().setStatus("connected");
2734
+ if (subControllerParams) {
2735
+ return;
2736
+ }
2737
+ const payload = controllerJoinSchema.parse({
2738
+ roomId: parsedRoomId,
2739
+ controllerId,
2740
+ nickname: nicknameRef.current || void 0
2741
+ });
2742
+ socket.emit("controller:join", payload, (ack) => {
2743
+ const storeState2 = store.getState();
2744
+ if (!ack.ok) {
2745
+ storeState2.setError(ack.message ?? "Unable to join room");
2746
+ storeState2.setStatus("disconnected");
2747
+ return;
2748
+ }
2749
+ if (ack.controllerId) {
2750
+ storeState2.setControllerId(ack.controllerId);
2751
+ }
2752
+ storeState2.setStatus("connected");
2753
+ });
2754
+ };
2755
+ const handleDisconnect = () => {
2756
+ store.getState().setStatus("disconnected");
2757
+ };
2758
+ const handleWelcome = (payload) => {
2759
+ const storeState2 = store.getState();
2760
+ const storeRoomId = storeState2.roomId;
2761
+ if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
2762
+ return;
2763
+ }
2764
+ if (!storeRoomId && payload.roomId) {
2765
+ storeState2.setRoomId(payload.roomId);
2766
+ }
2767
+ if (!payload.player) {
2768
+ storeState2.setError(
2769
+ "Welcome message received but no player profile included."
2770
+ );
2771
+ return;
2772
+ }
2773
+ storeState2.upsertPlayer(payload.player);
2774
+ };
2775
+ const handleState = (payload) => {
2776
+ if (payload.roomId !== parsedRoomId) return;
2777
+ const storeState2 = store.getState();
2778
+ if (payload.state.gameState) {
2779
+ storeState2.setGameState(payload.state.gameState);
2780
+ }
2781
+ if (payload.state.message !== void 0) {
2782
+ storeState2.setStateMessage(payload.state.message);
2783
+ }
2784
+ onStateRef.current?.(payload.state);
2785
+ };
2786
+ const handleHostLeft = (payload) => {
2787
+ const storeState2 = store.getState();
2788
+ storeState2.setError(payload.reason);
2789
+ storeState2.setStatus("disconnected");
2790
+ storeState2.resetGameState();
2791
+ setTimeout(() => {
2792
+ disconnectSocket("controller");
2793
+ setReconnectKey((prev) => prev + 1);
2794
+ }, 1e3);
2795
+ };
2796
+ const handleError = (payload) => {
2797
+ store.getState().setError(payload.message);
2798
+ };
2799
+ socket.on("connect", handleConnect);
2800
+ socket.on("disconnect", handleDisconnect);
2801
+ socket.on("server:welcome", handleWelcome);
2802
+ socket.on("server:state", handleState);
2803
+ socket.on("server:hostLeft", handleHostLeft);
2804
+ socket.on("server:error", handleError);
2805
+ socket.connect();
2806
+ return () => {
2807
+ socket.off("connect", handleConnect);
2808
+ socket.off("disconnect", handleDisconnect);
2809
+ socket.off("server:welcome", handleWelcome);
2810
+ socket.off("server:state", handleState);
2811
+ socket.off("server:hostLeft", handleHostLeft);
2812
+ socket.off("server:error", handleError);
2813
+ };
2814
+ }, [
2815
+ parsedRoomId,
2816
+ reconnectKey,
2817
+ canConnect,
2818
+ socket,
2819
+ controllerId,
2820
+ subControllerParams,
2821
+ store,
2822
+ disconnectSocket
2823
+ ]);
2824
+ const setNickname = React.useCallback((value) => {
2825
+ nicknameRef.current = value;
2826
+ }, []);
2827
+ const sendInput = React.useCallback(
2828
+ (input) => {
2829
+ const storeState = store.getState();
2830
+ if (!canConnect) {
2831
+ if (typeof window !== "undefined") {
2832
+ window.parent.postMessage(
2833
+ {
2834
+ type: "AIRJAM_INPUT",
2835
+ payload: input
2836
+ },
2837
+ "*"
2838
+ );
2839
+ }
2840
+ return true;
2841
+ }
2842
+ if (!parsedRoomId || !storeState.controllerId || !socket) {
2843
+ storeState.setError("Not connected to a room");
2844
+ return false;
2845
+ }
2846
+ if (!socket.connected) {
2847
+ return false;
2848
+ }
2849
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
2850
+ storeState.setError("Input must be an object");
2851
+ return false;
2852
+ }
2853
+ const payload = controllerInputSchema.safeParse({
2854
+ roomId: parsedRoomId,
2855
+ controllerId: storeState.controllerId,
2856
+ input
2857
+ });
2858
+ if (!payload.success) {
2859
+ storeState.setError(payload.error.message);
2860
+ return false;
2861
+ }
2862
+ socket.emit("controller:input", payload.data);
2863
+ return true;
2864
+ },
2865
+ [parsedRoomId, canConnect, socket, store]
2866
+ );
2867
+ const sendSystemCommand = React.useCallback(
2868
+ (command) => {
2869
+ const storeState = store.getState();
2870
+ if (!canConnect) return;
2871
+ if (!parsedRoomId || !storeState.controllerId || !socket) return;
2872
+ if (!socket.connected) return;
2873
+ const payload = controllerSystemSchema.safeParse({
2874
+ roomId: parsedRoomId,
2875
+ command
2876
+ });
2877
+ if (payload.success) {
2878
+ socket.emit("controller:system", payload.data);
2879
+ }
2880
+ },
2881
+ [parsedRoomId, canConnect, socket, store]
2882
+ );
2883
+ return {
2884
+ roomId: parsedRoomId,
2885
+ controllerId: connectionState.controllerId,
2886
+ connectionStatus: connectionState.connectionStatus,
2887
+ lastError: connectionState.lastError,
2888
+ gameState: connectionState.gameState,
2889
+ stateMessage: connectionState.stateMessage,
2890
+ sendInput,
2891
+ sendSystemCommand,
2892
+ setNickname,
2893
+ reconnect,
2894
+ players: connectionState.players,
2895
+ socket
2896
+ };
2897
+ };
2898
+ var useAirJamHost = (options = {}) => {
2899
+ const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
2900
+ const arcadeParams = React.useMemo(() => {
2901
+ if (typeof window === "undefined") return null;
2902
+ const params = new URLSearchParams(window.location.search);
2903
+ const room = params.get("aj_room");
2904
+ const token = params.get("aj_token");
2905
+ if (room && token) {
2906
+ return { room, token };
2907
+ }
2908
+ return null;
2909
+ }, []);
2910
+ const isChildMode = !!arcadeParams;
2911
+ const shouldConnect = true;
2912
+ const [fallbackRoomId] = React.useState(() => generateRoomCode());
2913
+ const parsedRoomId = React.useMemo(() => {
2914
+ if (arcadeParams) {
2915
+ return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
2916
+ }
2917
+ if (typeof window !== "undefined") {
2918
+ const params = new URLSearchParams(window.location.search);
2919
+ const paramRoom = params.get("room");
2920
+ if (paramRoom) {
2921
+ const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
2922
+ if (result.success) return result.data;
2923
+ }
2924
+ }
2925
+ if (options.roomId) {
2926
+ return roomCodeSchema.parse(options.roomId.toUpperCase());
2927
+ }
2928
+ return fallbackRoomId;
2929
+ }, [options.roomId, fallbackRoomId, arcadeParams]);
2930
+ React.useEffect(() => {
2931
+ if (inputManager) {
2932
+ inputManager.setRoomId(parsedRoomId);
2933
+ }
2934
+ }, [inputManager, parsedRoomId]);
2935
+ const [joinUrl, setJoinUrl] = React.useState("");
2936
+ const onPlayerJoinRef = React.useRef(options.onPlayerJoin);
2937
+ const onPlayerLeaveRef = React.useRef(options.onPlayerLeave);
2938
+ const onChildCloseRef = React.useRef(options.onChildClose);
2939
+ React.useEffect(() => {
2940
+ onPlayerJoinRef.current = options.onPlayerJoin;
2941
+ onPlayerLeaveRef.current = options.onPlayerLeave;
2942
+ onChildCloseRef.current = options.onChildClose;
2943
+ }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
2944
+ const connectionState = zustand.useStore(
2945
+ store,
2946
+ shallow.useShallow((state) => ({
2947
+ connectionStatus: state.connectionStatus,
2948
+ lastError: state.lastError,
2949
+ players: state.players,
2950
+ gameState: state.gameState,
2951
+ mode: state.mode
2952
+ }))
2953
+ );
2954
+ const socket = React.useMemo(
2955
+ () => getSocket("host") ,
2956
+ [shouldConnect, getSocket]
2957
+ );
2958
+ const [lastToggle, setLastToggle] = React.useState(0);
2959
+ const toggleGameState = React.useCallback(() => {
2960
+ const now = Date.now();
2961
+ if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
2962
+ return;
2963
+ }
2964
+ setLastToggle(now);
2965
+ if (!socket || !socket.connected) {
2966
+ return;
2967
+ }
2968
+ const payload = controllerSystemSchema.safeParse({
2969
+ roomId: parsedRoomId,
2970
+ command: "toggle_pause"
2971
+ });
2972
+ if (payload.success) {
2973
+ socket.emit("host:system", payload.data);
2974
+ }
2975
+ }, [socket, parsedRoomId, lastToggle]);
2976
+ const sendState = React.useCallback(
2977
+ (state) => {
2978
+ if (!socket || !socket.connected) {
2979
+ return false;
2980
+ }
2981
+ const payload = controllerStateSchema.safeParse({
2982
+ roomId: parsedRoomId,
2983
+ state
2984
+ });
2985
+ if (!payload.success) {
2986
+ return false;
2987
+ }
2988
+ socket.emit("host:state", payload.data);
2989
+ return true;
2990
+ },
2991
+ [socket, parsedRoomId]
2992
+ );
2993
+ const sendSignal = React.useCallback(
2994
+ (type, payload, targetId) => {
2995
+ if (!socket || !socket.connected) {
2996
+ return;
2997
+ }
2998
+ const signal = {
2999
+ targetId,
3000
+ type,
3001
+ payload
3002
+ };
3003
+ socket.emit("host:signal", signal);
3004
+ },
3005
+ [socket]
3006
+ );
3007
+ const reconnect = React.useCallback(() => {
3008
+ disconnectSocket("host");
3009
+ if (socket) {
3010
+ socket.connect();
3011
+ }
3012
+ }, [socket, disconnectSocket]);
3013
+ React.useEffect(() => {
3014
+ (async () => {
3015
+ const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
3016
+ path: config.controllerPath,
3017
+ host: config.publicHost
3018
+ });
3019
+ setJoinUrl(url);
3020
+ })();
3021
+ }, [parsedRoomId, config.controllerPath, config.publicHost]);
3022
+ const setRegisteredRoomId = zustand.useStore(store, (s) => s.setRegisteredRoomId);
3023
+ React.useEffect(() => {
3024
+ const storeState = store.getState();
3025
+ storeState.setMode(detectRunMode());
3026
+ storeState.setRole("host");
3027
+ storeState.setRoomId(parsedRoomId);
3028
+ storeState.setStatus("connecting");
3029
+ storeState.setError(void 0);
3030
+ if (!socket) {
3031
+ storeState.setStatus("idle");
3032
+ return;
3033
+ }
3034
+ const registerHost = async () => {
3035
+ const storeState2 = store.getState();
3036
+ const currentRegisteredRoomId2 = store.getState().registeredRoomId;
3037
+ if (currentRegisteredRoomId2 === parsedRoomId && socket.connected) {
3038
+ return;
3039
+ }
3040
+ if (arcadeParams) {
3041
+ const childRoomId = roomCodeSchema.parse(
3042
+ arcadeParams.room.toUpperCase()
3043
+ );
3044
+ const payload = {
3045
+ roomId: childRoomId,
3046
+ joinToken: arcadeParams.token
3047
+ };
3048
+ socket.emit("host:joinAsChild", payload, (ack) => {
3049
+ if (!ack.ok) {
3050
+ storeState2.setError(ack.message ?? "Failed to join as child");
3051
+ storeState2.setStatus("disconnected");
3052
+ setRegisteredRoomId(null);
3053
+ return;
3054
+ }
3055
+ storeState2.setStatus("connected");
3056
+ storeState2.setRoomId(childRoomId);
3057
+ setRegisteredRoomId(childRoomId);
3058
+ });
3059
+ } else {
3060
+ const payload = hostRegistrationSchema.parse({
3061
+ roomId: parsedRoomId,
3062
+ maxPlayers: options.maxPlayers ?? config.maxPlayers,
3063
+ apiKey: options.apiKey ?? config.apiKey
3064
+ });
3065
+ socket.emit("host:register", payload, (ack) => {
3066
+ if (!ack.ok) {
3067
+ storeState2.setError(ack.message ?? "Failed to register host");
3068
+ storeState2.setStatus("disconnected");
3069
+ setRegisteredRoomId(null);
3070
+ return;
3071
+ }
3072
+ storeState2.setStatus("connected");
3073
+ if (ack.roomId) {
3074
+ storeState2.setRoomId(ack.roomId);
3075
+ setRegisteredRoomId(ack.roomId);
3076
+ } else {
3077
+ setRegisteredRoomId(parsedRoomId);
3078
+ }
3079
+ });
3080
+ }
3081
+ };
3082
+ const handleConnect = () => {
3083
+ store.getState().setStatus("connected");
3084
+ registerHost();
3085
+ };
3086
+ const handleDisconnect = () => {
3087
+ store.getState().setStatus("disconnected");
3088
+ };
3089
+ const handleJoin = (payload) => {
3090
+ if (payload.player) {
3091
+ store.getState().upsertPlayer(payload.player);
3092
+ setTimeout(() => {
3093
+ onPlayerJoinRef.current?.(payload.player);
3094
+ }, 0);
3095
+ }
3096
+ };
3097
+ const handleLeave = (payload) => {
3098
+ store.getState().removePlayer(payload.controllerId);
3099
+ onPlayerLeaveRef.current?.(payload.controllerId);
3100
+ };
3101
+ const handleInput = (payload) => {
3102
+ if (inputManager) {
3103
+ inputManager.handleInput(payload);
3104
+ }
3105
+ };
3106
+ const handleChildClose = () => {
3107
+ onChildCloseRef.current?.();
3108
+ };
3109
+ const handleState = (payload) => {
3110
+ if (payload.roomId !== parsedRoomId) return;
3111
+ const storeState2 = store.getState();
3112
+ if (payload.state.gameState) {
3113
+ storeState2.setGameState(payload.state.gameState);
3114
+ }
3115
+ if (payload.state.message !== void 0) {
3116
+ storeState2.setStateMessage(payload.state.message);
3117
+ }
3118
+ };
3119
+ const handleError = (payload) => {
3120
+ store.getState().setError(payload.message);
3121
+ };
3122
+ socket.on("connect", handleConnect);
3123
+ socket.on("disconnect", handleDisconnect);
3124
+ socket.on("server:controllerJoined", handleJoin);
3125
+ socket.on("server:controllerLeft", handleLeave);
3126
+ socket.on("server:input", handleInput);
3127
+ socket.on("server:error", handleError);
3128
+ socket.on("server:closeChild", handleChildClose);
3129
+ socket.on("server:state", handleState);
3130
+ socket.connect();
3131
+ const currentRegisteredRoomId = store.getState().registeredRoomId;
3132
+ if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
3133
+ registerHost();
3134
+ }
3135
+ if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
3136
+ setRegisteredRoomId(null);
3137
+ }
3138
+ return () => {
3139
+ socket.off("connect", handleConnect);
3140
+ socket.off("disconnect", handleDisconnect);
3141
+ socket.off("server:controllerJoined", handleJoin);
3142
+ socket.off("server:controllerLeft", handleLeave);
3143
+ socket.off("server:input", handleInput);
3144
+ socket.off("server:error", handleError);
3145
+ socket.off("server:closeChild", handleChildClose);
3146
+ socket.off("server:state", handleState);
3147
+ };
3148
+ }, [
3149
+ config.maxPlayers,
3150
+ config.apiKey,
3151
+ options.maxPlayers,
3152
+ options.apiKey,
3153
+ parsedRoomId,
3154
+ arcadeParams,
3155
+ shouldConnect,
3156
+ socket,
3157
+ store,
3158
+ inputManager,
3159
+ setRegisteredRoomId
3160
+ ]);
3161
+ const returnSocket = socket ?? getSocket("host");
3162
+ const getInput = React.useCallback(
3163
+ (controllerId) => {
3164
+ if (!inputManager) {
3165
+ return void 0;
3166
+ }
3167
+ return inputManager.getInput(controllerId);
3168
+ },
3169
+ [inputManager]
3170
+ );
3171
+ return {
3172
+ roomId: parsedRoomId,
3173
+ joinUrl,
3174
+ connectionStatus: connectionState.connectionStatus,
3175
+ players: connectionState.players,
3176
+ lastError: connectionState.lastError,
3177
+ mode: connectionState.mode,
3178
+ gameState: connectionState.gameState,
3179
+ toggleGameState,
3180
+ sendState,
3181
+ sendSignal,
3182
+ reconnect,
3183
+ socket: returnSocket,
3184
+ isChildMode,
3185
+ getInput
3186
+ };
3187
+ };
3188
+ var getRoomFromLocation2 = () => {
3189
+ if (typeof window === "undefined") {
3190
+ return null;
3191
+ }
3192
+ const params = new URLSearchParams(window.location.search);
3193
+ const code = params.get("room");
3194
+ return code ? code.toUpperCase() : null;
3195
+ };
3196
+ var useAirJamShell = (options = {}) => {
3197
+ const { store, getSocket } = useAirJamContext();
3198
+ const nicknameRef = React.useRef(options.nickname ?? "Arcade Shell");
3199
+ const parsedRoomId = React.useMemo(() => {
3200
+ const code = options.roomId ?? getRoomFromLocation2();
3201
+ if (!code) return null;
3202
+ try {
3203
+ return roomCodeSchema.parse(code.toUpperCase());
3204
+ } catch {
3205
+ return null;
3206
+ }
3207
+ }, [options.roomId]);
3208
+ const controllerId = React.useMemo(() => {
3209
+ if (options.controllerId) return options.controllerId;
3210
+ if (typeof window !== "undefined") {
3211
+ const params = new URLSearchParams(window.location.search);
3212
+ const urlControllerId = params.get("controllerId");
3213
+ if (urlControllerId) return urlControllerId;
3214
+ }
3215
+ return generateControllerId();
3216
+ }, [options.controllerId]);
3217
+ const [activeUrl, setActiveUrl] = React.useState(null);
3218
+ const connectionState = zustand.useStore(
3219
+ store,
3220
+ shallow.useShallow((state) => ({
3221
+ connectionStatus: state.connectionStatus,
3222
+ lastError: state.lastError,
3223
+ controllerId: state.controllerId,
3224
+ players: state.players,
3225
+ gameState: state.gameState
3226
+ }))
3227
+ );
3228
+ const socket = React.useMemo(
3229
+ () => parsedRoomId ? getSocket("controller") : null,
3230
+ [parsedRoomId, getSocket]
3231
+ );
3232
+ React.useEffect(() => {
3233
+ if (!socket) return;
3234
+ const handleSignal = (signal) => {
3235
+ if (signal.type !== "HAPTIC") return;
3236
+ if (typeof navigator === "undefined" || !navigator.vibrate) return;
3237
+ const payload = signal.payload;
3238
+ switch (payload.pattern) {
3239
+ case "light":
3240
+ navigator.vibrate(10);
3241
+ break;
3242
+ case "medium":
3243
+ navigator.vibrate(30);
3244
+ break;
3245
+ case "heavy":
3246
+ navigator.vibrate([50, 20, 50]);
3247
+ break;
3248
+ case "success":
3249
+ navigator.vibrate([10, 30, 10]);
3250
+ break;
3251
+ case "failure":
3252
+ navigator.vibrate([50, 50, 50, 50]);
3253
+ break;
3254
+ case "custom":
3255
+ if (Array.isArray(payload.sequence)) {
3256
+ navigator.vibrate(payload.sequence);
3257
+ } else if (typeof payload.sequence === "number") {
3258
+ navigator.vibrate(payload.sequence);
3259
+ }
3260
+ break;
3261
+ }
3262
+ };
3263
+ socket.on("server:signal", handleSignal);
3264
+ return () => {
3265
+ socket.off("server:signal", handleSignal);
3266
+ };
3267
+ }, [socket]);
3268
+ React.useEffect(() => {
3269
+ const storeState = store.getState();
3270
+ storeState.setMode(detectRunMode());
3271
+ storeState.setRole("controller");
3272
+ storeState.setRoomId(parsedRoomId);
3273
+ storeState.setStatus(parsedRoomId ? "connecting" : "idle");
3274
+ storeState.setError(void 0);
3275
+ if (!parsedRoomId || !socket || !controllerId) {
3276
+ storeState.setStatus("idle");
3277
+ return;
3278
+ }
3279
+ storeState.setControllerId(controllerId);
3280
+ const handleConnect = () => {
3281
+ store.getState().setStatus("connected");
3282
+ const payload = controllerJoinSchema.parse({
3283
+ roomId: parsedRoomId,
3284
+ controllerId,
3285
+ nickname: nicknameRef.current || void 0
3286
+ });
3287
+ socket.emit("controller:join", payload, (ack) => {
3288
+ const storeState2 = store.getState();
3289
+ if (!ack.ok) {
3290
+ storeState2.setError(ack.message ?? "Unable to join room");
3291
+ storeState2.setStatus("disconnected");
3292
+ return;
3293
+ }
3294
+ if (ack.controllerId) {
3295
+ storeState2.setControllerId(ack.controllerId);
3296
+ }
3297
+ storeState2.setStatus("connected");
3298
+ });
3299
+ };
3300
+ const handleDisconnect = () => {
3301
+ store.getState().setStatus("disconnected");
3302
+ };
3303
+ const handleLoadUi = (payload) => {
3304
+ setActiveUrl(payload.url);
3305
+ };
3306
+ const handleUnloadUi = () => {
3307
+ setActiveUrl(null);
3308
+ };
3309
+ const handleWelcome = (payload) => {
3310
+ const storeState2 = store.getState();
3311
+ const storeRoomId = storeState2.roomId;
3312
+ if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
3313
+ return;
3314
+ }
3315
+ if (!storeRoomId && payload.roomId) {
3316
+ storeState2.setRoomId(payload.roomId);
3317
+ }
3318
+ if (payload.player) {
3319
+ storeState2.upsertPlayer(payload.player);
3320
+ }
3321
+ };
3322
+ const handleState = (payload) => {
3323
+ if (payload.roomId !== parsedRoomId) return;
3324
+ const storeState2 = store.getState();
3325
+ if (payload.state.gameState) {
3326
+ storeState2.setGameState(payload.state.gameState);
3327
+ }
3328
+ if (payload.state.message !== void 0) {
3329
+ storeState2.setStateMessage(payload.state.message);
3330
+ }
3331
+ };
3332
+ const handleError = (payload) => {
3333
+ store.getState().setError(payload.message);
3334
+ };
3335
+ const handleMessage = (event) => {
3336
+ const storeState2 = store.getState();
3337
+ const data = event.data;
3338
+ if (data?.type === "AIRJAM_INPUT") {
3339
+ const input = data.payload;
3340
+ const payload = controllerInputSchema.safeParse({
3341
+ roomId: parsedRoomId,
3342
+ controllerId: storeState2.controllerId,
3343
+ input
3344
+ });
3345
+ if (payload.success) {
3346
+ socket.emit("controller:input", payload.data);
3347
+ }
3348
+ } else if (data?.type === "AIRJAM_READY") ;
3349
+ };
3350
+ socket.on("connect", handleConnect);
3351
+ socket.on("disconnect", handleDisconnect);
3352
+ socket.on("server:welcome", handleWelcome);
3353
+ socket.on("server:state", handleState);
3354
+ socket.on("client:loadUi", handleLoadUi);
3355
+ socket.on("client:unloadUi", handleUnloadUi);
3356
+ socket.on("server:error", handleError);
3357
+ window.addEventListener("message", handleMessage);
3358
+ socket.connect();
3359
+ return () => {
3360
+ socket.off("connect", handleConnect);
3361
+ socket.off("disconnect", handleDisconnect);
3362
+ socket.off("server:welcome", handleWelcome);
3363
+ socket.off("server:state", handleState);
3364
+ socket.off("client:loadUi", handleLoadUi);
3365
+ socket.off("client:unloadUi", handleUnloadUi);
3366
+ socket.off("server:error", handleError);
3367
+ window.removeEventListener("message", handleMessage);
3368
+ };
3369
+ }, [parsedRoomId, socket, controllerId, store]);
3370
+ const sendInput = React.useCallback(
3371
+ (input) => {
3372
+ const storeState = store.getState();
3373
+ if (!parsedRoomId || !storeState.controllerId || !socket) {
3374
+ storeState.setError("Not connected to a room");
3375
+ return false;
3376
+ }
3377
+ if (!socket.connected) {
3378
+ return false;
3379
+ }
3380
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3381
+ storeState.setError("Input must be an object");
3382
+ return false;
3383
+ }
3384
+ const payload = controllerInputSchema.safeParse({
3385
+ roomId: parsedRoomId,
3386
+ controllerId: storeState.controllerId,
3387
+ input
3388
+ });
3389
+ if (!payload.success) {
3390
+ storeState.setError(payload.error.message);
3391
+ return false;
3392
+ }
3393
+ socket.emit("controller:input", payload.data);
3394
+ return true;
3395
+ },
3396
+ [parsedRoomId, socket, store]
3397
+ );
3398
+ const sendSystemCommand = React.useCallback(
3399
+ (command) => {
3400
+ const storeState = store.getState();
3401
+ if (!parsedRoomId || !storeState.controllerId || !socket) return;
3402
+ if (!socket.connected) return;
3403
+ const payload = controllerSystemSchema.safeParse({
3404
+ roomId: parsedRoomId,
3405
+ command
3406
+ });
3407
+ if (payload.success) {
3408
+ socket.emit("controller:system", payload.data);
3409
+ }
3410
+ },
3411
+ [parsedRoomId, socket, store]
3412
+ );
3413
+ return {
3414
+ roomId: parsedRoomId,
3415
+ controllerId: connectionState.controllerId,
3416
+ connectionStatus: connectionState.connectionStatus,
3417
+ lastError: connectionState.lastError,
3418
+ activeUrl,
3419
+ players: connectionState.players,
3420
+ gameState: connectionState.gameState,
3421
+ sendInput,
3422
+ sendSystemCommand
3423
+ };
3424
+ };
3425
+ var useGetInput = () => {
3426
+ const { inputManager } = useAirJamContext();
3427
+ return React.useCallback(
3428
+ (controllerId) => {
3429
+ if (!inputManager) {
3430
+ return void 0;
3431
+ }
3432
+ return inputManager.getInput(controllerId);
3433
+ },
3434
+ [inputManager]
3435
+ );
3436
+ };
3437
+ var useSendSignal = () => {
3438
+ const { getSocket } = useAirJamContext();
3439
+ const sendSignal = React.useCallback(
3440
+ (type, payload, targetId) => {
3441
+ const socket = getSocket("host");
3442
+ if (!socket || !socket.connected) {
3443
+ return;
3444
+ }
3445
+ const signal = {
3446
+ targetId,
3447
+ type,
3448
+ payload
3449
+ };
3450
+ socket.emit("host:signal", signal);
3451
+ },
3452
+ [getSocket]
3453
+ );
3454
+ return sendSignal;
3455
+ };
3456
+
3457
+ exports.AIRJAM_PROXY_PREFIX = AIRJAM_PROXY_PREFIX;
3458
+ exports.AirJamContext = AirJamContext;
3459
+ exports.AirJamOverlay = AirJamOverlay;
3460
+ exports.AirJamProvider = AirJamProvider;
3461
+ exports.AudioManager = AudioManager;
3462
+ exports.AudioProvider = AudioProvider;
3463
+ exports.Button = Button;
3464
+ exports.ChildEvents = ChildEvents;
3465
+ exports.ClientEvents = ClientEvents;
3466
+ exports.ControllerEvents = ControllerEvents;
3467
+ exports.ControllerShell = ControllerShell;
3468
+ exports.DEFAULT_CONTROLLER_PATH = DEFAULT_CONTROLLER_PATH;
3469
+ exports.DEFAULT_MAX_PLAYERS = DEFAULT_MAX_PLAYERS;
3470
+ exports.DEFAULT_SERVER_PORT = DEFAULT_SERVER_PORT;
3471
+ exports.ErrorCode = ErrorCode;
3472
+ exports.Events = Events;
3473
+ exports.HostEvents = HostEvents;
3474
+ exports.INPUT_DEBOUNCE_MS = INPUT_DEBOUNCE_MS;
3475
+ exports.SOCKET_CONFIG = SOCKET_CONFIG;
3476
+ exports.ServerEvents = ServerEvents;
3477
+ exports.Slider = Slider;
3478
+ exports.SocketManager = SocketManager;
3479
+ exports.SystemEvents = SystemEvents;
3480
+ exports.TOGGLE_DEBOUNCE_MS = TOGGLE_DEBOUNCE_MS;
3481
+ exports.UrlBuilder = UrlBuilder;
3482
+ exports.VolumeControls = VolumeControls;
3483
+ exports.buttonVariants = buttonVariants;
3484
+ exports.controllerInputSchema = controllerInputSchema;
3485
+ exports.controllerJoinSchema = controllerJoinSchema;
3486
+ exports.controllerLeaveSchema = controllerLeaveSchema;
3487
+ exports.controllerStateSchema = controllerStateSchema;
3488
+ exports.controllerSystemSchema = controllerSystemSchema;
3489
+ exports.createAudioManager = createAudioManager;
3490
+ exports.detectSoundCategory = detectSoundCategory;
3491
+ exports.generateControllerId = generateControllerId;
3492
+ exports.generateRoomCode = generateRoomCode;
3493
+ exports.getLocalNetworkIp = getLocalNetworkIp;
3494
+ exports.hostJoinAsChildSchema = hostJoinAsChildSchema;
3495
+ exports.hostRegisterSystemSchema = hostRegisterSystemSchema;
3496
+ exports.hostRegistrationSchema = hostRegistrationSchema;
3497
+ exports.roomCodeSchema = roomCodeSchema;
3498
+ exports.systemLaunchGameSchema = systemLaunchGameSchema;
3499
+ exports.urlBuilder = urlBuilder;
3500
+ exports.useAirJamConfig = useAirJamConfig;
3501
+ exports.useAirJamContext = useAirJamContext;
3502
+ exports.useAirJamController = useAirJamController;
3503
+ exports.useAirJamHost = useAirJamHost;
3504
+ exports.useAirJamShell = useAirJamShell;
3505
+ exports.useAirJamSocket = useAirJamSocket;
3506
+ exports.useAirJamState = useAirJamState;
3507
+ exports.useAudio = useAudio;
3508
+ exports.useAudioLegacy = useAudioLegacy;
3509
+ exports.useAudioManager = useAudioManager;
3510
+ exports.useGetInput = useGetInput;
3511
+ exports.useSendSignal = useSendSignal;
3512
+ exports.useVolumeStore = useVolumeStore;
3513
+ //# sourceMappingURL=index.cjs.map
3514
+ //# sourceMappingURL=index.cjs.map