// Polyfill Promise.try (TC39 Stage 4) for pdfjs-dist v6 compatibility across all browser engines
if (typeof Promise.try !== 'function') {
  (Promise as any).try = function <T>(fn: (...args: any[]) => T, ...args: any[]): Promise<T> {
    return new Promise((resolve) => {
      resolve(fn(...args));
    });
  };
}

// Polyfill Promise.withResolvers (TC39 Stage 4) for iOS Safari < 17.4 and older mobile WebKit
if (typeof (Promise as any).withResolvers !== 'function') {
  (Promise as any).withResolvers = function <T>() {
    let resolve!: (value: T | PromiseLike<T>) => void;
    let reject!: (reason?: any) => void;
    const promise = new Promise<T>((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve, reject };
  };
}

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { GoogleOAuthProvider } from '@react-oauth/google';
import App from './App.tsx';
import './index.css';
import { initializeStorage } from './lib/storage';

import ErrorBoundary from './components/ErrorBoundary';

// Initialize storage bucket
initializeStorage().catch(console.error);

const googleClientId = import.meta.env.VITE_GOOGLE_CLIENT_ID || '';

const appContent = (
  <ErrorBoundary fallbackTitle="Application Error">
    <App />
  </ErrorBoundary>
);

const appTree = (
  <StrictMode>
    {googleClientId ? (
      <GoogleOAuthProvider clientId={googleClientId}>
        {appContent}
      </GoogleOAuthProvider>
    ) : (
      appContent
    )}
  </StrictMode>
);

createRoot(document.getElementById('root')!).render(appTree);

