import "../use-account-D70N5avv.mjs";
import { t as FluidProvider } from "../FluidProvider-Cx0wNNF7.mjs";
import "../ScreenRenderer-CcT_j-WQ.mjs";
import "../use-optional-store-BPICvfcP.mjs";
import "../mysite-api-context-CoLr9vIf.mjs";
import "../ContactsTranslationBridge-Ckjj_Iu9.mjs";
import "../registry-context-DFsxRMN8.mjs";
import "../WidgetInteractionContext-CDHSzzws.mjs";
import "../RepUserContext-D1G5lEuo.mjs";
import "../QuickLinksWidget-CywzaGnH.mjs";
import "../WidgetRenderStateContext-Deuk22Oj.mjs";
import "../static-dict-adapter-B8kVuZyL.mjs";
import "../SearchSort-DuTESNHX.mjs";
import "../use-share-link-CkTsZcjg.mjs";
import "../translation-api-context-factory-hfY7ipc0.mjs";
import "../shell-translation-api-context-SVRZkj2i.mjs";
import "../error-state-7TTlrxt0.mjs";
import "../PointsWidget-C3oNVD91.mjs";
import "../task-composer-form-DyIXwTgx.mjs";
import "../ShopWidget-N0OqYNM-.mjs";
import "../LayoutWidget-DXPXYYd_.mjs";
import "../registries-CSAha0WD.mjs";
import "../fields-Ba-Ep01A.mjs";
import "../TextWidget-CRo4AN5-.mjs";
import "../AlertWidget-B5aibm-v.mjs";
import "../BulletListWidget-CSogQ3cu.mjs";
import "../preview-context-HwBYhMVb.mjs";
import "../CalendarWidget--EIsxRov.mjs";
import "../CardWidget-cIc9cOG9.mjs";
import "../purify.es-BdzfCAJP.mjs";
import "../MediaRenderer-Dl1imLwm.mjs";
import "../CarouselWidget-BTbRZPWn.mjs";
import "../CatchUpWidget-qNrDLfXJ.mjs";
import "../src-BPYu8cbo.mjs";
import "../ChartWidget-B4vLdttP.mjs";
import "../ContainerWidget-C1Nk6GPZ.mjs";
import "../EmbedWidget-p_Ybl0em.mjs";
import "../ImageWidget-WtC8Rg1y.mjs";
import "../LinkWidget-mKyp0LGz.mjs";
import "../ListWidget-CRzXIlzF.mjs";
import "../MySiteWidget-CY8eXMWv.mjs";
import "../NestedWidget-BXnLrul1.mjs";
import "../QuickShareWidget-DmZjvUVT.mjs";
import "../RecentActivityWidget-C4UFPIIB.mjs";
import "../SeparatorWidget-DxTG9J7u.mjs";
import "../SpacerWidget-Bj79fK_w.mjs";
import "../TableWidget-CG5nu9Bl.mjs";
import "../ToDoWidget-DiGklfKG.mjs";
import "../VideoWidget-DSIgaM1q.mjs";
import "../translation-adapter-C7MxrAX_.mjs";
import "../translation-adapter-CPr3Y0RW.mjs";
import "../translation-adapter-nPt5lYdk.mjs";
import { a as loadWidgetPackages, d as createDefaultFluidConfig, i as installAndReadFluidWidgetsRegistry, l as buildWidgetRegistry, t as dedupeWidgetPackagesByPackageIdAndVersion, u as mergeRegisteredWidgetsIntoRegistry } from "../widget-package-utils-DnNxWKOo.mjs";
import { n as isPreviewCommand, t as isAllowedOrigin } from "../protocol-D5N3pIHL.mjs";
import { Component, StrictMode, useCallback, useEffect, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";
import { createRoot } from "react-dom/client";
//#region src/preview/PreviewRenderer.tsx
/**
* Renders a single widget inside the preview iframe, driven by
* postMessage commands from the builder.
*
* Lifecycle:
*   1. Sends `ready` event on mount
*   2. Waits for `auth` command → calls onAuth()
*   3. Waits for `render-widget` command → renders the widget
*   4. Reports dimensions via ResizeObserver
*/
function PreviewRenderer({ widgetRegistry, onAuth, builderOrigin, skipReady = false }) {
	const [widget, setWidget] = useState(null);
	const [error, setError] = useState(null);
	const containerRef = useRef(null);
	const sentReady = useRef(false);
	const sendToBuilder = useCallback((event) => {
		if (!builderOrigin) return;
		window.parent.postMessage(event, builderOrigin);
	}, [builderOrigin]);
	useEffect(() => {
		if (skipReady) return;
		if (sentReady.current) return;
		sentReady.current = true;
		sendToBuilder({ type: "ready" });
	}, [sendToBuilder, skipReady]);
	const sentAuthReady = useRef(false);
	useEffect(() => {
		if (!skipReady) return;
		if (sentAuthReady.current) return;
		sentAuthReady.current = true;
		sendToBuilder({ type: "auth-ready" });
	}, [sendToBuilder, skipReady]);
	useEffect(() => {
		if (!builderOrigin) return;
		function handleMessage(event) {
			if (event.origin !== builderOrigin) return;
			if (!isPreviewCommand(event.data)) return;
			const command = event.data;
			switch (command.type) {
				case "auth":
					onAuth(command.token);
					if (!sentAuthReady.current) {
						sentAuthReady.current = true;
						sendToBuilder({ type: "auth-ready" });
					}
					break;
				case "render-widget":
					setError(null);
					setWidget({
						widgetType: command.widgetType,
						props: command.props
					});
					break;
				case "select-widget": break;
				case "unmount-widget":
					setWidget(null);
					setError(null);
					break;
				default:
			}
		}
		window.addEventListener("message", handleMessage);
		return () => window.removeEventListener("message", handleMessage);
	}, [
		builderOrigin,
		onAuth,
		sendToBuilder
	]);
	useEffect(() => {
		const container = containerRef.current;
		if (!container || !widget) return;
		const observer = new ResizeObserver((entries) => {
			const entry = entries[0];
			if (!entry) return;
			const { width, height } = entry.contentRect;
			sendToBuilder({
				type: "widget-rendered",
				widgetType: widget.widgetType,
				dimensions: {
					width: Math.ceil(width),
					height: Math.ceil(height)
				}
			});
		});
		observer.observe(container);
		return () => observer.disconnect();
	}, [widget, sendToBuilder]);
	useEffect(() => {
		const hot = import.meta.hot;
		if (hot) {
			const handler = () => sendToBuilder({ type: "widget-hmr" });
			hot.on("vite:afterUpdate", handler);
			return () => hot.off("vite:afterUpdate", handler);
		}
	}, [sendToBuilder]);
	const WidgetComponent = widget ? widgetRegistry[widget.widgetType] : void 0;
	useEffect(() => {
		if (!widget) return;
		if (!widgetRegistry[widget.widgetType]) sendToBuilder({
			type: "widget-error",
			widgetType: widget.widgetType,
			error: `Unknown widget type: ${widget.widgetType}`
		});
	}, [
		widget,
		widgetRegistry,
		sendToBuilder
	]);
	if (!widget) return null;
	if (!WidgetComponent) return null;
	if (error) return null;
	return /* @__PURE__ */ jsx("div", {
		ref: containerRef,
		onClick: () => sendToBuilder({
			type: "widget-clicked",
			widgetType: widget.widgetType
		}),
		children: /* @__PURE__ */ jsx(ErrorBoundary, {
			widgetType: widget.widgetType,
			onError: (err) => {
				setError(err);
				sendToBuilder({
					type: "widget-error",
					widgetType: widget.widgetType,
					error: err
				});
			},
			children: /* @__PURE__ */ jsx(WidgetComponent, { ...widget.props })
		}, widget.widgetType)
	});
}
var ErrorBoundary = class extends Component {
	constructor(props) {
		super(props);
		this.state = { hasError: false };
	}
	static getDerivedStateFromError() {
		return { hasError: true };
	}
	componentDidCatch(error) {
		this.props.onError(error.message);
	}
	render() {
		if (this.state.hasError) return null;
		return this.props.children;
	}
};
//#endregion
//#region src/preview/preview-entry.tsx
/**
* Preview iframe bootstrap function.
*
* Called from the portal project's src/preview-entry.tsx with the
* customWidgets array from portal.config.ts. Mirrors the createPortal()
* pattern — SDK handles the wiring, user project provides the widgets.
*
* Two-phase auth handshake:
*   Phase 1: Send `ready`, wait for `auth` command, store token
*   Phase 2: Mount provider stack + PreviewRenderer, send `auth-ready`
*/
function createPreview(options = {}) {
	const { customWidgets = [], widgetPackages = [], rootId = "preview-root" } = options;
	const dedupedWidgetPackages = dedupeWidgetPackagesByPackageIdAndVersion(widgetPackages);
	const initialWidgetRegistry = mergeRegisteredWidgetsIntoRegistry(buildWidgetRegistry(customWidgets), installAndReadFluidWidgetsRegistry());
	const rawBuilderOrigin = new URLSearchParams(window.location.search).get("builderOrigin");
	const builderOrigin = rawBuilderOrigin && isAllowedOrigin(rawBuilderOrigin) ? rawBuilderOrigin : null;
	if (builderOrigin) window.parent.postMessage({ type: "ready" }, builderOrigin);
	function handleAuthMessage(event) {
		if (event.origin !== builderOrigin) return;
		if (typeof event.data !== "object" || event.data === null || event.data.type !== "auth") return;
		window.removeEventListener("message", handleAuthMessage);
		const command = event.data;
		mountApp({
			initialWidgetRegistry,
			widgetPackages: dedupedWidgetPackages,
			builderOrigin,
			rootId,
			authToken: command.token
		});
	}
	if (builderOrigin) window.addEventListener("message", handleAuthMessage);
	else {
		const rootElement = document.getElementById(rootId);
		if (rootElement) {
			rootElement.style.cssText = "display:flex;align-items:center;justify-content:center;height:100vh;font-family:system-ui;color:#888;font-size:14px";
			rootElement.textContent = rawBuilderOrigin ? `Preview unavailable — origin "${rawBuilderOrigin}" is not allowed` : "Preview unavailable — missing builderOrigin parameter";
		}
	}
}
function mountApp({ initialWidgetRegistry, widgetPackages, builderOrigin, rootId, authToken }) {
	const rootElement = document.getElementById(rootId);
	if (!rootElement) return;
	const iframeOrigin = window.location.origin;
	const tree = /* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsx(PreviewRuntimeWidgetBootstrap, {
		fluidConfig: createDefaultFluidConfig({
			baseUrl: iframeOrigin,
			getAuthToken: () => authToken
		}),
		initialWidgetRegistry,
		widgetPackageLoadPromise: builderOrigin && widgetPackages.length ? loadWidgetPackages(widgetPackages) : void 0,
		builderOrigin
	}) });
	createRoot(rootElement).render(tree);
}
function PreviewRuntimeWidgetBootstrap({ fluidConfig, initialWidgetRegistry, widgetPackageLoadPromise, builderOrigin }) {
	const [runtimeWidgetState, setRuntimeWidgetState] = useState(() => ({
		widgetRegistry: initialWidgetRegistry,
		packageLoadSettled: !widgetPackageLoadPromise
	}));
	useEffect(() => {
		if (!widgetPackageLoadPromise) {
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
			return;
		}
		let cancelled = false;
		setRuntimeWidgetState({
			widgetRegistry: initialWidgetRegistry,
			packageLoadSettled: false
		});
		widgetPackageLoadPromise.then((summary) => {
			if (cancelled) return;
			setRuntimeWidgetState({
				widgetRegistry: mergeRegisteredWidgetsIntoRegistry(initialWidgetRegistry, summary.registeredWidgets),
				packageLoadSettled: true
			});
		}).catch((error) => {
			if (cancelled) return;
			console.error("[portal] Failed to load preview widget packages:", error);
			setRuntimeWidgetState({
				widgetRegistry: initialWidgetRegistry,
				packageLoadSettled: true
			});
		});
		return () => {
			cancelled = true;
		};
	}, [initialWidgetRegistry, widgetPackageLoadPromise]);
	return /* @__PURE__ */ jsx(FluidProvider, {
		config: fluidConfig,
		widgetRegistry: runtimeWidgetState.widgetRegistry,
		children: runtimeWidgetState.packageLoadSettled ? /* @__PURE__ */ jsx(PreviewRenderer, {
			widgetRegistry: runtimeWidgetState.widgetRegistry,
			onAuth: () => {},
			builderOrigin,
			skipReady: true
		}) : null
	});
}
//#endregion
export { createPreview };

//# sourceMappingURL=preview-entry.mjs.map