import type { View } from '$foliate/view.js';

let pending: Promise<void> | undefined;

/**
 * Loads foliate-js and registers its custom elements.
 *
 * view.js calls customElements.define() at module scope and subclasses
 * HTMLElement, and its class fields construct DOM helpers eagerly — so importing
 * it on the server throws. This module is safe to import anywhere because it
 * touches nothing at module scope; the vendored code is only pulled in when
 * loadFoliate() is called, which must be from onMount or a browser guard.
 *
 * The promise is cached so concurrent callers share one load. ESM already dedupes
 * module evaluation; this mainly makes the "define runs once" contract explicit.
 * Editing a file under src/lib/vendor invalidates the module and re-runs
 * customElements.define, which throws — hard-refresh after re-vendoring.
 */
export function loadFoliate(): Promise<void> {
	return (pending ??= import('$foliate/view.js').then(() => undefined));
}

/**
 * Creates a <foliate-view>. Call only after loadFoliate() has resolved.
 *
 * Built imperatively rather than written in markup so SSR never emits an unknown
 * element for Svelte to hydrate, and so svelte-check has no unknown attributes to
 * complain about.
 */
export function createFoliateView(): View {
	return document.createElement('foliate-view') as View;
}
