/* eslint-disable sonarjs/function-return-type */
'use client';

import { useClientOnce, useDidMount } from '@/hooks/telegram';
import { setLocale } from '@/utils/i18n/locale';
import { init } from '@/utils/telegram/init';
import { initData, useSignal } from '@telegram-apps/sdk-react';
import { type PropsWithChildren, useEffect } from 'react';

export function TelegramProvider(props: Readonly<PropsWithChildren>) {
  // Unfortunately, Telegram Mini Apps does not allow us to use all features of
  // the Server Side Rendering. That's why we are showing loader on the server
  // side.
  const didMount = useDidMount();

  if (!didMount) return <div>Loading</div>;

  return <RootInner {...props} />;
}

function RootInner({ children }: PropsWithChildren) {
  const isDevelopment = process.env.NODE_ENV === 'development';

  const debug = isDevelopment;

  // Initialize the library.
  useClientOnce(() => {
    init(debug);
  });

  const initDataUser = useSignal(initData.user);

  // Set the user locale.
  useEffect(() => {
    if (initDataUser) setLocale(initDataUser.languageCode);
  }, [initDataUser]);

  return children;
}
