import { Suspense } from "react";
import type { Metadata } from "next";
import GamePageContentF from "./content";

// page.tsx (Server Component)
export default async function GamePageContent({
	params
}: {
	params: { id: string };
}) {
	return (
		<Suspense
			fallback={
				<div className="page-container py-6 text-sm text-subtext1">
					Loading game…
				</div>
			}
		>
			<GamePageContentF placeId={(await params).id} />
		</Suspense>
	);
}

export async function generateMetadata({
	params
}: {
	params: { id: string };
}): Promise<Metadata> {
	const placeId = params.id;

	try {
		const universeRes = await fetch(
			`https://apis.roblox.com/universes/v1/places/${placeId}/universe`,
			{ next: { revalidate: 300 } }
		);
		if (!universeRes.ok) {
			return { title: "Game | Roblox" };
		}

		const { universeId } = await universeRes.json();
		if (!universeId) {
			return { title: "Game | Roblox" };
		}

		const gameRes = await fetch(
			`https://games.roblox.com/v1/games?universeIds=${universeId}`,
			{ next: { revalidate: 300 } }
		);
		if (!gameRes.ok) {
			return { title: "Game | Roblox" };
		}

		const data = await gameRes.json();
		const game = data?.data?.[0];
		if (!game) {
			return { title: "Game | Roblox" };
		}

		const title = `${game.name} | Roblox`;
		const description =
			game.description ||
			"Roblox is a global platform that brings people together through play.";
		let imageUrl: string | undefined;

		try {
			const thumbRes = await fetch(
				`https://thumbnails.roblox.com/v1/games/multiget?universeIds=${universeId}&size=768x432&format=png&isCircular=false`,
				{ next: { revalidate: 300 } }
			);
			if (thumbRes.ok) {
				const thumbs = await thumbRes.json();
				imageUrl = thumbs?.data?.[0]?.imageUrl;
			}
		} catch {
			imageUrl = undefined;
		}

		return {
			title,
			description,
			openGraph: {
				title,
				description,
				images: imageUrl ? [imageUrl] : undefined
			},
			twitter: {
				title,
				description,
				images: imageUrl ? [imageUrl] : undefined
			}
		};
	} catch {
		return { title: "Game | Roblox" };
	}
}
