"use client";

import React, { createContext, useCallback, useContext, useMemo } from "react";
import { openGameLaunchWithParams } from "@/components/providers/game-launch-store";

type GameLaunchContextValue = {
	launchGame: (placeId: string, jobId?: string) => void;
};

const GameLaunchContext = createContext<GameLaunchContextValue | null>(null);

export function useGameLaunch() {
	const ctx = useContext(GameLaunchContext);
	if (!ctx) {
		throw new Error("useGameLaunch must be used within GameLaunchProvider");
	}
	return ctx;
}

export function GameLaunchProvider({
	children
}: {
	children: React.ReactNode;
}) {
	const launchGame = useCallback((placeId: string, jobId?: string) => {
		openGameLaunchWithParams(placeId, jobId);

		console.log("[GameLaunchProvider] Launching",{placeId, jobId});

		const gameLaunchParams = {
			launchmode: "play",
			LaunchExp: "InApp",
			placeId: placeId,
			gameInstanceId: jobId ?? undefined
		};

		console.log("[GameLaunchProvider] Constructed GameLaunchParams",gameLaunchParams);

		const url = new URL("roblox://experiences/start")

		for (const [key, value] of Object.entries(gameLaunchParams)) {
			if (value !== undefined && value !== null) {
				url.searchParams.append(key, String(value));
			}
		}

		const deeplinkNew = url.toString();
		console.log("[GameLaunchProvider] Opening URL:", deeplinkNew);

		document.location.href = deeplinkNew;
	}, []);

	const value = useMemo(() => ({ launchGame }), [launchGame]);

	return (
		<GameLaunchContext.Provider value={value}>
			{children}
		</GameLaunchContext.Provider>
	);
}
