"use client";

import { useSyncExternalStore } from "react";
import { APP_VERSION, BUILD_ID } from "@/constants/version.constant";
import { APP_TARGET, type AppTarget } from "./target";
import type { DistributionChannel } from "./channels";

export type RuntimePlatform = "web" | "android" | "ios";

/** The installed binary. Only exists inside the native shells. */
export interface NativeBinaryInfo {
    applicationId: string;
    /** versionName / CFBundleShortVersionString, e.g. "2.4.0". */
    version: string;
    /** versionCode / CFBundleVersion; what update checks compare. */
    build: number;
}

export interface AppInfo {
    target: AppTarget;
    platform: RuntimePlatform;
    channel: DistributionChannel;
    /** Version of the web code (NEXT_PUBLIC_APP_VERSION). */
    webVersion: string;
    webBuildId: string;
    native: NativeBinaryInfo | null;
    /** Native only: how logins from this device are labelled (device_name). */
    deviceName?: string;
}

// What the static export was prerendered with, and so what hydration must see.
const PRERENDERED: AppInfo = {
    target: APP_TARGET,
    platform: "web",
    channel: APP_TARGET === "web" ? "web" : "unknown",
    webVersion: APP_VERSION,
    webBuildId: BUILD_ID,
    native: null,
};

// Provisional in the apps until the native bootstrap asks the binary.
let current: AppInfo = { ...PRERENDERED, platform: detectRuntimePlatform() };

const listeners = new Set<() => void>();

export function getAppInfo(): AppInfo {
    return current;
}

/** Native bootstrap only. */
export function setAppInfo(next: AppInfo): void {
    current = next;
    listeners.forEach((listener) => listener());
}

export function subscribeAppInfo(listener: () => void): () => void {
    listeners.add(listener);
    return () => { listeners.delete(listener); };
}

/** AppInfo as React state: re-renders once the native bootstrap fills it in. */
export function useAppInfo(): AppInfo {
    return useSyncExternalStore(subscribeAppInfo, getAppInfo, () => PRERENDERED);
}

/** From the bridge Capacitor injects; not @capacitor/core, which would pull Capacitor into the website. */
function detectRuntimePlatform(): RuntimePlatform {
    if (process.env.NEXT_PUBLIC_APP_TARGET !== "native") return "web";
    if (typeof window === "undefined") return "web";

    const platform = (window as { Capacitor?: { getPlatform?: () => string } }).Capacitor?.getPlatform?.();
    return platform === "android" || platform === "ios" ? platform : "web";
}

/** True inside the Android/iOS app -- not merely a native build opened in a browser. */
export function isNativeRuntime(): boolean {
    return getAppInfo().platform !== "web";
}
