// SparkBun Full Preload Script (for trusted webviews)
// This is compiled to JS and injected into webviews that are NOT sandboxed
//
// Includes: RPC, encryption, drag regions, webview tags, lifecycle events
//
// Before this script runs, the following must be set:
// - window.__sparkbunWebviewId
// - window.__sparkbunWindowId
// - window.__sparkbunRpcSocketPort
// - window.__sparkbunHostSocketPort (optional alias)
// - window.__sparkbunSecretKeyBytes
// - window.__sparkbunEventBridge (event emission - all webviews)
// - window.__sparkbunInternalBridge (internal RPC - trusted only)
// - window.__sparkbunHostBridge (user RPC - trusted only)
// - window.__sparkbunBunBridge (legacy alias)

import "./globals.d.ts";
import { initEncryption } from "./encryption";
import { handleResponse } from "./internalRpc";
import { initDragRegions } from "./dragRegions";
import { initWebviewTag } from "./webviewTag";
import { initWgpuTag } from "./wgpuTag";
import {
	emitWebviewEvent,
	initLifecycleEvents,
	initCmdClickHandling,
	initSPANavigationInterception,
	initOverscrollPrevention,
} from "./events";

// Initialize encryption first (async)
initEncryption().catch((err) =>
	console.error("Failed to initialize encryption:", err),
);

// Set up global handlers for bun to call back
// Wrapper to satisfy the (msg: unknown) => void type
const internalMessageHandler = (msg: unknown) => {
	handleResponse(msg as { type: string; id: string; success: boolean; payload: unknown });
};

const defaultUserMessageHandler = (msg: unknown) => {
	// Buffer user RPC packets that arrive before the page-specific Electroview
	// instance installs the real handler.
	if (!window.__sparkbunPendingHostMessages) {
		window.__sparkbunPendingHostMessages = [];
	}
	window.__sparkbunPendingHostMessages.push(msg);
};

if (!window.__sparkbun) {
	window.__sparkbun = {
		receiveInternalMessageFromHost: internalMessageHandler,
		receiveMessageFromHost: defaultUserMessageHandler,
		receiveInternalMessageFromBun: internalMessageHandler,
		receiveMessageFromBun: defaultUserMessageHandler,
	};
} else {
	window.__sparkbun.receiveInternalMessageFromHost = internalMessageHandler;
	window.__sparkbun.receiveMessageFromHost = defaultUserMessageHandler;
	window.__sparkbun.receiveInternalMessageFromBun = internalMessageHandler;
	window.__sparkbun.receiveMessageFromBun = defaultUserMessageHandler;
}

// Allow preload scripts to send custom messages to the host webview
window.__sparkbunSendToHost = (message: unknown) => {
	emitWebviewEvent("host-message", JSON.stringify(message));
};

// Initialize all features
initLifecycleEvents();
initCmdClickHandling();
initSPANavigationInterception();
initOverscrollPrevention();
initDragRegions();
initWebviewTag();
initWgpuTag();
