<script lang="ts">
	import { env } from "$env/dynamic/public";
	import type { Identity } from "spacetimedb";
	import { createSpacetimeDBProvider } from "spacetimedb/svelte";
	import { DbConnection, type ErrorContext } from "$lib/st-bindings";
	import "./layout.css";
	import favicon from "$lib/assets/favicon.svg";
	import { browser } from "$app/environment";

	let { children } = $props();

	const HOST = env.PUBLIC_SPACETIMEDB_HOST ?? "ws://localhost:3000";
	const DB_NAME = env.PUBLIC_SPACETIMEDB_DB_NAME ?? "svelte-ts";
	const TOKEN_KEY = `${HOST}/${DB_NAME}/auth_token`;

	console.log(HOST, DB_NAME, TOKEN_KEY);

	const onConnect = (_conn: DbConnection, identity: Identity, token: string) => {
		if (browser) localStorage.setItem(TOKEN_KEY, token);
		console.log("Connected to SpacetimeDB with identity:", identity.toHexString());
	};

	const onDisconnect = () => {
		console.log("Disconnected from SpacetimeDB");
	};

	const onConnectError = (_ctx: ErrorContext, err: Error) => {
		console.log("Error connecting to SpacetimeDB:", err);
	};

	const connectionBuilder = DbConnection.builder()
		.withUri(HOST)
		.withDatabaseName(DB_NAME)
		.withToken(browser ? localStorage.getItem(TOKEN_KEY) || undefined : undefined)
		.onConnect(onConnect)
		.onDisconnect(onDisconnect)
		.onConnectError(onConnectError);

	createSpacetimeDBProvider(connectionBuilder);
</script>

<svelte:head>
	<link rel="icon" href={favicon} />
	<title>Space Stream</title>
</svelte:head>
{@render children()}
