type TelegramMiniAppUser = {
  id: number | string;
  first_name?: string;
  last_name?: string;
  username?: string;
  language_code?: string;
  photo_url?: string;
};

type TelegramWebApp = {
  initData?: string;
  initDataUnsafe?: {
    user?: TelegramMiniAppUser;
    start_param?: string;
  };
  ready?: () => void;
  expand?: () => void;
};

declare global {
  interface Window {
    Telegram?: {
      WebApp?: TelegramWebApp;
    };
  }
}

function buildDisplayName(user: TelegramMiniAppUser | null) {
  if (!user) {
    return '';
  }

  const firstName = String(user.first_name || '').trim();
  const lastName = String(user.last_name || '').trim();
  return `${firstName} ${lastName}`.trim() || firstName || String(user.username || '').trim();
}

export function useTelegramMiniApp() {
  const webApp = computed<TelegramWebApp | null>(() => {
    if (!import.meta.client) {
      return null;
    }

    return window.Telegram?.WebApp ?? null;
  });

  const initData = computed(() => String(webApp.value?.initData || '').trim());
  const user = computed<TelegramMiniAppUser | null>(() => webApp.value?.initDataUnsafe?.user ?? null);
  const startParam = computed(() => String(webApp.value?.initDataUnsafe?.start_param || '').trim());
  const isAvailable = computed(() => Boolean(initData.value));
  const displayName = computed(() => buildDisplayName(user.value));

  return {
    webApp,
    initData,
    user,
    startParam,
    isAvailable,
    displayName,
  };
}
