"use client";

// Starts the native bootstrap. AuthProvider waits on platformReady() for the stored login.

let resolveNativeReady: () => void = () => { };
const nativeReady = new Promise<void>((resolve) => {
    resolveNativeReady = resolve;
});

/** Resolves once the platform layer is ready: at once on web, and also if the native bootstrap failed. */
export function platformReady(): Promise<void> {
    return process.env.NEXT_PUBLIC_APP_TARGET === "native" ? nativeReady : Promise.resolve();
}

let started = false;

/** Once per page, from ClientProviders. A no-op on web. */
export function bootPlatform(): void {
    // An if-block, not an early return, so webpack drops it from the website (target.ts).
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") {
        if (typeof window === "undefined" || started) return;
        started = true;

        import("./native/bootstrap")
            .then((native) => native.bootstrapNative())
            .catch((err) => {
                console.error("[platform] native bootstrap failed, continuing on web defaults:", err);
            })
            .finally(() => resolveNativeReady());
    }
}
