export type Unsubscribe = () => void;

export function tgBackButtonBind(onBack: () => void): Unsubscribe {
    const tg = (window as any).Telegram?.WebApp;
    if (!tg?.BackButton) return () => {};

    const handler = () => onBack();
    tg.BackButton.onClick(handler);
    tg.BackButton.show();

    return () => {
        tg.BackButton.offClick(handler);
        tg.BackButton.hide();
    };
}

export function tmaBackButtonBind(onBack: () => void): Unsubscribe {
    try {
        const { backButton } = require("@tma.js/sdk");
        backButton.mount();
        const off = backButton.onClick(onBack);
        backButton.show();
        return () => {
            off?.();
            backButton.hide();
            backButton.unmount();
        };
    } catch {
        return () => {};
    }
}
