import { RenderContext } from "./RenderContext.js";
import { DEFAULT_HEIGHT, DEFAULT_WIDTH } from "./previewTypes.js";
import { captureTimelineToDataUri } from "./rendering/serializeTimelineDirect.js";
import { getEffectiveRenderMode } from "./renderers.js";
import { loadImageFromDataUri } from "./rendering/loadImage.js";
import { renderToImageNative } from "./rendering/renderToImageNative.js";

//#region src/preview/renderElementToCanvas.ts
/**
* Render any element to canvas or image.
*
* This is a low-level rendering function that renders the element as-is.
* The caller is responsible for:
* - Creating clones if needed
* - Seeking to the correct time
* - Finding the correct element to render
*
* Use cases:
* - Preview: Pass prime timeline element (already at correct time)
* - Video/thumbnails: Pass element from reused clone (already seeked)
* - One-off capture: Create clone, seek, pass element, clean up
*
* @param element - Element to render (timegroup, temporal element, or plain DOM)
* @param options - Render options
* @returns Canvas or Image (both are CanvasImageSource)
*/
async function renderElementToCanvas(element, options) {
	return await renderElementToImage(element, options);
}
/**
* Render an element using either native or foreignObject mode.
* Returns Canvas or Image directly without unnecessary copying.
*/
async function renderElementToImage(element, options) {
	const { timeMs, scale = 1 } = options;
	const computedStyle = getComputedStyle(element);
	const width = options.width ?? (parseFloat(computedStyle.width) || DEFAULT_WIDTH);
	const height = options.height ?? (parseFloat(computedStyle.height) || DEFAULT_HEIGHT);
	const renderContext = options.renderContext ?? new RenderContext();
	const shouldDisposeContext = !options.renderContext;
	try {
		if ((options.renderMode ?? getEffectiveRenderMode()) === "native") {
			const elementContainer = document.createElement("div");
			elementContainer.style.cssText = `
        position: fixed;
        left: 0;
        top: 0;
        width: ${width}px;
        height: ${height}px;
        pointer-events: none;
        overflow: hidden;
      `;
			elementContainer.appendChild(element.cloneNode(true));
			document.body.appendChild(elementContainer);
			try {
				return await renderToImageNative(elementContainer, width, height, { skipDprScaling: true });
			} finally {
				elementContainer.remove();
			}
		} else return await loadImageFromDataUri(await captureTimelineToDataUri(element, width, height, {
			renderContext,
			canvasScale: scale,
			timeMs
		}));
	} finally {
		if (shouldDisposeContext) renderContext.dispose();
	}
}

//#endregion
export { renderElementToCanvas };
//# sourceMappingURL=renderElementToCanvas.js.map