---
/**
 * Sandbox Test Page
 *
 * Tests the Worker Loader functionality by spawning a dynamic isolate.
 */
import { env } from "cloudflare:workers";

interface TestResult {
	loaderAvailable: boolean;
	isolateSpawned: boolean;
	rpcWorked: boolean;
	error?: string;
	result?: unknown;
}

const results: TestResult = {
	loaderAvailable: false,
	isolateSpawned: false,
	rpcWorked: false,
};

try {
	// Check if LOADER binding is available
	// @ts-ignore - env typing
	const loader = env.LOADER;
	results.loaderAvailable = !!loader;

	if (loader) {
		// Try to spawn a simple isolate
		const testCode = `
			import { WorkerEntrypoint } from "cloudflare:workers";
			
			export default class TestEntrypoint extends WorkerEntrypoint {
				async test(input) {
					return {
						success: true,
						message: "Hello from sandbox!",
						received: input,
						timestamp: Date.now()
					};
				}
			}
		`;

		const worker = loader.get("sandbox-test-" + Date.now(), () => ({
			compatibilityDate: "2025-01-01",
			mainModule: "test.js",
			modules: {
				"test.js": { js: testCode },
			},
			globalOutbound: null, // Block network
			env: {},
		}));

		results.isolateSpawned = true;

		// Test RPC call — methods are dynamically defined in sandbox code
		// @ts-ignore - Worker Loader RPC methods are not statically typed
		const entrypoint = worker.getEntrypoint("default");
		// @ts-ignore - dynamic RPC method
		const rpcResult = await entrypoint.test({ test: "data" });
		results.rpcWorked = rpcResult?.success === true;
		results.result = rpcResult;
	}
} catch (e) {
	results.error = e instanceof Error ? e.message : String(e);
}
---

<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>Sandbox Test</title>
		<style>
			body {
				font-family: system-ui, sans-serif;
				max-width: 800px;
				margin: 2rem auto;
				padding: 1rem;
			}
			.result {
				padding: 1rem;
				border-radius: 0.5rem;
				margin: 1rem 0;
			}
			.success {
				background: #d4edda;
				border: 1px solid #c3e6cb;
			}
			.error {
				background: #f8d7da;
				border: 1px solid #f5c6cb;
			}
			.pending {
				background: #fff3cd;
				border: 1px solid #ffeeba;
			}
			pre {
				background: #f4f4f4;
				padding: 1rem;
				overflow: auto;
				border-radius: 0.25rem;
			}
		</style>
	</head>
	<body>
		<h1>Worker Loader Sandbox Test</h1>

		<div class={`result ${results.loaderAvailable ? 'success' : 'error'}`}>
			<strong>LOADER Binding:</strong>
			{results.loaderAvailable ? 'Available' : 'Not available'}
		</div>

		<div class={`result ${results.isolateSpawned ? 'success' : results.loaderAvailable ? 'error' : 'pending'}`}>
			<strong>Isolate Spawned:</strong>
			{results.isolateSpawned ? 'Yes' : 'No'}
		</div>

		<div class={`result ${results.rpcWorked ? 'success' : results.isolateSpawned ? 'error' : 'pending'}`}>
			<strong>RPC Call:</strong>
			{results.rpcWorked ? 'Success' : 'Failed'}
		</div>

		{results.error && (
			<div class="result error">
				<strong>Error:</strong>
				<pre>{results.error}</pre>
			</div>
		)}

		{results.result && (
			<div class="result success">
				<strong>Result from Sandbox:</strong>
				<pre>{JSON.stringify(results.result, null, 2)}</pre>
			</div>
		)}

		<h2>Next Steps</h2>
		<p>
			If all tests pass, the Worker Loader is working correctly.
			This means we can run sandboxed plugins in isolated V8 isolates.
		</p>

		<h2>Raw Results</h2>
		<pre>{JSON.stringify(results, null, 2)}</pre>
	</body>
</html>
