import { decodeMessengerMiniAppStartParam } from '~/composables/useMessengerMiniAppStart';

export function useMessengerMiniApp() {
  const telegramMiniApp = useTelegramMiniApp();
  const maxMiniApp = useMaxMiniApp();

  const channel = computed<'TELEGRAM' | 'MAX' | null>(() => {
    if (maxMiniApp.isAvailable.value) {
      return 'MAX';
    }

    if (telegramMiniApp.isAvailable.value) {
      return 'TELEGRAM';
    }

    return null;
  });

  const isAvailable = computed(() => channel.value !== null);
  const initData = computed(() =>
    channel.value === 'MAX' ? maxMiniApp.initData.value : telegramMiniApp.initData.value,
  );
  const startParam = computed(() =>
    channel.value === 'MAX' ? maxMiniApp.startParam.value : telegramMiniApp.startParam.value,
  );
  const startPath = computed(() => decodeMessengerMiniAppStartParam(startParam.value));
  const displayName = computed(() =>
    channel.value === 'MAX' ? maxMiniApp.displayName.value : telegramMiniApp.displayName.value,
  );
  const channelLabel = computed(() =>
    channel.value === 'MAX' ? 'MAX' : channel.value === 'TELEGRAM' ? 'Telegram' : '',
  );

  return {
    channel,
    channelLabel,
    isAvailable,
    initData,
    startParam,
    startPath,
    displayName,
    telegramMiniApp,
    maxMiniApp,
  };
}
