@air-jam/sdk 0.1.0 → 0.1.2

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 (37) hide show
  1. package/dist/{chunk-XSXI3RIS.js → chunk-B5DURUWT.js} +11 -3
  2. package/dist/chunk-B5DURUWT.js.map +1 -0
  3. package/dist/index.cjs +2346 -1931
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +97 -41
  6. package/dist/index.d.ts +97 -41
  7. package/dist/index.js +2401 -2001
  8. package/dist/index.js.map +1 -1
  9. package/dist/protocol.cjs +10 -0
  10. package/dist/protocol.cjs.map +1 -1
  11. package/dist/protocol.d.cts +42 -1
  12. package/dist/protocol.d.ts +42 -1
  13. package/dist/protocol.js +1 -1
  14. package/package.json +5 -1
  15. package/src/AirJamClient.ts +1 -552
  16. package/src/audio/audio-manager.ts +12 -1
  17. package/src/audio/volume-store.ts +47 -0
  18. package/src/components/air-jam-debug.tsx +77 -0
  19. package/src/components/air-jam-overlay.tsx +243 -186
  20. package/src/components/controller-shell.tsx +174 -182
  21. package/src/components/debug-state-dialog.tsx +83 -0
  22. package/src/components/player-avatar.tsx +64 -0
  23. package/src/components/qr-scanner-dialog.tsx +2 -2
  24. package/src/components/ui/button.tsx +1 -1
  25. package/src/components/ui/dialog.tsx +122 -0
  26. package/src/constants.ts +3 -2
  27. package/src/context/air-jam-context.tsx +3 -14
  28. package/src/hooks/use-air-jam-controller.ts +1 -1
  29. package/src/hooks/use-air-jam-host.ts +94 -49
  30. package/src/hooks/use-air-jam-shell.ts +36 -0
  31. package/src/index.ts +6 -0
  32. package/src/internal/input-manager.ts +28 -14
  33. package/src/protocol.ts +55 -0
  34. package/src/store/create-air-jam-store.ts +274 -0
  35. package/src/store/index.ts +1 -0
  36. package/src/utils/url-builder.ts +3 -3
  37. package/dist/chunk-XSXI3RIS.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -7,15 +7,16 @@ var socket_ioClient = require('socket.io-client');
7
7
  var jsxRuntime = require('react/jsx-runtime');
8
8
  var howler = require('howler');
9
9
  var lucideReact = require('lucide-react');
10
- var QRCode = require('qrcode');
10
+ var reactSlot = require('@radix-ui/react-slot');
11
11
  var classVarianceAuthority = require('class-variance-authority');
12
12
  var clsx = require('clsx');
13
13
  var tailwindMerge = require('tailwind-merge');
14
- var reactSlot = require('@radix-ui/react-slot');
14
+ var DialogPrimitive = require('@radix-ui/react-dialog');
15
+ var QRCode = require('qrcode');
16
+ var zod = require('zod');
15
17
  var TabsPrimitive = require('@radix-ui/react-tabs');
16
18
  var SliderPrimitive = require('@radix-ui/react-slider');
17
19
  var html5Qrcode = require('html5-qrcode');
18
- var zod = require('zod');
19
20
 
20
21
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
22
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -39,6 +40,7 @@ function _interopNamespace(e) {
39
40
  }
40
41
 
41
42
  var React__namespace = /*#__PURE__*/_interopNamespace(React);
43
+ var DialogPrimitive__namespace = /*#__PURE__*/_interopNamespace(DialogPrimitive);
42
44
  var QRCode__default = /*#__PURE__*/_interopDefault(QRCode);
43
45
  var TabsPrimitive__namespace = /*#__PURE__*/_interopNamespace(TabsPrimitive);
44
46
  var SliderPrimitive__namespace = /*#__PURE__*/_interopNamespace(SliderPrimitive);
@@ -47,7 +49,7 @@ var SliderPrimitive__namespace = /*#__PURE__*/_interopNamespace(SliderPrimitive)
47
49
 
48
50
  // src/constants.ts
49
51
  var DEFAULT_SERVER_PORT = 4e3;
50
- var DEFAULT_CONTROLLER_PATH = "/joypad";
52
+ var CONTROLLER_PATH = "/controller";
51
53
  var INPUT_DEBOUNCE_MS = 200;
52
54
  var TOGGLE_DEBOUNCE_MS = 300;
53
55
  var SOCKET_CONFIG = {
@@ -61,26 +63,21 @@ var SOCKET_CONFIG = {
61
63
  PING_TIMEOUT: 5e3
62
64
  };
63
65
  var DEFAULT_MAX_PLAYERS = 8;
64
-
65
- // src/internal/input-manager.ts
66
66
  var InputManager = class {
67
67
  inputBuffer = /* @__PURE__ */ new Map();
68
68
  latchState = /* @__PURE__ */ new Map();
69
69
  config;
70
- roomId;
71
- constructor(config = {}, roomId) {
70
+ constructor(config = {}) {
72
71
  this.config = config;
73
- this.roomId = roomId;
74
72
  }
75
73
  /**
76
74
  * Handles incoming input events from the socket.
77
75
  * Should be called when 'server:input' event is received.
78
76
  */
79
77
  handleInput(payload) {
80
- if (this.roomId && payload.roomId !== this.roomId) {
81
- return;
82
- }
83
78
  this.inputBuffer.set(payload.controllerId, payload.input);
79
+ const input = payload?.input;
80
+ input && (input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01));
84
81
  }
85
82
  /**
86
83
  * Gets input for a specific controller.
@@ -119,12 +116,6 @@ var InputManager = class {
119
116
  this.inputBuffer.delete(controllerId);
120
117
  this.latchState.delete(controllerId);
121
118
  }
122
- /**
123
- * Updates the room ID filter.
124
- */
125
- setRoomId(roomId) {
126
- this.roomId = roomId;
127
- }
128
119
  /**
129
120
  * Internal method to apply latching logic.
130
121
  */
@@ -348,7 +339,6 @@ var AirJamProvider = ({
348
339
  children,
349
340
  serverUrl,
350
341
  apiKey,
351
- controllerPath = DEFAULT_CONTROLLER_PATH,
352
342
  maxPlayers = DEFAULT_MAX_PLAYERS,
353
343
  publicHost,
354
344
  input
@@ -357,11 +347,10 @@ var AirJamProvider = ({
357
347
  () => ({
358
348
  serverUrl: serverUrl ?? getEnvServerUrl(),
359
349
  apiKey: apiKey ?? getEnvApiKey(),
360
- controllerPath,
361
350
  maxPlayers,
362
351
  publicHost
363
352
  }),
364
- [serverUrl, apiKey, controllerPath, maxPlayers, publicHost]
353
+ [serverUrl, apiKey, maxPlayers, publicHost]
365
354
  );
366
355
  const inputManager = React.useMemo(() => {
367
356
  if (!input) {
@@ -478,6 +467,22 @@ var useVolumeStore = zustand.create((set, get) => ({
478
467
  return masterVolume * categoryVolume;
479
468
  }
480
469
  }));
470
+ var setupParentSettingsListener = () => {
471
+ if (typeof window === "undefined") return;
472
+ const isInIframe = window.parent !== window;
473
+ if (!isInIframe) return;
474
+ const handleMessage = (event) => {
475
+ if (event.source !== window.parent) return;
476
+ if (event.data?.type !== "AIRJAM_SETTINGS_SYNC") return;
477
+ const { masterVolume, musicVolume, sfxVolume } = event.data.payload;
478
+ const store = useVolumeStore.getState();
479
+ if (typeof masterVolume === "number") store.setMasterVolume(masterVolume);
480
+ if (typeof musicVolume === "number") store.setMusicVolume(musicVolume);
481
+ if (typeof sfxVolume === "number") store.setSfxVolume(sfxVolume);
482
+ };
483
+ window.addEventListener("message", handleMessage);
484
+ };
485
+ setupParentSettingsListener();
481
486
 
482
487
  // src/audio/audio-manager.ts
483
488
  function detectSoundCategory(config) {
@@ -546,7 +551,12 @@ var AudioManager = class {
546
551
  if (roomId) this.roomId = roomId;
547
552
  }
548
553
  /**
549
- * Initialize audio context (must be called on user interaction)
554
+ * Resume audio context if suspended. This is automatically called by play(),
555
+ * so you typically don't need to call this manually.
556
+ *
557
+ * Note: Due to browser autoplay policies, audio context starts suspended
558
+ * and can only be resumed in response to a user gesture. The useAudio hook
559
+ * handles this automatically, and play() also calls init() internally.
550
560
  */
551
561
  init() {
552
562
  if (howler.Howler.ctx && howler.Howler.ctx.state === "suspended") {
@@ -590,6 +600,7 @@ var AudioManager = class {
590
600
  sprite,
591
601
  pitch
592
602
  } = options || {};
603
+ this.init();
593
604
  if (remote) {
594
605
  this.playRemote(id, target, volume, loop);
595
606
  return null;
@@ -647,6 +658,7 @@ var AudioManager = class {
647
658
  * Play a sound at a specific 3D position
648
659
  */
649
660
  playSpatial(id, pos, sprite) {
661
+ this.init();
650
662
  const soundId = this.playLocal(id, void 0, void 0, sprite);
651
663
  if (soundId !== null) {
652
664
  const sound = this.sounds.get(id);
@@ -810,116 +822,6 @@ var useAudioManager = (manifest) => {
810
822
  return managerRef.current;
811
823
  };
812
824
  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
825
  var buttonVariants = classVarianceAuthority.cva(
924
826
  "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
827
  {
@@ -929,7 +831,7 @@ var buttonVariants = classVarianceAuthority.cva(
929
831
  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
832
  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
833
  secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
932
- ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
834
+ ghost: "text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
933
835
  link: "text-primary underline-offset-4 hover:underline"
934
836
  },
935
837
  size: {
@@ -964,667 +866,168 @@ function Button({
964
866
  }
965
867
  );
966
868
  }
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",
869
+ var Dialog = DialogPrimitive__namespace.Root;
870
+ var DialogPortal = DialogPrimitive__namespace.Portal;
871
+ var DialogOverlay = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
872
+ DialogPrimitive__namespace.Overlay,
873
+ {
874
+ ref,
875
+ className: cn(
876
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-99999 bg-black/80",
877
+ className
878
+ ),
879
+ ...props
880
+ }
881
+ ));
882
+ DialogOverlay.displayName = DialogPrimitive__namespace.Overlay.displayName;
883
+ var DialogContent = React__namespace.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(DialogPortal, { children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "dark", children: [
884
+ /* @__PURE__ */ jsxRuntime.jsx(DialogOverlay, {}),
885
+ /* @__PURE__ */ jsxRuntime.jsxs(
886
+ DialogPrimitive__namespace.Content,
983
887
  {
984
- "data-slot": "card-header",
888
+ ref,
985
889
  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",
890
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-99999 w-full translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border border-white p-6 shadow-lg duration-200",
987
891
  className
988
892
  ),
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
893
+ ...props,
894
+ children: [
895
+ children,
896
+ /* @__PURE__ */ jsxRuntime.jsxs(DialogPrimitive__namespace.Close, { className: "text-foreground ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none", children: [
897
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-4 w-4" }),
898
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Close" })
899
+ ] })
900
+ ]
1033
901
  }
1034
- );
1035
- }
1036
- function TabsList({
902
+ )
903
+ ] }) }));
904
+ DialogContent.displayName = DialogPrimitive__namespace.Content.displayName;
905
+ var DialogHeader = ({
1037
906
  className,
1038
907
  ...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
908
+ }) => /* @__PURE__ */ jsxRuntime.jsx(
909
+ "div",
910
+ {
911
+ className: cn(
912
+ "flex flex-col space-y-1.5 text-center sm:text-left",
913
+ className
914
+ ),
915
+ ...props
916
+ }
917
+ );
918
+ DialogHeader.displayName = "DialogHeader";
919
+ var DialogTitle = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
920
+ DialogPrimitive__namespace.Title,
921
+ {
922
+ ref,
923
+ className: cn(
924
+ "text-lg leading-none font-semibold tracking-tight",
925
+ className
926
+ ),
927
+ ...props
928
+ }
929
+ ));
930
+ DialogTitle.displayName = DialogPrimitive__namespace.Title.displayName;
931
+ var DialogDescription = React__namespace.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxRuntime.jsx(
932
+ DialogPrimitive__namespace.Description,
933
+ {
934
+ ref,
935
+ className: cn("text-muted-foreground text-sm", className),
936
+ ...props
937
+ }
938
+ ));
939
+ DialogDescription.displayName = DialogPrimitive__namespace.Description.displayName;
940
+ var DebugStateDialog = ({
941
+ isOpen,
942
+ onClose,
943
+ getState,
944
+ title = "Debug State",
945
+ updateInterval = 100
946
+ }) => {
947
+ const [state, setState] = React.useState(() => getState());
948
+ const [copied, setCopied] = React.useState(false);
949
+ React.useEffect(() => {
950
+ if (!isOpen) return;
951
+ const interval = setInterval(() => {
952
+ setState(getState());
953
+ }, updateInterval);
954
+ const timeoutId = setTimeout(() => {
955
+ setState(getState());
956
+ }, 0);
957
+ return () => {
958
+ clearInterval(interval);
959
+ clearTimeout(timeoutId);
960
+ };
961
+ }, [isOpen, getState, updateInterval]);
962
+ const jsonString = JSON.stringify(state, null, 2);
963
+ const handleCopy = async () => {
964
+ try {
965
+ await navigator.clipboard.writeText(jsonString);
966
+ setCopied(true);
967
+ setTimeout(() => setCopied(false), 2e3);
968
+ } catch (error) {
969
+ console.error("Failed to copy:", error);
1049
970
  }
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
971
+ };
972
+ return /* @__PURE__ */ jsxRuntime.jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: /* @__PURE__ */ jsxRuntime.jsxs(DialogContent, { className: "dark max-h-[90vh] max-w-2xl flex-col", children: [
973
+ /* @__PURE__ */ jsxRuntime.jsx(DialogHeader, { children: /* @__PURE__ */ jsxRuntime.jsx(DialogTitle, { className: "text-foreground", children: title }) }),
974
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex-1 overflow-auto pt-4", children: [
975
+ /* @__PURE__ */ jsxRuntime.jsx(
976
+ Button,
977
+ {
978
+ variant: "ghost",
979
+ size: "icon-sm",
980
+ onClick: handleCopy,
981
+ className: "text-muted-foreground hover:text-foreground absolute top-6 right-2 z-10",
982
+ "aria-label": "Copy state",
983
+ children: copied ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Copy, { className: "h-4 w-4" })
984
+ }
1063
985
  ),
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
- )
986
+ /* @__PURE__ */ jsxRuntime.jsx("pre", { className: "bg-muted text-muted-foreground overflow-auto rounded-lg border p-4 font-mono text-xs", children: jsonString })
1219
987
  ] })
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
- )}`;
988
+ ] }) });
1233
989
  };
1234
- var AirJamOverlay = ({
1235
- roomId,
1236
- joinUrl,
1237
- connectionStatus,
1238
- players,
1239
- lastError,
1240
- gameState,
1241
- onTogglePlayPause,
1242
- isChildMode = false
990
+ var AirJamDebug = ({
991
+ state,
992
+ title = "Debug State",
993
+ updateInterval = 100,
994
+ className
1243
995
  }) => {
1244
- const [qrUrl, setQrUrl] = React.useState(null);
1245
- const [qrError, setQrError] = React.useState(null);
996
+ const [isOpen, setIsOpen] = React.useState(false);
997
+ const [currentState, setCurrentState] = React.useState(state);
1246
998
  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;
999
+ if (!isOpen) return;
1000
+ const interval = setInterval(() => {
1001
+ setCurrentState(state);
1002
+ }, updateInterval);
1003
+ setCurrentState(state);
1004
+ return () => clearInterval(interval);
1005
+ }, [isOpen, state, updateInterval]);
1282
1006
  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,
1007
+ /* @__PURE__ */ jsxRuntime.jsx(
1008
+ Button,
1328
1009
  {
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();
1010
+ type: "button",
1011
+ variant: "ghost",
1012
+ size: "icon",
1013
+ onClick: () => setIsOpen(true),
1014
+ "aria-label": "Debug state",
1015
+ title,
1016
+ className: `text-white hover:bg-white/20 hover:text-white ${className || ""}`,
1017
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Bug, { className: "h-4 w-4" })
1595
1018
  }
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);
1019
+ ),
1020
+ /* @__PURE__ */ jsxRuntime.jsx(
1021
+ DebugStateDialog,
1022
+ {
1023
+ isOpen,
1024
+ onClose: () => setIsOpen(false),
1025
+ getState: () => currentState,
1026
+ title,
1027
+ updateInterval
1606
1028
  }
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
- }
1029
+ )
1030
+ ] });
1628
1031
  };
1629
1032
  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
1033
  var controllerInputSchema = zod.z.object({
@@ -1690,8 +1093,28 @@ var hostJoinAsChildSchema = zod.z.object({
1690
1093
  roomId: roomCodeSchema,
1691
1094
  joinToken: zod.z.string()
1692
1095
  });
1096
+ var hostCreateRoomSchema = zod.z.object({
1097
+ maxPlayers: zod.z.number().int().min(1).max(16).default(8),
1098
+ apiKey: zod.z.string().optional()
1099
+ });
1100
+ var hostReconnectSchema = zod.z.object({
1101
+ roomId: roomCodeSchema,
1102
+ apiKey: zod.z.string().optional()
1103
+ });
1693
1104
  var AIRJAM_PROXY_PREFIX = "AIRJAM_";
1694
1105
 
1106
+ // src/utils/mode.ts
1107
+ var detectRunMode = () => {
1108
+ if (typeof window === "undefined") {
1109
+ return "standalone";
1110
+ }
1111
+ try {
1112
+ return window.self !== window.top ? "platform" : "standalone";
1113
+ } catch {
1114
+ return "platform";
1115
+ }
1116
+ };
1117
+
1695
1118
  // src/utils/network-ip.ts
1696
1119
  var isVirtualNetwork = (ip) => {
1697
1120
  if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
@@ -1843,10 +1266,11 @@ var UrlBuilder = class {
1843
1266
  }
1844
1267
  /**
1845
1268
  * Build a controller URL with room code.
1269
+ * Controller is always at {baseUrl}/controller (standardized convention).
1846
1270
  * Automatically uses local IP when running on localhost.
1847
1271
  */
1848
1272
  async buildControllerUrl(roomId, options) {
1849
- const path = options?.path || DEFAULT_CONTROLLER_PATH;
1273
+ const path = CONTROLLER_PATH;
1850
1274
  if (options?.host) {
1851
1275
  const url2 = new URL(path, this.normalizeOrigin(options.host));
1852
1276
  url2.searchParams.set("room", roomId);
@@ -1905,1206 +1329,2007 @@ var UrlBuilder = class {
1905
1329
  }
1906
1330
  };
1907
1331
  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);
1332
+
1333
+ // src/hooks/use-air-jam-host.ts
1334
+ var useAirJamHost = (options = {}) => {
1335
+ const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
1336
+ const arcadeParams = React.useMemo(() => {
1337
+ if (typeof window === "undefined") return null;
1338
+ const params = new URLSearchParams(window.location.search);
1339
+ const room = params.get("aj_room");
1340
+ const token = params.get("aj_token");
1341
+ if (room && token) {
1342
+ return { room, token };
1343
+ }
1344
+ return null;
1345
+ }, []);
1346
+ const isChildMode = !!arcadeParams;
1347
+ const shouldConnect = true;
1348
+ const storeRoomId = zustand.useStore(store, (s) => s.roomId);
1349
+ const parsedRoomId = React.useMemo(() => {
1350
+ if (arcadeParams) {
1351
+ return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
1352
+ }
1353
+ if (storeRoomId) {
1354
+ return roomCodeSchema.parse(storeRoomId.toUpperCase());
1355
+ }
1356
+ if (typeof window !== "undefined") {
1357
+ const params = new URLSearchParams(window.location.search);
1358
+ const paramRoom = params.get("room");
1359
+ if (paramRoom) {
1360
+ const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
1361
+ if (result.success) return result.data;
1362
+ }
1363
+ }
1364
+ if (options.roomId) {
1365
+ return roomCodeSchema.parse(options.roomId.toUpperCase());
1366
+ }
1367
+ return null;
1368
+ }, [options.roomId, storeRoomId, arcadeParams]);
1934
1369
  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);
1370
+ const onPlayerJoinRef = React.useRef(options.onPlayerJoin);
1371
+ const onPlayerLeaveRef = React.useRef(options.onPlayerLeave);
1372
+ const onChildCloseRef = React.useRef(options.onChildClose);
1939
1373
  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);
1374
+ onPlayerJoinRef.current = options.onPlayerJoin;
1375
+ onPlayerLeaveRef.current = options.onPlayerLeave;
1376
+ onChildCloseRef.current = options.onChildClose;
1377
+ }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
1378
+ const connectionState = zustand.useStore(
1379
+ store,
1380
+ shallow.useShallow((state) => ({
1381
+ connectionStatus: state.connectionStatus,
1382
+ lastError: state.lastError,
1383
+ players: state.players,
1384
+ gameState: state.gameState,
1385
+ mode: state.mode,
1386
+ roomId: state.roomId
1387
+ }))
1388
+ );
1389
+ const socket = React.useMemo(
1390
+ () => getSocket("host") ,
1391
+ [shouldConnect, getSocket]
1392
+ );
1393
+ const [lastToggle, setLastToggle] = React.useState(0);
1394
+ const toggleGameState = React.useCallback(() => {
1395
+ const now = Date.now();
1396
+ if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
1397
+ return;
1948
1398
  }
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("");
1399
+ setLastToggle(now);
1400
+ if (!socket || !socket.connected) {
1401
+ return;
1402
+ }
1403
+ if (!parsedRoomId) return;
1404
+ const payload = controllerSystemSchema.safeParse({
1405
+ roomId: parsedRoomId,
1406
+ command: "toggle_pause"
1407
+ });
1408
+ if (payload.success) {
1409
+ socket.emit("host:system", payload.data);
1410
+ }
1411
+ }, [socket, parsedRoomId, lastToggle]);
1412
+ const sendState = React.useCallback(
1413
+ (state) => {
1414
+ if (!socket || !socket.connected || !parsedRoomId) {
1415
+ return false;
1964
1416
  }
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;
1417
+ const payload = controllerStateSchema.safeParse({
1418
+ roomId: parsedRoomId,
1419
+ state
1420
+ });
1421
+ if (!payload.success) {
1422
+ return false;
1423
+ }
1424
+ socket.emit("host:state", payload.data);
1425
+ return true;
1426
+ },
1427
+ [socket, parsedRoomId]
1428
+ );
1429
+ const sendSignal = React.useCallback(
1430
+ (type, payload, targetId) => {
1431
+ if (!socket || !socket.connected) {
1432
+ return;
1983
1433
  }
1434
+ const signal = {
1435
+ targetId,
1436
+ type,
1437
+ payload
1438
+ };
1439
+ socket.emit("host:signal", signal);
1440
+ },
1441
+ [socket]
1442
+ );
1443
+ const reconnect = React.useCallback(() => {
1444
+ disconnectSocket("host");
1445
+ if (socket) {
1446
+ socket.connect();
1984
1447
  }
1985
- }, [isOpen]);
1448
+ }, [socket, disconnectSocket]);
1986
1449
  React.useEffect(() => {
1987
- if (!isOpen) {
1450
+ if (!parsedRoomId) return;
1451
+ (async () => {
1452
+ const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
1453
+ host: config.publicHost
1454
+ });
1455
+ setJoinUrl(url);
1456
+ })();
1457
+ }, [parsedRoomId, config.publicHost, options.roomId]);
1458
+ const setRegisteredRoomId = zustand.useStore(store, (s) => s.setRegisteredRoomId);
1459
+ React.useEffect(() => {
1460
+ const storeState = store.getState();
1461
+ storeState.setMode(detectRunMode());
1462
+ storeState.setRole("host");
1463
+ if (parsedRoomId) {
1464
+ storeState.setRoomId(parsedRoomId);
1465
+ }
1466
+ storeState.setStatus("connecting");
1467
+ storeState.setError(void 0);
1468
+ if (!socket) {
1469
+ storeState.setStatus("idle");
1988
1470
  return;
1989
1471
  }
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");
1472
+ const registerHost = async () => {
1473
+ const storeState2 = store.getState();
1474
+ const currentRegisteredRoomId2 = store.getState().registeredRoomId;
1475
+ if (currentRegisteredRoomId2 && socket.connected) {
1476
+ return;
1477
+ }
1478
+ if (arcadeParams) {
1479
+ const childRoomId = roomCodeSchema.parse(
1480
+ arcadeParams.room.toUpperCase()
1481
+ );
1482
+ const payload = {
1483
+ roomId: childRoomId,
1484
+ joinToken: arcadeParams.token
1485
+ };
1486
+ socket.emit("host:joinAsChild", payload, (ack) => {
1487
+ if (!ack.ok) {
1488
+ storeState2.setError(ack.message ?? "Failed to join as child");
1489
+ storeState2.setStatus("disconnected");
1490
+ setRegisteredRoomId(null);
1491
+ return;
1492
+ }
1493
+ storeState2.setStatus("connected");
1494
+ storeState2.setRoomId(childRoomId);
1495
+ setRegisteredRoomId(childRoomId);
1496
+ });
1497
+ } else {
1498
+ const createNewRoom = () => {
1499
+ const payload = hostCreateRoomSchema.parse({
1500
+ maxPlayers: options.maxPlayers ?? config.maxPlayers,
1501
+ apiKey: options.apiKey ?? config.apiKey
1502
+ });
1503
+ socket.emit("host:createRoom", payload, (ack) => {
1504
+ if (!ack.ok) {
1505
+ storeState2.setError(ack.message ?? "Failed to create room");
1506
+ storeState2.setStatus("disconnected");
1507
+ setRegisteredRoomId(null);
1508
+ return;
1509
+ }
1510
+ if (ack.roomId) {
1511
+ storeState2.setStatus("connected");
1512
+ storeState2.setRoomId(ack.roomId);
1513
+ setRegisteredRoomId(ack.roomId);
1514
+ if (typeof window !== "undefined") {
1515
+ sessionStorage.setItem("airjam_room_id", ack.roomId);
1516
+ }
1517
+ } else {
1518
+ storeState2.setError("Server did not return room ID");
1519
+ storeState2.setStatus("disconnected");
1520
+ }
1521
+ });
1522
+ };
1523
+ if (typeof window !== "undefined") {
1524
+ const savedRoomId = sessionStorage.getItem("airjam_room_id");
1525
+ if (savedRoomId) {
1526
+ const reconnectPayload = hostReconnectSchema.parse({
1527
+ roomId: savedRoomId,
1528
+ apiKey: options.apiKey ?? config.apiKey
2016
1529
  });
2017
- cameraId = (envCamera || backCamera || devices[0])?.id || null;
1530
+ socket.emit("host:reconnect", reconnectPayload, (ack) => {
1531
+ if (ack.ok && ack.roomId) {
1532
+ storeState2.setStatus("connected");
1533
+ storeState2.setRoomId(ack.roomId);
1534
+ setRegisteredRoomId(ack.roomId);
1535
+ } else {
1536
+ if (typeof window !== "undefined") {
1537
+ sessionStorage.removeItem("airjam_room_id");
1538
+ }
1539
+ createNewRoom();
1540
+ }
1541
+ });
1542
+ } else {
1543
+ createNewRoom();
2018
1544
  }
2019
- } catch {
1545
+ } else {
1546
+ createNewRoom();
2020
1547
  }
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
1548
  }
2069
1549
  };
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
- }
1550
+ const handleConnect = () => {
1551
+ store.getState().setStatus("connected");
1552
+ registerHost();
1553
+ };
1554
+ const handleDisconnect = () => {
1555
+ store.getState().setStatus("disconnected");
1556
+ };
1557
+ const handleJoin = (payload) => {
1558
+ if (payload.player) {
1559
+ store.getState().upsertPlayer(payload.player);
1560
+ setTimeout(() => {
1561
+ onPlayerJoinRef.current?.(payload.player);
1562
+ }, 0);
2089
1563
  }
2090
- scannerRef.current = null;
2091
1564
  };
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 {
1565
+ const handleLeave = (payload) => {
1566
+ store.getState().removePlayer(payload.controllerId);
1567
+ onPlayerLeaveRef.current?.(payload.controllerId);
1568
+ };
1569
+ const handleInput = (payload) => {
1570
+ if (inputManager) {
1571
+ inputManager.handleInput(payload);
2126
1572
  }
2127
- document.body.removeChild(textArea);
1573
+ };
1574
+ const handleChildClose = () => {
1575
+ onChildCloseRef.current?.();
1576
+ };
1577
+ const handleState = (payload) => {
1578
+ if (!parsedRoomId || payload.roomId !== parsedRoomId) return;
1579
+ const storeState2 = store.getState();
1580
+ if (payload.state.gameState) {
1581
+ storeState2.setGameState(payload.state.gameState);
1582
+ }
1583
+ if (payload.state.message !== void 0) {
1584
+ storeState2.setStateMessage(payload.state.message);
1585
+ }
1586
+ };
1587
+ const handleError = (payload) => {
1588
+ store.getState().setError(payload.message);
1589
+ };
1590
+ socket.on("connect", handleConnect);
1591
+ socket.on("disconnect", handleDisconnect);
1592
+ socket.on("server:controllerJoined", handleJoin);
1593
+ socket.on("server:controllerLeft", handleLeave);
1594
+ socket.on("server:input", handleInput);
1595
+ socket.on("server:error", handleError);
1596
+ socket.on("server:closeChild", handleChildClose);
1597
+ socket.on("server:state", handleState);
1598
+ socket.connect();
1599
+ const currentRegisteredRoomId = store.getState().registeredRoomId;
1600
+ if (socket.connected && !currentRegisteredRoomId) {
1601
+ registerHost();
2128
1602
  }
1603
+ return () => {
1604
+ socket.off("connect", handleConnect);
1605
+ socket.off("disconnect", handleDisconnect);
1606
+ socket.off("server:controllerJoined", handleJoin);
1607
+ socket.off("server:controllerLeft", handleLeave);
1608
+ socket.off("server:input", handleInput);
1609
+ socket.off("server:error", handleError);
1610
+ socket.off("server:closeChild", handleChildClose);
1611
+ socket.off("server:state", handleState);
1612
+ };
1613
+ }, [
1614
+ config.maxPlayers,
1615
+ config.apiKey,
1616
+ options.maxPlayers,
1617
+ options.apiKey,
1618
+ arcadeParams,
1619
+ parsedRoomId,
1620
+ // Include parsedRoomId since it's used in handleState callback
1621
+ shouldConnect,
1622
+ socket,
1623
+ store,
1624
+ inputManager,
1625
+ setRegisteredRoomId
1626
+ ]);
1627
+ const returnSocket = socket ?? getSocket("host");
1628
+ const getInput = React.useCallback(
1629
+ (controllerId) => {
1630
+ if (!inputManager) {
1631
+ return void 0;
1632
+ }
1633
+ return inputManager.getInput(controllerId);
1634
+ },
1635
+ [inputManager]
1636
+ );
1637
+ return {
1638
+ roomId: parsedRoomId ?? "",
1639
+ // Return empty string as fallback if not yet available
1640
+ joinUrl,
1641
+ connectionStatus: connectionState.connectionStatus,
1642
+ players: connectionState.players,
1643
+ lastError: connectionState.lastError,
1644
+ mode: connectionState.mode,
1645
+ gameState: connectionState.gameState,
1646
+ toggleGameState,
1647
+ sendState,
1648
+ sendSignal,
1649
+ reconnect,
1650
+ socket: returnSocket,
1651
+ isChildMode,
1652
+ getInput
2129
1653
  };
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
1654
  };
2196
- var getPlayerAvatarUrl2 = (playerId) => {
1655
+ var getPlayerAvatarUrl = (playerId) => {
2197
1656
  return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
2198
1657
  playerId
2199
1658
  )}`;
2200
1659
  };
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;
1660
+ var hexToRgba = (hex, opacity) => {
1661
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
1662
+ if (!result) return `rgba(0, 0, 0, ${opacity})`;
1663
+ const r = parseInt(result[1], 16);
1664
+ const g = parseInt(result[2], 16);
1665
+ const b = parseInt(result[3], 16);
1666
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
2221
1667
  };
2222
- var ControllerShell = ({
2223
- roomId,
2224
- connectionStatus,
2225
- requiredOrientation = "landscape",
2226
- children,
2227
- gameState = "paused",
2228
- onTogglePlayPause,
2229
- onReconnect,
2230
- onRefresh,
2231
- customActions
1668
+ var PlayerAvatar = ({
1669
+ player,
1670
+ size = "md",
1671
+ className = ""
2232
1672
  }) => {
2233
- const isChildMode = React.useMemo(() => detectRunMode() === "platform", []);
2234
- const [isOrientationOk, setOrientationOk] = React.useState(
2235
- () => orientationMatches(requiredOrientation)
1673
+ const sizeClasses = {
1674
+ sm: "h-8 w-8 border-2",
1675
+ md: "h-12 w-12 border-4",
1676
+ lg: "h-16 w-16 border-4"
1677
+ };
1678
+ const shadowStyles = {
1679
+ sm: player.color ? `inset 0 0 4px rgba(0, 0, 0, 0.2), 0 0 8px ${hexToRgba(player.color, 0.4)}` : "inset 0 0 4px rgba(0, 0, 0, 0.2)",
1680
+ md: player.color ? `inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px ${hexToRgba(player.color, 0.6)}, 0 0 10px ${hexToRgba(player.color, 0.8)}` : "inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px hsl(var(--border) / 0.5)",
1681
+ lg: player.color ? `inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px ${hexToRgba(player.color, 0.6)}, 0 0 12px ${hexToRgba(player.color, 0.8)}` : "inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px hsl(var(--border) / 0.5)"
1682
+ };
1683
+ return /* @__PURE__ */ jsxRuntime.jsx(
1684
+ "img",
1685
+ {
1686
+ src: getPlayerAvatarUrl(player.id),
1687
+ alt: player.label,
1688
+ className: `bg-secondary/30 shrink-0 rounded-full shadow-lg ${sizeClasses[size]} ${className}`,
1689
+ style: {
1690
+ borderColor: player.color || "hsl(var(--border))",
1691
+ boxShadow: shadowStyles[size]
1692
+ }
1693
+ }
2236
1694
  );
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
- )
1695
+ };
1696
+ var alertVariants = classVarianceAuthority.cva(
1697
+ "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",
1698
+ {
1699
+ variants: {
1700
+ variant: {
1701
+ default: "bg-card text-card-foreground",
1702
+ destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
1703
+ }
1704
+ },
1705
+ defaultVariants: {
1706
+ variant: "default"
1707
+ }
1708
+ }
1709
+ );
1710
+ function Alert({
1711
+ className,
1712
+ variant,
1713
+ ...props
1714
+ }) {
1715
+ return /* @__PURE__ */ jsxRuntime.jsx(
1716
+ "div",
1717
+ {
1718
+ "data-slot": "alert",
1719
+ role: "alert",
1720
+ className: cn(alertVariants({ variant }), className),
1721
+ ...props
1722
+ }
2248
1723
  );
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;
1724
+ }
1725
+ function AlertDescription({
1726
+ className,
1727
+ ...props
1728
+ }) {
1729
+ return /* @__PURE__ */ jsxRuntime.jsx(
1730
+ "div",
1731
+ {
1732
+ "data-slot": "alert-description",
1733
+ className: cn(
1734
+ "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
1735
+ className
1736
+ ),
1737
+ ...props
2258
1738
  }
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";
1739
+ );
1740
+ }
1741
+ var badgeVariants = classVarianceAuthority.cva(
1742
+ "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",
1743
+ {
1744
+ variants: {
1745
+ variant: {
1746
+ default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
1747
+ secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
1748
+ 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",
1749
+ outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
1750
+ }
1751
+ },
1752
+ defaultVariants: {
1753
+ variant: "default"
2276
1754
  }
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
1755
  }
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 };
1756
+ );
1757
+ function Badge({
1758
+ className,
1759
+ variant,
1760
+ asChild = false,
1761
+ ...props
1762
+ }) {
1763
+ const Comp = asChild ? reactSlot.Slot : "span";
1764
+ return /* @__PURE__ */ jsxRuntime.jsx(
1765
+ Comp,
1766
+ {
1767
+ "data-slot": "badge",
1768
+ className: cn(badgeVariants({ variant }), className),
1769
+ ...props
2593
1770
  }
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;
1771
+ );
1772
+ }
1773
+ function Card({ className, ...props }) {
1774
+ return /* @__PURE__ */ jsxRuntime.jsx(
1775
+ "div",
1776
+ {
1777
+ "data-slot": "card",
1778
+ className: cn(
1779
+ "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
1780
+ className
1781
+ ),
1782
+ ...props
2603
1783
  }
2604
- }, [options.roomId, subControllerParams]);
2605
- const controllerId = React.useMemo(() => {
2606
- if (subControllerParams?.controllerId) {
2607
- return subControllerParams.controllerId;
1784
+ );
1785
+ }
1786
+ function CardTitle({ className, ...props }) {
1787
+ return /* @__PURE__ */ jsxRuntime.jsx(
1788
+ "div",
1789
+ {
1790
+ "data-slot": "card-title",
1791
+ className: cn("leading-none font-semibold", className),
1792
+ ...props
2608
1793
  }
2609
- if (options.controllerId) {
2610
- return options.controllerId;
1794
+ );
1795
+ }
1796
+ function CardDescription({ className, ...props }) {
1797
+ return /* @__PURE__ */ jsxRuntime.jsx(
1798
+ "div",
1799
+ {
1800
+ "data-slot": "card-description",
1801
+ className: cn("text-muted-foreground text-sm", className),
1802
+ ...props
2611
1803
  }
2612
- if (typeof window !== "undefined") {
2613
- const params = new URLSearchParams(window.location.search);
2614
- const urlControllerId = params.get("controllerId");
2615
- if (urlControllerId) return urlControllerId;
1804
+ );
1805
+ }
1806
+ function CardContent({ className, ...props }) {
1807
+ return /* @__PURE__ */ jsxRuntime.jsx(
1808
+ "div",
1809
+ {
1810
+ "data-slot": "card-content",
1811
+ className: cn("px-6", className),
1812
+ ...props
2616
1813
  }
2617
- return generateControllerId();
2618
- }, [options.controllerId, subControllerParams]);
2619
- const onStateRef = React.useRef(
2620
- options.onState
2621
1814
  );
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
- }))
1815
+ }
1816
+ function Tabs({
1817
+ className,
1818
+ ...props
1819
+ }) {
1820
+ return /* @__PURE__ */ jsxRuntime.jsx(
1821
+ TabsPrimitive__namespace.Root,
1822
+ {
1823
+ "data-slot": "tabs",
1824
+ className: cn("flex flex-col gap-2", className),
1825
+ ...props
1826
+ }
2635
1827
  );
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";
1828
+ }
1829
+ function TabsList({
1830
+ className,
1831
+ ...props
1832
+ }) {
1833
+ return /* @__PURE__ */ jsxRuntime.jsx(
1834
+ TabsPrimitive__namespace.List,
1835
+ {
1836
+ "data-slot": "tabs-list",
1837
+ className: cn(
1838
+ "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1839
+ className
1840
+ ),
1841
+ ...props
2653
1842
  }
2654
- return false;
2655
- }, [options.forceConnect, subControllerParams]);
2656
- const canConnect = React.useMemo(
2657
- () => !isChildMode || shouldConnect,
2658
- [isChildMode, shouldConnect]
2659
1843
  );
2660
- const socket = React.useMemo(
2661
- () => canConnect && parsedRoomId ? getSocket("controller") : null,
2662
- [canConnect, parsedRoomId, getSocket]
1844
+ }
1845
+ function TabsTrigger({
1846
+ className,
1847
+ ...props
1848
+ }) {
1849
+ return /* @__PURE__ */ jsxRuntime.jsx(
1850
+ TabsPrimitive__namespace.Trigger,
1851
+ {
1852
+ "data-slot": "tabs-trigger",
1853
+ className: cn(
1854
+ "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",
1855
+ className
1856
+ ),
1857
+ ...props
1858
+ }
2663
1859
  );
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
- };
1860
+ }
1861
+ function TabsContent({
1862
+ className,
1863
+ ...props
1864
+ }) {
1865
+ return /* @__PURE__ */ jsxRuntime.jsx(
1866
+ TabsPrimitive__namespace.Content,
1867
+ {
1868
+ "data-slot": "tabs-content",
1869
+ className: cn("flex-1 outline-none", className),
1870
+ ...props
2726
1871
  }
2727
- if (!parsedRoomId || !socket || !controllerId) {
2728
- storeState.setStatus("idle");
2729
- return;
1872
+ );
1873
+ }
1874
+ function Slider({
1875
+ className,
1876
+ defaultValue,
1877
+ value,
1878
+ min = 0,
1879
+ max = 100,
1880
+ ...props
1881
+ }) {
1882
+ const _values = React__namespace.useMemo(
1883
+ () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1884
+ [value, defaultValue, min, max]
1885
+ );
1886
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1887
+ SliderPrimitive__namespace.Root,
1888
+ {
1889
+ "data-slot": "slider",
1890
+ defaultValue,
1891
+ value,
1892
+ min,
1893
+ max,
1894
+ className: cn(
1895
+ "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",
1896
+ className
1897
+ ),
1898
+ ...props,
1899
+ children: [
1900
+ /* @__PURE__ */ jsxRuntime.jsx(
1901
+ SliderPrimitive__namespace.Track,
1902
+ {
1903
+ "data-slot": "slider-track",
1904
+ className: cn(
1905
+ "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"
1906
+ ),
1907
+ children: /* @__PURE__ */ jsxRuntime.jsx(
1908
+ SliderPrimitive__namespace.Range,
1909
+ {
1910
+ "data-slot": "slider-range",
1911
+ className: cn(
1912
+ "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
1913
+ )
1914
+ }
1915
+ )
1916
+ }
1917
+ ),
1918
+ Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsxRuntime.jsx(
1919
+ SliderPrimitive__namespace.Thumb,
1920
+ {
1921
+ "data-slot": "slider-thumb",
1922
+ 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"
1923
+ },
1924
+ index
1925
+ ))
1926
+ ]
2730
1927
  }
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;
1928
+ );
1929
+ }
1930
+ function VolumeControls({ className, compact }) {
1931
+ const {
1932
+ masterVolume,
1933
+ musicVolume,
1934
+ sfxVolume,
1935
+ setMasterVolume,
1936
+ setMusicVolume,
1937
+ setSfxVolume
1938
+ } = useVolumeStore();
1939
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1940
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1941
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Volume2, { className: "text-muted-foreground h-4 w-4" }),
1942
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: "Volume" })
1943
+ ] }),
1944
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1945
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1946
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1947
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1948
+ Math.round(masterVolume * 100),
1949
+ "%"
1950
+ ] })
1951
+ ] }),
1952
+ /* @__PURE__ */ jsxRuntime.jsx(
1953
+ Slider,
1954
+ {
1955
+ value: [masterVolume * 100],
1956
+ onValueChange: (values) => setMasterVolume(values[0] / 100),
1957
+ min: 0,
1958
+ max: 100,
1959
+ step: 1,
1960
+ className: "w-full",
1961
+ "aria-label": "Master volume"
2748
1962
  }
2749
- if (ack.controllerId) {
2750
- storeState2.setControllerId(ack.controllerId);
1963
+ )
1964
+ ] }),
1965
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1966
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1967
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1968
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Music, { className: "text-muted-foreground h-3 w-3" }),
1969
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1970
+ ] }),
1971
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1972
+ Math.round(musicVolume * 100),
1973
+ "%"
1974
+ ] })
1975
+ ] }),
1976
+ /* @__PURE__ */ jsxRuntime.jsx(
1977
+ Slider,
1978
+ {
1979
+ value: [musicVolume * 100],
1980
+ onValueChange: (values) => setMusicVolume(values[0] / 100),
1981
+ min: 0,
1982
+ max: 100,
1983
+ step: 1,
1984
+ className: "w-full",
1985
+ "aria-label": "Music volume"
2751
1986
  }
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);
1987
+ )
1988
+ ] }),
1989
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1990
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
1991
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1992
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Headphones, { className: "text-muted-foreground h-3 w-3" }),
1993
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1994
+ ] }),
1995
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1996
+ Math.round(sfxVolume * 100),
1997
+ "%"
1998
+ ] })
1999
+ ] }),
2000
+ /* @__PURE__ */ jsxRuntime.jsx(
2001
+ Slider,
2002
+ {
2003
+ value: [sfxVolume * 100],
2004
+ onValueChange: (values) => setSfxVolume(values[0] / 100),
2005
+ min: 0,
2006
+ max: 100,
2007
+ step: 1,
2008
+ className: "w-full",
2009
+ "aria-label": "SFX volume"
2010
+ }
2011
+ )
2012
+ ] })
2013
+ ] });
2014
+ }
2015
+ var statusCopy = {
2016
+ idle: "Idle",
2017
+ connecting: "Waiting for server\u2026",
2018
+ connected: "Ready for controllers",
2019
+ disconnected: "Disconnected",
2020
+ reconnecting: "Reconnecting\u2026"
2021
+ };
2022
+ var AirJamOverlay = () => {
2023
+ const host = useAirJamHost();
2024
+ const {
2025
+ roomId,
2026
+ joinUrl,
2027
+ connectionStatus,
2028
+ players,
2029
+ lastError,
2030
+ gameState,
2031
+ toggleGameState,
2032
+ isChildMode
2033
+ } = host;
2034
+ const [qrUrl, setQrUrl] = React.useState(null);
2035
+ const [qrError, setQrError] = React.useState(null);
2036
+ const [copied, setCopied] = React.useState(false);
2037
+ const [copiedPlayerId, setCopiedPlayerId] = React.useState(null);
2038
+ React.useEffect(() => {
2039
+ if (isChildMode) return;
2040
+ let mounted = true;
2041
+ QRCode__default.default.toDataURL(joinUrl, {
2042
+ margin: 1,
2043
+ color: {
2044
+ dark: "#0f172a",
2045
+ light: "#ffffff"
2046
+ },
2047
+ width: 320
2048
+ }).then((value) => {
2049
+ if (mounted) {
2050
+ setQrUrl(value);
2051
+ setQrError(null);
2780
2052
  }
2781
- if (payload.state.message !== void 0) {
2782
- storeState2.setStateMessage(payload.state.message);
2053
+ }).catch((err) => {
2054
+ if (mounted) {
2055
+ setQrError(err.message);
2783
2056
  }
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();
2057
+ });
2806
2058
  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);
2059
+ mounted = false;
2813
2060
  };
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;
2061
+ }, [joinUrl, isChildMode]);
2062
+ const handleCopyUrl = async () => {
2063
+ if (!joinUrl) return;
2064
+ try {
2065
+ await navigator.clipboard.writeText(joinUrl);
2066
+ setCopied(true);
2067
+ setTimeout(() => setCopied(false), 2e3);
2068
+ } catch {
2069
+ const textArea = document.createElement("textarea");
2070
+ textArea.value = joinUrl;
2071
+ textArea.style.position = "fixed";
2072
+ textArea.style.opacity = "0";
2073
+ document.body.appendChild(textArea);
2074
+ textArea.select();
2075
+ try {
2076
+ document.execCommand("copy");
2077
+ setCopied(true);
2078
+ setTimeout(() => setCopied(false), 2e3);
2079
+ } catch {
2861
2080
  }
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);
2081
+ document.body.removeChild(textArea);
2082
+ }
2083
+ };
2084
+ const handleOpenInNewTab = () => {
2085
+ if (joinUrl) {
2086
+ window.open(joinUrl, "_blank", "noopener,noreferrer");
2087
+ }
2088
+ };
2089
+ const handleCopyPlayerId = async (playerId) => {
2090
+ try {
2091
+ await navigator.clipboard.writeText(playerId);
2092
+ console.log(`Copied player ID: ${playerId}`);
2093
+ setCopiedPlayerId(playerId);
2094
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
2095
+ } catch {
2096
+ const textArea = document.createElement("textarea");
2097
+ textArea.value = playerId;
2098
+ textArea.style.position = "fixed";
2099
+ textArea.style.opacity = "0";
2100
+ document.body.appendChild(textArea);
2101
+ textArea.select();
2102
+ try {
2103
+ document.execCommand("copy");
2104
+ console.log(`Copied player ID: ${playerId}`);
2105
+ setCopiedPlayerId(playerId);
2106
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
2107
+ } catch {
2879
2108
  }
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
2109
+ document.body.removeChild(textArea);
2110
+ }
2896
2111
  };
2112
+ const connectionVariant = React.useMemo(() => {
2113
+ switch (connectionStatus) {
2114
+ case "connected":
2115
+ return "default";
2116
+ case "connecting":
2117
+ case "reconnecting":
2118
+ return "secondary";
2119
+ default:
2120
+ return "destructive";
2121
+ }
2122
+ }, [connectionStatus]);
2123
+ if (isChildMode) return null;
2124
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "dark", children: [
2125
+ !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: [
2126
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2127
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs tracking-[0.18em] uppercase", children: "Room" }),
2128
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-foreground text-lg font-semibold", children: roomId })
2129
+ ] }) }),
2130
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2131
+ players.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center -space-x-2", children: [
2132
+ players.slice(0, 4).map((player) => /* @__PURE__ */ jsxRuntime.jsx(PlayerAvatar, { player, size: "sm" }, player.id)),
2133
+ 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: [
2134
+ "+",
2135
+ players.length - 4
2136
+ ] })
2137
+ ] }),
2138
+ /* @__PURE__ */ jsxRuntime.jsx(
2139
+ Button,
2140
+ {
2141
+ type: "button",
2142
+ variant: "ghost",
2143
+ size: "icon",
2144
+ onClick: toggleGameState,
2145
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2146
+ className: "h-8 w-8",
2147
+ children: gameState === "playing" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "h-4 w-4" })
2148
+ }
2149
+ )
2150
+ ] })
2151
+ ] }) }) }),
2152
+ 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 max-h-[85vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxRuntime.jsxs(
2153
+ Tabs,
2154
+ {
2155
+ defaultValue: isChildMode ? "settings" : "room-code",
2156
+ className: "flex h-full w-full flex-col gap-0",
2157
+ children: [
2158
+ /* @__PURE__ */ jsxRuntime.jsxs(TabsList, { className: "border-border grid w-full shrink-0 grid-cols-2 rounded-none border-b bg-transparent p-0", children: [
2159
+ !isChildMode && /* @__PURE__ */ jsxRuntime.jsxs(
2160
+ TabsTrigger,
2161
+ {
2162
+ value: "room-code",
2163
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2164
+ children: [
2165
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.QrCode, { className: "h-4 w-4" }),
2166
+ "Room Code"
2167
+ ]
2168
+ }
2169
+ ),
2170
+ isChildMode && /* @__PURE__ */ jsxRuntime.jsxs(
2171
+ TabsTrigger,
2172
+ {
2173
+ value: "info",
2174
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2175
+ children: [
2176
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.MonitorSmartphone, { className: "h-4 w-4" }),
2177
+ "Platform"
2178
+ ]
2179
+ }
2180
+ ),
2181
+ /* @__PURE__ */ jsxRuntime.jsxs(
2182
+ TabsTrigger,
2183
+ {
2184
+ value: "settings",
2185
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2186
+ children: [
2187
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Settings, { className: "h-4 w-4" }),
2188
+ "Settings"
2189
+ ]
2190
+ }
2191
+ )
2192
+ ] }),
2193
+ !isChildMode && /* @__PURE__ */ jsxRuntime.jsx(
2194
+ TabsContent,
2195
+ {
2196
+ value: "room-code",
2197
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2198
+ children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-1 gap-6 md:grid-cols-[auto_1fr]", children: [
2199
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-start gap-4", children: [
2200
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
2201
+ /* @__PURE__ */ jsxRuntime.jsx(CardTitle, { className: "text-3xl font-bold tracking-wider", children: roomId }),
2202
+ /* @__PURE__ */ jsxRuntime.jsx(
2203
+ Badge,
2204
+ {
2205
+ variant: connectionVariant,
2206
+ className: "w-fit",
2207
+ children: statusCopy[connectionStatus]
2208
+ }
2209
+ )
2210
+ ] }),
2211
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-border bg-card w-48 shrink-0 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsxRuntime.jsx(
2212
+ "img",
2213
+ {
2214
+ src: qrUrl,
2215
+ alt: `Join room ${roomId}`,
2216
+ className: "w-full rounded bg-white"
2217
+ }
2218
+ ) : /* @__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" }) })
2219
+ ] }),
2220
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-6", children: [
2221
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
2222
+ /* @__PURE__ */ jsxRuntime.jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
2223
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
2224
+ /* @__PURE__ */ jsxRuntime.jsx(
2225
+ "input",
2226
+ {
2227
+ type: "text",
2228
+ readOnly: true,
2229
+ value: joinUrl,
2230
+ className: "bg-background border-input text-foreground focus:ring-ring flex h-10 w-full rounded-md border px-3 py-2 font-mono text-xs focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
2231
+ }
2232
+ ),
2233
+ /* @__PURE__ */ jsxRuntime.jsx(
2234
+ Button,
2235
+ {
2236
+ type: "button",
2237
+ variant: "outline",
2238
+ size: "icon",
2239
+ onClick: handleCopyUrl,
2240
+ className: "h-10 shrink-0",
2241
+ "aria-label": "Copy join URL",
2242
+ children: copied ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Copy, { className: "h-4 w-4" })
2243
+ }
2244
+ ),
2245
+ /* @__PURE__ */ jsxRuntime.jsx(
2246
+ Button,
2247
+ {
2248
+ type: "button",
2249
+ variant: "outline",
2250
+ size: "icon",
2251
+ onClick: handleOpenInNewTab,
2252
+ className: "h-10 shrink-0",
2253
+ "aria-label": "Open join URL in new tab",
2254
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ExternalLink, { className: "h-4 w-4" })
2255
+ }
2256
+ )
2257
+ ] })
2258
+ ] }),
2259
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-3", children: players.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-white", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2260
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-foreground text-sm font-medium", children: [
2261
+ "Connected Players (",
2262
+ players.length,
2263
+ ")"
2264
+ ] }),
2265
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsxRuntime.jsx(
2266
+ "li",
2267
+ {
2268
+ className: "flex min-w-0 flex-col items-start gap-2",
2269
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
2270
+ /* @__PURE__ */ jsxRuntime.jsx(
2271
+ PlayerAvatar,
2272
+ {
2273
+ player,
2274
+ size: "md"
2275
+ }
2276
+ ),
2277
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: [
2278
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }),
2279
+ /* @__PURE__ */ jsxRuntime.jsx(
2280
+ "div",
2281
+ {
2282
+ onClick: () => handleCopyPlayerId(player.id),
2283
+ className: "text-muted-foreground m-0 inline min-w-0 cursor-pointer truncate border-0 font-mono text-xs transition-colors hover:text-white",
2284
+ title: "Click to copy player ID",
2285
+ children: copiedPlayerId === player.id ? "Copied!" : player.id.slice(0, 8)
2286
+ }
2287
+ )
2288
+ ] })
2289
+ ] })
2290
+ },
2291
+ player.id
2292
+ )) })
2293
+ ] }) }),
2294
+ lastError && /* @__PURE__ */ jsxRuntime.jsx(Alert, { variant: "destructive", className: "w-full", children: /* @__PURE__ */ jsxRuntime.jsx(AlertDescription, { children: lastError }) }),
2295
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-auto flex justify-end", children: /* @__PURE__ */ jsxRuntime.jsxs(
2296
+ Button,
2297
+ {
2298
+ type: "button",
2299
+ onClick: toggleGameState,
2300
+ size: "lg",
2301
+ children: [
2302
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "mr-2 h-5 w-5" }),
2303
+ "Play"
2304
+ ]
2305
+ }
2306
+ ) })
2307
+ ] })
2308
+ ] }) })
2309
+ }
2310
+ ),
2311
+ isChildMode && /* @__PURE__ */ jsxRuntime.jsx(
2312
+ TabsContent,
2313
+ {
2314
+ value: "info",
2315
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2316
+ children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
2317
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
2318
+ /* @__PURE__ */ jsxRuntime.jsx(CardTitle, { className: "text-2xl font-bold tracking-wider", children: "Connected to Platform" }),
2319
+ /* @__PURE__ */ jsxRuntime.jsx(CardDescription, { children: "This game is running inside the Air Jam Platform." })
2320
+ ] }),
2321
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
2322
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-foreground text-sm font-medium", children: [
2323
+ "Connected Players (",
2324
+ players.length,
2325
+ ")"
2326
+ ] }),
2327
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsxRuntime.jsx(
2328
+ "li",
2329
+ {
2330
+ className: "flex min-w-0 flex-col items-start gap-2",
2331
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
2332
+ /* @__PURE__ */ jsxRuntime.jsx(PlayerAvatar, { player, size: "md" }),
2333
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }) })
2334
+ ] })
2335
+ },
2336
+ player.id
2337
+ )) })
2338
+ ] }),
2339
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxRuntime.jsxs(
2340
+ Button,
2341
+ {
2342
+ type: "button",
2343
+ onClick: toggleGameState,
2344
+ size: "lg",
2345
+ children: [
2346
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "mr-2 h-5 w-5" }),
2347
+ "Resume Game"
2348
+ ]
2349
+ }
2350
+ ) })
2351
+ ] }) })
2352
+ }
2353
+ ),
2354
+ /* @__PURE__ */ jsxRuntime.jsx(
2355
+ TabsContent,
2356
+ {
2357
+ value: "settings",
2358
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2359
+ children: /* @__PURE__ */ jsxRuntime.jsx(CardContent, { className: "pt-6 pb-6", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
2360
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntime.jsx(VolumeControls, {}) }),
2361
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 border-t pt-4", children: [
2362
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: "Connection" }),
2363
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
2364
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
2365
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Status" }),
2366
+ /* @__PURE__ */ jsxRuntime.jsx(Badge, { variant: connectionVariant, children: statusCopy[connectionStatus] })
2367
+ ] }),
2368
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
2369
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Room ID" }),
2370
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-mono text-sm", children: roomId })
2371
+ ] }),
2372
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
2373
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Players" }),
2374
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: players.length })
2375
+ ] })
2376
+ ] })
2377
+ ] }),
2378
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 border-t pt-4", children: [
2379
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: "Display" }),
2380
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
2381
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-sm", children: "Game State" }),
2382
+ /* @__PURE__ */ jsxRuntime.jsx(Badge, { variant: "outline", className: "capitalize", children: gameState })
2383
+ ] }) })
2384
+ ] })
2385
+ ] }) })
2386
+ }
2387
+ )
2388
+ ]
2389
+ }
2390
+ ) }) }) })
2391
+ ] });
2392
+ };
2393
+ var useFullscreen = () => {
2394
+ const [isFullscreen, setIsFullscreen] = React.useState(false);
2395
+ React.useEffect(() => {
2396
+ const handleFullscreenChange = () => {
2397
+ const doc = document;
2398
+ setIsFullscreen(
2399
+ !!(document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement)
2400
+ );
2401
+ };
2402
+ document.addEventListener("fullscreenchange", handleFullscreenChange);
2403
+ document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
2404
+ document.addEventListener("mozfullscreenchange", handleFullscreenChange);
2405
+ document.addEventListener("msfullscreenchange", handleFullscreenChange);
2406
+ return () => {
2407
+ document.removeEventListener("fullscreenchange", handleFullscreenChange);
2408
+ document.removeEventListener(
2409
+ "webkitfullscreenchange",
2410
+ handleFullscreenChange
2411
+ );
2412
+ document.removeEventListener(
2413
+ "mozfullscreenchange",
2414
+ handleFullscreenChange
2415
+ );
2416
+ document.removeEventListener(
2417
+ "msfullscreenchange",
2418
+ handleFullscreenChange
2419
+ );
2420
+ };
2421
+ }, []);
2422
+ const exitFullscreen = React.useCallback(async () => {
2423
+ try {
2424
+ const doc = document;
2425
+ if (document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement) {
2426
+ if (document.exitFullscreen) {
2427
+ await document.exitFullscreen();
2428
+ } else if (doc.webkitExitFullscreen) {
2429
+ await doc.webkitExitFullscreen();
2430
+ } else if (doc.mozCancelFullScreen) {
2431
+ await doc.mozCancelFullScreen();
2432
+ } else if (doc.msExitFullscreen) {
2433
+ await doc.msExitFullscreen();
2434
+ }
2435
+ }
2436
+ } catch (error) {
2437
+ console.error("Error exiting fullscreen:", error);
2438
+ }
2439
+ }, []);
2440
+ const enterFullscreen = React.useCallback(async (element) => {
2441
+ try {
2442
+ const elem = element || document.documentElement;
2443
+ if (elem.requestFullscreen) {
2444
+ await elem.requestFullscreen();
2445
+ } else if (elem.webkitRequestFullscreen) {
2446
+ await elem.webkitRequestFullscreen();
2447
+ } else if (elem.mozRequestFullScreen) {
2448
+ await elem.mozRequestFullScreen();
2449
+ } else if (elem.msRequestFullscreen) {
2450
+ await elem.msRequestFullscreen();
2451
+ }
2452
+ } catch (error) {
2453
+ console.error("Error entering fullscreen:", error);
2454
+ }
2455
+ }, []);
2456
+ const toggleFullscreen = React.useCallback(
2457
+ async (element) => {
2458
+ if (isFullscreen) {
2459
+ await exitFullscreen();
2460
+ } else {
2461
+ await enterFullscreen(element);
2462
+ }
2463
+ },
2464
+ [isFullscreen, exitFullscreen, enterFullscreen]
2465
+ );
2466
+ return {
2467
+ isFullscreen,
2468
+ enterFullscreen,
2469
+ exitFullscreen,
2470
+ toggleFullscreen
2471
+ };
2472
+ };
2473
+ var extractRoomCode = (text) => {
2474
+ try {
2475
+ const url = new URL(text);
2476
+ const roomParam = url.searchParams.get("room");
2477
+ if (roomParam) {
2478
+ const parsed2 = roomCodeSchema.safeParse(roomParam.toUpperCase());
2479
+ if (parsed2.success) {
2480
+ return parsed2.data;
2481
+ }
2482
+ }
2483
+ } catch {
2484
+ }
2485
+ const parsed = roomCodeSchema.safeParse(text.trim().toUpperCase());
2486
+ if (parsed.success) {
2487
+ return parsed.data;
2488
+ }
2489
+ return null;
2490
+ };
2491
+ var QRScannerDialog = ({
2492
+ isOpen,
2493
+ onClose,
2494
+ onScan,
2495
+ currentRoomId
2496
+ }) => {
2497
+ const [code, setCode] = React.useState("");
2498
+ const [isCameraAvailable, setIsCameraAvailable] = React.useState(false);
2499
+ const [joinUrl, setJoinUrl] = React.useState("");
2500
+ const [copied, setCopied] = React.useState(false);
2501
+ const scannerRef = React.useRef(null);
2502
+ const inputRef = React.useRef(null);
2503
+ const prevIsOpenRef = React.useRef(false);
2504
+ React.useEffect(() => {
2505
+ if (isOpen && !prevIsOpenRef.current) {
2506
+ const initialCode = currentRoomId || "";
2507
+ setTimeout(() => {
2508
+ setIsCameraAvailable(false);
2509
+ setCode(initialCode);
2510
+ inputRef.current?.focus();
2511
+ inputRef.current?.select();
2512
+ }, 0);
2513
+ }
2514
+ prevIsOpenRef.current = isOpen;
2515
+ }, [isOpen, currentRoomId]);
2516
+ React.useEffect(() => {
2517
+ const buildUrl = async () => {
2518
+ const trimmed = code.trim().toUpperCase();
2519
+ const parsed = roomCodeSchema.safeParse(trimmed);
2520
+ if (parsed.success) {
2521
+ try {
2522
+ const url = await urlBuilder.buildControllerUrl(parsed.data);
2523
+ setJoinUrl(url);
2524
+ } catch {
2525
+ setJoinUrl("");
2526
+ }
2527
+ } else {
2528
+ setJoinUrl("");
2529
+ }
2530
+ };
2531
+ buildUrl();
2532
+ }, [code]);
2533
+ React.useEffect(() => {
2534
+ if (!isOpen) {
2535
+ setTimeout(() => {
2536
+ setIsCameraAvailable(false);
2537
+ }, 0);
2538
+ if (scannerRef.current) {
2539
+ const scanner = scannerRef.current;
2540
+ scanner.stop().catch(() => {
2541
+ }).finally(() => {
2542
+ try {
2543
+ scanner.clear();
2544
+ } catch {
2545
+ }
2546
+ });
2547
+ scannerRef.current = null;
2548
+ }
2549
+ }
2550
+ }, [isOpen]);
2551
+ React.useEffect(() => {
2552
+ if (!isOpen) {
2553
+ return;
2554
+ }
2555
+ const containerId = "qr-reader";
2556
+ let scanner = null;
2557
+ let scannerRunning = false;
2558
+ let mounted = true;
2559
+ const startScanning = async () => {
2560
+ try {
2561
+ const container = document.getElementById(containerId);
2562
+ if (!container) {
2563
+ return;
2564
+ }
2565
+ const rect = container.getBoundingClientRect();
2566
+ if (rect.width === 0 || rect.height === 0) {
2567
+ return;
2568
+ }
2569
+ scanner = new html5Qrcode.Html5Qrcode(containerId);
2570
+ scannerRef.current = scanner;
2571
+ let cameraId = null;
2572
+ try {
2573
+ const devices = await html5Qrcode.Html5Qrcode.getCameras();
2574
+ if (devices && devices.length > 0) {
2575
+ const backCamera = devices.find(
2576
+ (d) => d.label.toLowerCase().includes("back") || d.label.toLowerCase().includes("rear")
2577
+ );
2578
+ const envCamera = devices.find((d) => {
2579
+ const label = d.label.toLowerCase();
2580
+ return label.includes("environment") || label.includes("facing back");
2581
+ });
2582
+ cameraId = (envCamera || backCamera || devices[0])?.id || null;
2583
+ }
2584
+ } catch {
2585
+ }
2586
+ const config = cameraId ? { deviceId: { exact: cameraId } } : { facingMode: "environment" };
2587
+ await scanner.start(
2588
+ config,
2589
+ {
2590
+ fps: 10,
2591
+ qrbox: (viewfinderWidth, viewfinderHeight) => {
2592
+ const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
2593
+ const qrboxSize = Math.min(250, minEdge * 0.8);
2594
+ return {
2595
+ width: qrboxSize,
2596
+ height: qrboxSize
2597
+ };
2598
+ },
2599
+ aspectRatio: 1
2600
+ },
2601
+ (decodedText) => {
2602
+ if (!mounted) return;
2603
+ const roomCode = extractRoomCode(decodedText);
2604
+ if (roomCode) {
2605
+ setCode(roomCode);
2606
+ scannerRunning = false;
2607
+ scanner?.stop().catch(() => {
2608
+ }).finally(() => {
2609
+ if (mounted) {
2610
+ setIsCameraAvailable(false);
2611
+ }
2612
+ });
2613
+ }
2614
+ },
2615
+ () => {
2616
+ }
2617
+ );
2618
+ scannerRunning = true;
2619
+ if (mounted) {
2620
+ setIsCameraAvailable(true);
2621
+ }
2622
+ } catch {
2623
+ if (mounted) {
2624
+ setIsCameraAvailable(false);
2625
+ }
2626
+ if (scanner) {
2627
+ try {
2628
+ scanner.clear();
2629
+ } catch {
2630
+ }
2631
+ }
2632
+ scannerRef.current = null;
2633
+ }
2634
+ };
2635
+ const timeoutId = setTimeout(() => {
2636
+ startScanning();
2637
+ }, 200);
2638
+ return () => {
2639
+ mounted = false;
2640
+ clearTimeout(timeoutId);
2641
+ if (scanner && scannerRunning) {
2642
+ scanner.stop().catch(() => {
2643
+ }).finally(() => {
2644
+ try {
2645
+ scanner?.clear();
2646
+ } catch {
2647
+ }
2648
+ });
2649
+ } else if (scanner) {
2650
+ try {
2651
+ scanner.clear();
2652
+ } catch {
2653
+ }
2654
+ }
2655
+ scannerRef.current = null;
2656
+ };
2657
+ }, [isOpen]);
2658
+ const handleSubmit = () => {
2659
+ const trimmed = code.trim().toUpperCase();
2660
+ const parsed = roomCodeSchema.safeParse(trimmed);
2661
+ if (parsed.success) {
2662
+ onScan(parsed.data);
2663
+ onClose();
2664
+ }
2665
+ };
2666
+ const handleInputFocus = (e) => {
2667
+ e.target.select();
2668
+ };
2669
+ const handleInputChange = (e) => {
2670
+ setCode(e.target.value.toUpperCase());
2671
+ setCopied(false);
2672
+ };
2673
+ const handleCopyUrl = async () => {
2674
+ if (!joinUrl) return;
2675
+ try {
2676
+ await navigator.clipboard.writeText(joinUrl);
2677
+ setCopied(true);
2678
+ setTimeout(() => setCopied(false), 2e3);
2679
+ } catch {
2680
+ const textArea = document.createElement("textarea");
2681
+ textArea.value = joinUrl;
2682
+ textArea.style.position = "fixed";
2683
+ textArea.style.opacity = "0";
2684
+ document.body.appendChild(textArea);
2685
+ textArea.select();
2686
+ try {
2687
+ document.execCommand("copy");
2688
+ setCopied(true);
2689
+ setTimeout(() => setCopied(false), 2e3);
2690
+ } catch {
2691
+ }
2692
+ document.body.removeChild(textArea);
2693
+ }
2694
+ };
2695
+ if (!isOpen) {
2696
+ return null;
2697
+ }
2698
+ const isValid = code.trim().length > 0;
2699
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background fixed inset-0 z-50 flex flex-col items-center justify-center", children: [
2700
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-1 flex-col items-center justify-center", children: [
2701
+ isCameraAvailable && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "relative flex aspect-square w-full items-center justify-center overflow-hidden p-6", children: /* @__PURE__ */ jsxRuntime.jsx(
2702
+ "div",
2703
+ {
2704
+ id: "qr-reader",
2705
+ className: "h-full w-full overflow-hidden rounded-lg bg-black"
2706
+ }
2707
+ ) }),
2708
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full max-w-md px-6", children: /* @__PURE__ */ jsxRuntime.jsx(
2709
+ "input",
2710
+ {
2711
+ ref: inputRef,
2712
+ type: "text",
2713
+ value: code,
2714
+ onChange: handleInputChange,
2715
+ onFocus: handleInputFocus,
2716
+ onKeyDown: (e) => {
2717
+ if (e.key === "Enter" && isValid) {
2718
+ handleSubmit();
2719
+ }
2720
+ },
2721
+ placeholder: "Enter room code",
2722
+ 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",
2723
+ autoComplete: "off",
2724
+ autoCapitalize: "characters"
2725
+ }
2726
+ ) }),
2727
+ joinUrl && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-4 w-full max-w-md px-6 pb-2", children: /* @__PURE__ */ jsxRuntime.jsx(
2728
+ "button",
2729
+ {
2730
+ type: "button",
2731
+ onClick: handleCopyUrl,
2732
+ 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",
2733
+ children: copied ? "\u2713 Copied!" : joinUrl
2734
+ }
2735
+ ) })
2736
+ ] }),
2737
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex w-full max-w-md gap-4 px-6 pb-6", children: [
2738
+ /* @__PURE__ */ jsxRuntime.jsx(
2739
+ Button,
2740
+ {
2741
+ type: "button",
2742
+ variant: "outline",
2743
+ onClick: onClose,
2744
+ className: "flex-1 py-6",
2745
+ children: "Cancel"
2746
+ }
2747
+ ),
2748
+ /* @__PURE__ */ jsxRuntime.jsx(
2749
+ Button,
2750
+ {
2751
+ type: "button",
2752
+ onClick: handleSubmit,
2753
+ disabled: !isValid,
2754
+ className: "flex-1 py-6",
2755
+ children: "Connect"
2756
+ }
2757
+ )
2758
+ ] })
2759
+ ] });
2760
+ };
2761
+ var describeStatus = (status) => {
2762
+ switch (status) {
2763
+ case "connected":
2764
+ return "Connected to host";
2765
+ case "connecting":
2766
+ return "Connecting\u2026";
2767
+ case "reconnecting":
2768
+ return "Trying to reconnect\u2026";
2769
+ case "disconnected":
2770
+ return "Disconnected";
2771
+ case "idle":
2772
+ default:
2773
+ return "Idle";
2774
+ }
2775
+ };
2776
+ var orientationMatches = (required) => {
2777
+ if (!required) return true;
2778
+ if (typeof window === "undefined" || !window.matchMedia) return true;
2779
+ const matcher = window.matchMedia(`(orientation: ${required})`);
2780
+ return matcher.matches;
2781
+ };
2782
+ var ControllerShell = ({
2783
+ roomId,
2784
+ connectionStatus,
2785
+ forceOrientation,
2786
+ children,
2787
+ gameState = "paused",
2788
+ onTogglePlayPause,
2789
+ onReconnect,
2790
+ onRefresh,
2791
+ customActions
2792
+ }) => {
2793
+ const isChildMode = React.useMemo(() => detectRunMode() === "platform", []);
2794
+ const [isOrientationOk, setOrientationOk] = React.useState(
2795
+ () => orientationMatches(forceOrientation)
2796
+ );
2797
+ const [isScannerOpen, setIsScannerOpen] = React.useState(false);
2798
+ const { isFullscreen, toggleFullscreen } = useFullscreen();
2799
+ const { store } = useAirJamContext();
2800
+ const { controllerId, players } = zustand.useStore(
2801
+ store,
2802
+ shallow.useShallow(
2803
+ (state) => ({
2804
+ controllerId: state.controllerId,
2805
+ players: state.players
2806
+ })
2807
+ )
2808
+ );
2809
+ const currentPlayer = React.useMemo(() => {
2810
+ if (!controllerId) return null;
2811
+ const found = players.find((p) => p.id === controllerId);
2812
+ if (!found && connectionStatus === "connected" && players.length > 0) ;
2813
+ return found || null;
2814
+ }, [controllerId, players, connectionStatus]);
2815
+ React.useEffect(() => {
2816
+ if (!forceOrientation) {
2817
+ setOrientationOk(true);
2818
+ return;
2819
+ }
2820
+ const media = window.matchMedia(`(orientation: ${forceOrientation})`);
2821
+ const handleChange = () => setOrientationOk(media.matches);
2822
+ handleChange();
2823
+ media.addEventListener("change", handleChange);
2824
+ return () => media.removeEventListener("change", handleChange);
2825
+ }, [forceOrientation]);
2826
+ const orientationOk = !forceOrientation ? true : isOrientationOk;
2827
+ const statusDotColor = React.useMemo(() => {
2828
+ switch (connectionStatus) {
2829
+ case "connected":
2830
+ return "bg-green-500";
2831
+ case "connecting":
2832
+ case "reconnecting":
2833
+ return "bg-yellow-500";
2834
+ case "disconnected":
2835
+ default:
2836
+ return "bg-red-500";
2837
+ }
2838
+ }, [connectionStatus]);
2839
+ if (isChildMode) {
2840
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "dark", children: /* @__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: [
2841
+ !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: [
2842
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2843
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2844
+ "This game is best experienced in ",
2845
+ forceOrientation,
2846
+ " ",
2847
+ "orientation."
2848
+ ] })
2849
+ ] }),
2850
+ /* @__PURE__ */ jsxRuntime.jsx(
2851
+ "div",
2852
+ {
2853
+ className: cn(
2854
+ "h-full w-full select-none",
2855
+ !orientationOk && "pointer-events-none opacity-30"
2856
+ ),
2857
+ children
2858
+ }
2859
+ )
2860
+ ] }) }) });
2861
+ }
2862
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "dark", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2863
+ /* @__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: [
2864
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2865
+ typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxRuntime.jsxs(
2866
+ "div",
2867
+ {
2868
+ className: "relative",
2869
+ title: describeStatus(connectionStatus),
2870
+ children: [
2871
+ currentPlayer ? /* @__PURE__ */ jsxRuntime.jsx(PlayerAvatar, { player: currentPlayer, size: "sm" }) : controllerId ? /* @__PURE__ */ jsxRuntime.jsx(
2872
+ PlayerAvatar,
2873
+ {
2874
+ player: {
2875
+ id: controllerId,
2876
+ label: "Player"
2877
+ },
2878
+ size: "sm"
2879
+ }
2880
+ ) : null,
2881
+ /* @__PURE__ */ jsxRuntime.jsx(
2882
+ "span",
2883
+ {
2884
+ className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2885
+ "aria-hidden": "true"
2886
+ }
2887
+ ),
2888
+ /* @__PURE__ */ jsxRuntime.jsx(
2889
+ "span",
2890
+ {
2891
+ className: cn(
2892
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2893
+ statusDotColor,
2894
+ connectionStatus === "connected" && "animate-pulse"
2895
+ ),
2896
+ "aria-label": describeStatus(connectionStatus)
2897
+ }
2898
+ )
2899
+ ]
2900
+ }
2901
+ ),
2902
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2903
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2904
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2905
+ ] })
2906
+ ] }),
2907
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2908
+ customActions,
2909
+ onRefresh && roomId && /* @__PURE__ */ jsxRuntime.jsx(
2910
+ Button,
2911
+ {
2912
+ type: "button",
2913
+ variant: "outline",
2914
+ size: "icon",
2915
+ onClick: onRefresh,
2916
+ disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2917
+ "aria-label": "Reconnect",
2918
+ title: "Reconnect to room",
2919
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2920
+ lucideReact.RefreshCw,
2921
+ {
2922
+ className: cn(
2923
+ "h-5 w-5",
2924
+ (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
2925
+ )
2926
+ }
2927
+ )
2928
+ }
2929
+ ),
2930
+ onReconnect && /* @__PURE__ */ jsxRuntime.jsx(
2931
+ Button,
2932
+ {
2933
+ type: "button",
2934
+ variant: "outline",
2935
+ size: "icon",
2936
+ onClick: () => setIsScannerOpen(true),
2937
+ "aria-label": "Scan QR code to reconnect",
2938
+ title: "Scan QR code to reconnect",
2939
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.QrCode, { className: "h-5 w-5" })
2940
+ }
2941
+ ),
2942
+ onTogglePlayPause && /* @__PURE__ */ jsxRuntime.jsx(
2943
+ Button,
2944
+ {
2945
+ type: "button",
2946
+ variant: "outline",
2947
+ size: "icon",
2948
+ onClick: onTogglePlayPause,
2949
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2950
+ title: gameState === "playing" ? "Pause" : "Play",
2951
+ children: gameState === "playing" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Play, { className: "h-5 w-5" })
2952
+ }
2953
+ ),
2954
+ /* @__PURE__ */ jsxRuntime.jsx(
2955
+ Button,
2956
+ {
2957
+ type: "button",
2958
+ variant: "outline",
2959
+ size: "icon",
2960
+ onClick: () => toggleFullscreen(),
2961
+ "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2962
+ title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2963
+ children: isFullscreen ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Maximize, { className: "h-5 w-5" })
2964
+ }
2965
+ )
2966
+ ] })
2967
+ ] }),
2968
+ /* @__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: [
2969
+ !orientationOk && forceOrientation && /* @__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: [
2970
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2971
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2972
+ "This game is best experienced in ",
2973
+ forceOrientation,
2974
+ " ",
2975
+ "orientation."
2976
+ ] })
2977
+ ] }),
2978
+ /* @__PURE__ */ jsxRuntime.jsx(
2979
+ "div",
2980
+ {
2981
+ className: cn(
2982
+ "h-full w-full select-none",
2983
+ !orientationOk && "pointer-events-none opacity-30"
2984
+ ),
2985
+ children
2986
+ }
2987
+ )
2988
+ ] }) }),
2989
+ onReconnect && /* @__PURE__ */ jsxRuntime.jsx(
2990
+ QRScannerDialog,
2991
+ {
2992
+ isOpen: isScannerOpen,
2993
+ onClose: () => setIsScannerOpen(false),
2994
+ onScan: (roomCode) => {
2995
+ onReconnect(roomCode);
2996
+ setIsScannerOpen(false);
2997
+ },
2998
+ currentRoomId: roomId
2999
+ }
3000
+ )
3001
+ ] }) });
3002
+ };
3003
+
3004
+ // src/events.ts
3005
+ var HostEvents = {
3006
+ /**
3007
+ * Register as a master host (standalone mode)
3008
+ */
3009
+ REGISTER: "host:register",
3010
+ /**
3011
+ * Register as the system/arcade master host
3012
+ */
3013
+ REGISTER_SYSTEM: "host:registerSystem",
3014
+ /**
3015
+ * Join as a child host (game launched from arcade)
3016
+ */
3017
+ JOIN_AS_CHILD: "host:joinAsChild"
3018
+ };
3019
+ var ControllerEvents = {
3020
+ /**
3021
+ * Controller joins a room
3022
+ */
3023
+ JOIN: "controller:join",
3024
+ /**
3025
+ * Controller sends input
3026
+ */
3027
+ INPUT: "controller:input",
3028
+ /**
3029
+ * Controller leaves a room
3030
+ */
3031
+ LEAVE: "controller:leave",
3032
+ /**
3033
+ * Controller sends game state update
3034
+ */
3035
+ STATE: "controller:state",
3036
+ /**
3037
+ * Controller sends system command
3038
+ */
3039
+ SYSTEM: "controller:system"
3040
+ };
3041
+ var SystemEvents = {
3042
+ /**
3043
+ * Arcade launches a game
3044
+ */
3045
+ LAUNCH_GAME: "system:launchGame",
3046
+ /**
3047
+ * Arcade closes a game
3048
+ */
3049
+ CLOSE_GAME: "system:closeGame"
3050
+ };
3051
+ var ServerEvents = {
3052
+ /**
3053
+ * Welcome message with room/controller info
3054
+ */
3055
+ WELCOME: "server:welcome",
3056
+ /**
3057
+ * Room is ready
3058
+ */
3059
+ ROOM_READY: "server:roomReady",
3060
+ /**
3061
+ * Controller joined notification
3062
+ */
3063
+ CONTROLLER_JOINED: "server:controllerJoined",
3064
+ /**
3065
+ * Controller left notification
3066
+ */
3067
+ CONTROLLER_LEFT: "server:controllerLeft",
3068
+ /**
3069
+ * Host left notification
3070
+ */
3071
+ HOST_LEFT: "server:hostLeft",
3072
+ /**
3073
+ * Server error
3074
+ */
3075
+ ERROR: "server:error",
3076
+ /**
3077
+ * Play sound on client
3078
+ */
3079
+ PLAY_SOUND: "server:playSound"
3080
+ };
3081
+ var ClientEvents = {
3082
+ /**
3083
+ * Load a game UI in the controller iframe
3084
+ */
3085
+ LOAD_UI: "client:loadUi",
3086
+ /**
3087
+ * Unload the game UI from the controller iframe
3088
+ */
3089
+ UNLOAD_UI: "client:unloadUi",
3090
+ /**
3091
+ * Update game state display
3092
+ */
3093
+ STATE: "client:state"
3094
+ };
3095
+ var ChildEvents = {
3096
+ /**
3097
+ * Server requests child to close
3098
+ */
3099
+ CLOSE: "child:close"
2897
3100
  };
2898
- var useAirJamHost = (options = {}) => {
2899
- const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
2900
- const arcadeParams = React.useMemo(() => {
3101
+ var Events = {
3102
+ Host: HostEvents,
3103
+ Controller: ControllerEvents,
3104
+ System: SystemEvents,
3105
+ Server: ServerEvents,
3106
+ Client: ClientEvents,
3107
+ Child: ChildEvents
3108
+ };
3109
+
3110
+ // src/utils/ids.ts
3111
+ var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
3112
+ var generateRoomCode = () => {
3113
+ const array = new Uint32Array(4);
3114
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
3115
+ crypto.getRandomValues(array);
3116
+ } else {
3117
+ for (let i = 0; i < array.length; i += 1) {
3118
+ array[i] = Math.floor(Math.random() * alphabet.length);
3119
+ }
3120
+ }
3121
+ const code = Array.from(
3122
+ array,
3123
+ (value) => alphabet[value % alphabet.length]
3124
+ ).join("");
3125
+ return roomCodeSchema.parse(code);
3126
+ };
3127
+ var generateControllerId = () => {
3128
+ const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
3129
+ const random = alphabet[Math.floor(Math.random() * alphabet.length)];
3130
+ return `C${random}${stamp}`;
3131
+ };
3132
+
3133
+ // src/hooks/use-air-jam-controller.ts
3134
+ var getRoomFromLocation = () => {
3135
+ if (typeof window === "undefined") {
3136
+ return null;
3137
+ }
3138
+ const params = new URLSearchParams(window.location.search);
3139
+ const code = params.get("room");
3140
+ return code ? code.toUpperCase() : null;
3141
+ };
3142
+ var useAirJamController = (options = {}) => {
3143
+ const { store, getSocket, disconnectSocket } = useAirJamContext();
3144
+ const nicknameRef = React.useRef(options.nickname ?? "");
3145
+ const subControllerParams = React.useMemo(() => {
2901
3146
  if (typeof window === "undefined") return null;
2902
3147
  const params = new URLSearchParams(window.location.search);
2903
3148
  const room = params.get("aj_room");
2904
- const token = params.get("aj_token");
2905
- if (room && token) {
2906
- return { room, token };
3149
+ const controllerId2 = params.get("aj_controller_id");
3150
+ if (room && controllerId2) {
3151
+ return { room, controllerId: controllerId2 };
2907
3152
  }
2908
3153
  return null;
2909
3154
  }, []);
2910
- const isChildMode = !!arcadeParams;
2911
- const shouldConnect = true;
2912
- const [fallbackRoomId] = React.useState(() => generateRoomCode());
2913
3155
  const parsedRoomId = React.useMemo(() => {
2914
- if (arcadeParams) {
2915
- return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
3156
+ const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
3157
+ if (!code) return null;
3158
+ try {
3159
+ return roomCodeSchema.parse(code.toUpperCase());
3160
+ } catch {
3161
+ return null;
2916
3162
  }
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
- }
3163
+ }, [options.roomId, subControllerParams]);
3164
+ const controllerId = React.useMemo(() => {
3165
+ if (subControllerParams?.controllerId) {
3166
+ return subControllerParams.controllerId;
2924
3167
  }
2925
- if (options.roomId) {
2926
- return roomCodeSchema.parse(options.roomId.toUpperCase());
3168
+ if (options.controllerId) {
3169
+ return options.controllerId;
2927
3170
  }
2928
- return fallbackRoomId;
2929
- }, [options.roomId, fallbackRoomId, arcadeParams]);
2930
- React.useEffect(() => {
2931
- if (inputManager) {
2932
- inputManager.setRoomId(parsedRoomId);
3171
+ if (typeof window !== "undefined") {
3172
+ const params = new URLSearchParams(window.location.search);
3173
+ const urlControllerId = params.get("controllerId");
3174
+ if (urlControllerId) return urlControllerId;
2933
3175
  }
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);
3176
+ return generateControllerId();
3177
+ }, [options.controllerId, subControllerParams]);
3178
+ const onStateRef = React.useRef(
3179
+ options.onState
3180
+ );
2939
3181
  React.useEffect(() => {
2940
- onPlayerJoinRef.current = options.onPlayerJoin;
2941
- onPlayerLeaveRef.current = options.onPlayerLeave;
2942
- onChildCloseRef.current = options.onChildClose;
2943
- }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
3182
+ onStateRef.current = options.onState;
3183
+ }, [options.onState]);
2944
3184
  const connectionState = zustand.useStore(
2945
3185
  store,
2946
3186
  shallow.useShallow((state) => ({
2947
3187
  connectionStatus: state.connectionStatus,
2948
3188
  lastError: state.lastError,
3189
+ controllerId: state.controllerId,
2949
3190
  players: state.players,
2950
3191
  gameState: state.gameState,
2951
- mode: state.mode
3192
+ stateMessage: state.stateMessage
2952
3193
  }))
2953
3194
  );
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);
3195
+ const [reconnectKey, setReconnectKey] = React.useState(0);
3196
+ const reconnect = React.useCallback(() => {
3197
+ if (!parsedRoomId) return;
3198
+ disconnectSocket("controller");
3199
+ setReconnectKey((prev) => prev + 1);
3200
+ }, [parsedRoomId, disconnectSocket]);
3201
+ const isChildMode = React.useMemo(() => {
3202
+ if (typeof window === "undefined") return false;
3203
+ const params = new URLSearchParams(window.location.search);
3204
+ return params.get("airjam_mode") === "child";
3205
+ }, []);
3206
+ const shouldConnect = React.useMemo(() => {
3207
+ if (options.forceConnect) return true;
3208
+ if (subControllerParams) return true;
3209
+ if (typeof window !== "undefined") {
3210
+ const params = new URLSearchParams(window.location.search);
3211
+ return params.get("airjam_force_connect") === "true";
2974
3212
  }
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]
3213
+ return false;
3214
+ }, [options.forceConnect, subControllerParams]);
3215
+ const canConnect = React.useMemo(
3216
+ () => !isChildMode || shouldConnect,
3217
+ [isChildMode, shouldConnect]
2992
3218
  );
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]
3219
+ const socket = React.useMemo(
3220
+ () => canConnect && parsedRoomId ? getSocket("controller") : null,
3221
+ [canConnect, parsedRoomId, getSocket]
3006
3222
  );
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
3223
  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);
3224
+ if (!socket) return;
3225
+ const handleSignal = (signal) => {
3226
+ if (signal.type !== "HAPTIC") return;
3227
+ if (typeof navigator === "undefined" || !navigator.vibrate) return;
3228
+ const payload = signal.payload;
3229
+ switch (payload.pattern) {
3230
+ case "light":
3231
+ navigator.vibrate(10);
3232
+ break;
3233
+ case "medium":
3234
+ navigator.vibrate(30);
3235
+ break;
3236
+ case "heavy":
3237
+ navigator.vibrate([50, 20, 50]);
3238
+ break;
3239
+ case "success":
3240
+ navigator.vibrate([10, 30, 10]);
3241
+ break;
3242
+ case "failure":
3243
+ navigator.vibrate([50, 50, 50, 50]);
3244
+ break;
3245
+ case "custom":
3246
+ if (Array.isArray(payload.sequence)) {
3247
+ navigator.vibrate(payload.sequence);
3248
+ } else if (typeof payload.sequence === "number") {
3249
+ navigator.vibrate(payload.sequence);
3078
3250
  }
3079
- });
3251
+ break;
3080
3252
  }
3081
3253
  };
3254
+ socket.on("server:signal", handleSignal);
3255
+ return () => {
3256
+ socket.off("server:signal", handleSignal);
3257
+ };
3258
+ }, [socket]);
3259
+ React.useEffect(() => {
3260
+ const storeState = store.getState();
3261
+ storeState.setMode(detectRunMode());
3262
+ storeState.setRole("controller");
3263
+ storeState.setRoomId(parsedRoomId);
3264
+ storeState.setStatus(parsedRoomId ? "connecting" : "idle");
3265
+ storeState.setError(void 0);
3266
+ if (!canConnect) {
3267
+ storeState.setStatus("connected");
3268
+ const handleMessage = (event) => {
3269
+ if (event.source !== window.parent) return;
3270
+ const data = event.data;
3271
+ if (data?.type === "AIRJAM_STATE") {
3272
+ const payload = data.payload;
3273
+ if (payload.gameState) storeState.setGameState(payload.gameState);
3274
+ if (payload.message !== void 0)
3275
+ storeState.setStateMessage(payload.message);
3276
+ onStateRef.current?.(payload);
3277
+ }
3278
+ };
3279
+ window.addEventListener("message", handleMessage);
3280
+ window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
3281
+ return () => {
3282
+ window.removeEventListener("message", handleMessage);
3283
+ storeState.setStatus("disconnected");
3284
+ };
3285
+ }
3286
+ if (!parsedRoomId || !socket || !controllerId) {
3287
+ storeState.setStatus("idle");
3288
+ return;
3289
+ }
3290
+ storeState.setControllerId(controllerId);
3082
3291
  const handleConnect = () => {
3083
3292
  store.getState().setStatus("connected");
3084
- registerHost();
3293
+ if (subControllerParams) {
3294
+ return;
3295
+ }
3296
+ const payload = controllerJoinSchema.parse({
3297
+ roomId: parsedRoomId,
3298
+ controllerId,
3299
+ nickname: nicknameRef.current || void 0
3300
+ });
3301
+ socket.emit("controller:join", payload, (ack) => {
3302
+ const storeState2 = store.getState();
3303
+ if (!ack.ok) {
3304
+ storeState2.setError(ack.message ?? "Unable to join room");
3305
+ storeState2.setStatus("disconnected");
3306
+ return;
3307
+ }
3308
+ if (ack.controllerId) {
3309
+ storeState2.setControllerId(ack.controllerId);
3310
+ }
3311
+ storeState2.setStatus("connected");
3312
+ });
3085
3313
  };
3086
3314
  const handleDisconnect = () => {
3087
3315
  store.getState().setStatus("disconnected");
3088
3316
  };
3089
- const handleJoin = (payload) => {
3090
- if (payload.player) {
3091
- store.getState().upsertPlayer(payload.player);
3092
- setTimeout(() => {
3093
- onPlayerJoinRef.current?.(payload.player);
3094
- }, 0);
3317
+ const handleWelcome = (payload) => {
3318
+ const storeState2 = store.getState();
3319
+ const storeRoomId = storeState2.roomId;
3320
+ if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
3321
+ return;
3095
3322
  }
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);
3323
+ if (!storeRoomId && payload.roomId) {
3324
+ storeState2.setRoomId(payload.roomId);
3104
3325
  }
3105
- };
3106
- const handleChildClose = () => {
3107
- onChildCloseRef.current?.();
3326
+ if (!payload.player) {
3327
+ storeState2.setError(
3328
+ "Welcome message received but no player profile included."
3329
+ );
3330
+ return;
3331
+ }
3332
+ storeState2.upsertPlayer(payload.player);
3108
3333
  };
3109
3334
  const handleState = (payload) => {
3110
3335
  if (payload.roomId !== parsedRoomId) return;
@@ -3115,74 +3340,118 @@ var useAirJamHost = (options = {}) => {
3115
3340
  if (payload.state.message !== void 0) {
3116
3341
  storeState2.setStateMessage(payload.state.message);
3117
3342
  }
3343
+ onStateRef.current?.(payload.state);
3344
+ };
3345
+ const handleHostLeft = (payload) => {
3346
+ const storeState2 = store.getState();
3347
+ storeState2.setError(payload.reason);
3348
+ storeState2.setStatus("disconnected");
3349
+ storeState2.resetGameState();
3350
+ setTimeout(() => {
3351
+ disconnectSocket("controller");
3352
+ setReconnectKey((prev) => prev + 1);
3353
+ }, 1e3);
3118
3354
  };
3119
3355
  const handleError = (payload) => {
3120
3356
  store.getState().setError(payload.message);
3121
3357
  };
3122
3358
  socket.on("connect", handleConnect);
3123
3359
  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);
3360
+ socket.on("server:welcome", handleWelcome);
3129
3361
  socket.on("server:state", handleState);
3362
+ socket.on("server:hostLeft", handleHostLeft);
3363
+ socket.on("server:error", handleError);
3130
3364
  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
3365
  return () => {
3139
3366
  socket.off("connect", handleConnect);
3140
3367
  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);
3368
+ socket.off("server:welcome", handleWelcome);
3146
3369
  socket.off("server:state", handleState);
3370
+ socket.off("server:hostLeft", handleHostLeft);
3371
+ socket.off("server:error", handleError);
3147
3372
  };
3148
3373
  }, [
3149
- config.maxPlayers,
3150
- config.apiKey,
3151
- options.maxPlayers,
3152
- options.apiKey,
3153
3374
  parsedRoomId,
3154
- arcadeParams,
3155
- shouldConnect,
3375
+ reconnectKey,
3376
+ canConnect,
3156
3377
  socket,
3378
+ controllerId,
3379
+ subControllerParams,
3157
3380
  store,
3158
- inputManager,
3159
- setRegisteredRoomId
3381
+ disconnectSocket
3160
3382
  ]);
3161
- const returnSocket = socket ?? getSocket("host");
3162
- const getInput = React.useCallback(
3163
- (controllerId) => {
3164
- if (!inputManager) {
3165
- return void 0;
3383
+ const setNickname = React.useCallback((value) => {
3384
+ nicknameRef.current = value;
3385
+ }, []);
3386
+ const sendInput = React.useCallback(
3387
+ (input) => {
3388
+ const storeState = store.getState();
3389
+ if (!canConnect) {
3390
+ if (typeof window !== "undefined") {
3391
+ window.parent.postMessage(
3392
+ {
3393
+ type: "AIRJAM_INPUT",
3394
+ payload: input
3395
+ },
3396
+ "*"
3397
+ );
3398
+ }
3399
+ return true;
3166
3400
  }
3167
- return inputManager.getInput(controllerId);
3401
+ if (!parsedRoomId || !storeState.controllerId || !socket) {
3402
+ storeState.setError("Not connected to a room");
3403
+ return false;
3404
+ }
3405
+ if (!socket.connected) {
3406
+ return false;
3407
+ }
3408
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3409
+ storeState.setError("Input must be an object");
3410
+ return false;
3411
+ }
3412
+ const payload = controllerInputSchema.safeParse({
3413
+ roomId: parsedRoomId,
3414
+ controllerId: storeState.controllerId,
3415
+ input
3416
+ });
3417
+ if (!payload.success) {
3418
+ storeState.setError(payload.error.message);
3419
+ return false;
3420
+ }
3421
+ socket.emit("controller:input", payload.data);
3422
+ return true;
3168
3423
  },
3169
- [inputManager]
3424
+ [parsedRoomId, canConnect, socket, store]
3425
+ );
3426
+ const sendSystemCommand = React.useCallback(
3427
+ (command) => {
3428
+ const storeState = store.getState();
3429
+ if (!canConnect) return;
3430
+ if (!parsedRoomId || !storeState.controllerId || !socket) return;
3431
+ if (!socket.connected) return;
3432
+ const payload = controllerSystemSchema.safeParse({
3433
+ roomId: parsedRoomId,
3434
+ command
3435
+ });
3436
+ if (payload.success) {
3437
+ socket.emit("controller:system", payload.data);
3438
+ }
3439
+ },
3440
+ [parsedRoomId, canConnect, socket, store]
3170
3441
  );
3171
3442
  return {
3172
3443
  roomId: parsedRoomId,
3173
- joinUrl,
3444
+ controllerId: connectionState.controllerId,
3174
3445
  connectionStatus: connectionState.connectionStatus,
3175
- players: connectionState.players,
3176
3446
  lastError: connectionState.lastError,
3177
- mode: connectionState.mode,
3178
3447
  gameState: connectionState.gameState,
3179
- toggleGameState,
3180
- sendState,
3181
- sendSignal,
3448
+ stateMessage: connectionState.stateMessage,
3449
+ sendInput,
3450
+ sendSystemCommand,
3451
+ setNickname,
3182
3452
  reconnect,
3183
- socket: returnSocket,
3184
- isChildMode,
3185
- getInput
3453
+ players: connectionState.players,
3454
+ socket
3186
3455
  };
3187
3456
  };
3188
3457
  var getRoomFromLocation2 = () => {
@@ -3370,6 +3639,7 @@ var useAirJamShell = (options = {}) => {
3370
3639
  const sendInput = React.useCallback(
3371
3640
  (input) => {
3372
3641
  const storeState = store.getState();
3642
+ input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01);
3373
3643
  if (!parsedRoomId || !storeState.controllerId || !socket) {
3374
3644
  storeState.setError("Not connected to a room");
3375
3645
  return false;
@@ -3453,25 +3723,167 @@ var useSendSignal = () => {
3453
3723
  );
3454
3724
  return sendSignal;
3455
3725
  };
3726
+ function createAirJamStore2(initializer) {
3727
+ const store = zustand.create((set, get, api) => {
3728
+ const baseState = initializer(set, get, api);
3729
+ return {
3730
+ ...baseState,
3731
+ actions: {
3732
+ ...baseState.actions,
3733
+ _syncState: (partial) => {
3734
+ set(partial);
3735
+ }
3736
+ }
3737
+ };
3738
+ });
3739
+ const gameUiUnloadedRef = { current: false };
3740
+ const useSyncedStore = (selector = (s) => s) => {
3741
+ const slice = store(selector);
3742
+ const { getSocket } = useAirJamContext();
3743
+ const role = useAirJamState((state) => state.role);
3744
+ const roomId = useAirJamState((state) => state.roomId);
3745
+ const controllerId = useAirJamState((state) => state.controllerId);
3746
+ const socket = role === "host" ? getSocket("host") : getSocket("controller");
3747
+ const socketRef = React.useRef(socket);
3748
+ React.useEffect(() => {
3749
+ socketRef.current = socket;
3750
+ }, [socket]);
3751
+ React.useEffect(() => {
3752
+ if (!socket || !roomId || !role) {
3753
+ return;
3754
+ }
3755
+ if (role === "host") {
3756
+ const unsubscribe = store.subscribe((newState) => {
3757
+ const { actions, ...stateData } = newState;
3758
+ socket.emit("host:state_sync", { roomId, data: stateData });
3759
+ });
3760
+ const handleAction = (payload) => {
3761
+ const { actionName, args, controllerId: controllerId2 } = payload;
3762
+ const actionFn = store.getState().actions[actionName];
3763
+ if (actionFn) {
3764
+ actionFn(...args, controllerId2);
3765
+ }
3766
+ };
3767
+ socket.on("airjam:action_rpc", handleAction);
3768
+ return () => {
3769
+ unsubscribe();
3770
+ socket.off("airjam:action_rpc", handleAction);
3771
+ };
3772
+ }
3773
+ if (role === "controller") {
3774
+ gameUiUnloadedRef.current = false;
3775
+ const handleSync = (payload) => {
3776
+ const { data } = payload;
3777
+ const currentState = store.getState();
3778
+ const actions = currentState.actions;
3779
+ if (actions._syncState) {
3780
+ actions._syncState(data);
3781
+ } else {
3782
+ store.setState(data);
3783
+ }
3784
+ };
3785
+ socket.on("airjam:state_sync", handleSync);
3786
+ const handleUnloadUi = () => {
3787
+ gameUiUnloadedRef.current = true;
3788
+ socket.off("airjam:state_sync", handleSync);
3789
+ };
3790
+ const handleLoadUi = () => {
3791
+ gameUiUnloadedRef.current = false;
3792
+ };
3793
+ socket.on("client:loadUi", handleLoadUi);
3794
+ const handleDisconnect = () => {
3795
+ gameUiUnloadedRef.current = true;
3796
+ };
3797
+ socket.on("disconnect", handleDisconnect);
3798
+ socket.on("client:unloadUi", handleUnloadUi);
3799
+ return () => {
3800
+ socket.off("airjam:state_sync", handleSync);
3801
+ socket.off("client:loadUi", handleLoadUi);
3802
+ socket.off("client:unloadUi", handleUnloadUi);
3803
+ socket.off("disconnect", handleDisconnect);
3804
+ };
3805
+ }
3806
+ }, [socket, role, roomId, socket?.id]);
3807
+ if (role === "controller" && socket && roomId) {
3808
+ let originalActions = null;
3809
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3810
+ originalActions = slice.actions;
3811
+ } else if (typeof slice === "object" && slice !== null) {
3812
+ const fullState = store.getState();
3813
+ if (fullState.actions) {
3814
+ const sliceKeys = Object.keys(slice);
3815
+ const actionKeys = Object.keys(fullState.actions);
3816
+ if (sliceKeys.length > 0 && sliceKeys.every(
3817
+ (key) => typeof slice[key] === "function" && actionKeys.includes(key)
3818
+ )) {
3819
+ originalActions = slice;
3820
+ }
3821
+ }
3822
+ }
3823
+ if (originalActions) {
3824
+ const proxyActions = {};
3825
+ Object.keys(originalActions).forEach((key) => {
3826
+ proxyActions[key] = (...args) => {
3827
+ if (gameUiUnloadedRef.current) {
3828
+ console.warn(
3829
+ `[AirJamStore] Action "${key}" blocked: Game UI unloaded.`
3830
+ );
3831
+ return;
3832
+ }
3833
+ const activeSocket = socketRef.current;
3834
+ if (!activeSocket || !activeSocket.connected) {
3835
+ console.warn(
3836
+ `[AirJamStore] Action "${key}" blocked: Socket disconnected.`
3837
+ );
3838
+ return;
3839
+ }
3840
+ if (!controllerId) {
3841
+ console.warn(
3842
+ "[AirJamStore] Cannot send action RPC: controllerId not set"
3843
+ );
3844
+ return;
3845
+ }
3846
+ activeSocket.emit("controller:action_rpc", {
3847
+ roomId,
3848
+ actionName: key,
3849
+ args,
3850
+ controllerId
3851
+ });
3852
+ };
3853
+ });
3854
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3855
+ return { ...slice, actions: proxyActions };
3856
+ } else {
3857
+ return proxyActions;
3858
+ }
3859
+ }
3860
+ }
3861
+ return slice;
3862
+ };
3863
+ return useSyncedStore;
3864
+ }
3456
3865
 
3457
3866
  exports.AIRJAM_PROXY_PREFIX = AIRJAM_PROXY_PREFIX;
3458
3867
  exports.AirJamContext = AirJamContext;
3868
+ exports.AirJamDebug = AirJamDebug;
3459
3869
  exports.AirJamOverlay = AirJamOverlay;
3460
3870
  exports.AirJamProvider = AirJamProvider;
3461
3871
  exports.AudioManager = AudioManager;
3462
3872
  exports.AudioProvider = AudioProvider;
3463
3873
  exports.Button = Button;
3874
+ exports.CONTROLLER_PATH = CONTROLLER_PATH;
3464
3875
  exports.ChildEvents = ChildEvents;
3465
3876
  exports.ClientEvents = ClientEvents;
3466
3877
  exports.ControllerEvents = ControllerEvents;
3467
3878
  exports.ControllerShell = ControllerShell;
3468
- exports.DEFAULT_CONTROLLER_PATH = DEFAULT_CONTROLLER_PATH;
3469
3879
  exports.DEFAULT_MAX_PLAYERS = DEFAULT_MAX_PLAYERS;
3470
3880
  exports.DEFAULT_SERVER_PORT = DEFAULT_SERVER_PORT;
3881
+ exports.DebugStateDialog = DebugStateDialog;
3471
3882
  exports.ErrorCode = ErrorCode;
3472
3883
  exports.Events = Events;
3473
3884
  exports.HostEvents = HostEvents;
3474
3885
  exports.INPUT_DEBOUNCE_MS = INPUT_DEBOUNCE_MS;
3886
+ exports.PlayerAvatar = PlayerAvatar;
3475
3887
  exports.SOCKET_CONFIG = SOCKET_CONFIG;
3476
3888
  exports.ServerEvents = ServerEvents;
3477
3889
  exports.Slider = Slider;
@@ -3486,12 +3898,15 @@ exports.controllerJoinSchema = controllerJoinSchema;
3486
3898
  exports.controllerLeaveSchema = controllerLeaveSchema;
3487
3899
  exports.controllerStateSchema = controllerStateSchema;
3488
3900
  exports.controllerSystemSchema = controllerSystemSchema;
3901
+ exports.createAirJamStore = createAirJamStore2;
3489
3902
  exports.createAudioManager = createAudioManager;
3490
3903
  exports.detectSoundCategory = detectSoundCategory;
3491
3904
  exports.generateControllerId = generateControllerId;
3492
3905
  exports.generateRoomCode = generateRoomCode;
3493
3906
  exports.getLocalNetworkIp = getLocalNetworkIp;
3907
+ exports.hostCreateRoomSchema = hostCreateRoomSchema;
3494
3908
  exports.hostJoinAsChildSchema = hostJoinAsChildSchema;
3909
+ exports.hostReconnectSchema = hostReconnectSchema;
3495
3910
  exports.hostRegisterSystemSchema = hostRegisterSystemSchema;
3496
3911
  exports.hostRegistrationSchema = hostRegistrationSchema;
3497
3912
  exports.roomCodeSchema = roomCodeSchema;