import type { PlatformAPI } from "./types";

export function createTgAPI(): PlatformAPI {
    const tg = (window as any).Telegram?.WebApp;
    tg?.ready?.();

    const colorScheme = (tg?.colorScheme === "dark") ? "dark" : "light";

    const safeAreaInsets = { top: 0, bottom: 0, left: 0, right: 0 };

    return {
        platform: "tg",
        colorScheme,
        safeAreaInsets,

        haptics: {
            impact: (style) => tg?.HapticFeedback?.impactOccurred?.(style),
            notify: (type) => tg?.HapticFeedback?.notificationOccurred?.(type)
        },

        navigation: {
            setBackHandler: (cb) => {
                if (!tg) return;
                if (cb) {
                    tg.BackButton.show();
                    tg.BackButton.onClick(cb);
                } else {
                    tg.BackButton.hide();
                }
            }
        },

        mainButton: {
            show: (text, onClick) => {
                if (!tg) return;
                tg.MainButton.setText(text);
                tg.MainButton.show();
                tg.MainButton.onClick(onClick);
            },
            hide: () => tg?.MainButton?.hide?.(),
            setLoading: (loading) => {
                if (!tg) return;
                loading ? tg.MainButton.showProgress() : tg.MainButton.hideProgress();
            }
        }
    };
}
