"use client";

// What the website and the apps do differently. The web versions below are the defaults;
// the native bootstrap replaces them (native/services.ts). Screens call these instead of
// checking the platform.

export interface OpenExternalOptions {
    /** Android: open with this app only (a store), rather than a chooser. */
    package?: string;
    /** Opened instead when nothing can handle `url` (e.g. the store app is not installed). */
    fallbackUrl?: string;
}

export interface PlatformServices {
    /** Open a URL outside the app (new tab on web; browser or store app in the apps). False if nothing could. */
    openExternal(url: string, options?: OpenExternalOptions): Promise<boolean>;

    /** Go to a payment gateway. `returnTo`: where the apps land if the user comes back without a result. */
    startPayment(gatewayUrl: string, returnTo: string): Promise<void>;

    /** Extra headers sent with every API request. */
    requestHeaders(): Record<string, string>;

    /** This app's page in the system settings. False where there is none. */
    openAppSettings(): Promise<boolean>;

    /** This copy's store page, or the APK download for the website build. False on web. */
    openAppUpdatePage(): Promise<boolean>;

    /** Called when the user comes back to the app. Returns an unsubscribe function. */
    onResume(listener: () => void): () => void;
}

const NO_HEADERS: Record<string, string> = Object.freeze({}) as Record<string, string>;

const webServices: PlatformServices = {
    async openExternal(url) {
        window.open(url, "_blank", "noopener,noreferrer");
        return true;
    },

    async startPayment(gatewayUrl) {
        window.location.href = gatewayUrl;
    },

    requestHeaders() {
        return NO_HEADERS;
    },

    async openAppSettings() {
        return false;
    },

    async openAppUpdatePage() {
        return false;
    },

    onResume(listener) {
        const onVisible = () => {
            if (document.visibilityState === "visible") listener();
        };
        document.addEventListener("visibilitychange", onVisible);
        return () => document.removeEventListener("visibilitychange", onVisible);
    },
};

let services: PlatformServices = webServices;

export function getPlatformServices(): PlatformServices {
    return services;
}

/** Native bootstrap only. */
export function installPlatformServices(next: PlatformServices): void {
    services = next;
}
