import type { PlatformAPI } from "./types";
import { detectPlatform } from "./detect";
import { createWebAPI } from "./web";
import { createVkAPI } from "./vk/vk";
import { createTgAPI } from "./tg";
import React, { createContext, useContext, useMemo } from "react";

const PlatformContext = createContext<PlatformAPI | null>(null);

export function PlatformProvider({ children }: { children: React.ReactNode }) {
    const api = useMemo(() => {
        const p = detectPlatform();
        if (p === "tg") return createTgAPI();
        if (p === "vk") return createVkAPI();
        return createWebAPI();
    }, []);

    // @ts-ignore
    return <PlatformContext.Provider value={api}>{children}</PlatformContext.Provider>;
}

export function usePlatform(): PlatformAPI {
    const ctx = useContext(PlatformContext);
    if (!ctx) throw new Error("usePlatform must be used within PlatformProvider");
    return ctx;
}
