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

type MaxWebApp = {
  initData?: string;
  initDataUnsafe?: {
    user?: MaxMiniAppUser;
    start_param?: string;
  };
  ready?: () => void;
  close?: () => void;
  openLink?: (url: string) => void;
  openMaxLink?: (url: string) => void;
  platform?: string;
  version?: string;
};

declare global {
  interface Window {
    WebApp?: MaxWebApp;
  }
}

function buildDisplayName(user: MaxMiniAppUser | 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 useMaxMiniApp() {
  const webApp = computed<MaxWebApp | null>(() => {
    if (!import.meta.client) {
      return null;
    }

    return window.WebApp ?? null;
  });

  const initData = computed(() => String(webApp.value?.initData || '').trim());
  const user = computed<MaxMiniAppUser | 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,
  };
}
