import { Buffer } from 'buffer';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

if (typeof window !== 'undefined') {
  (window as any).Buffer = (window as any).Buffer || Buffer;
  (window as any).global = (window as any).global || window;

  // Global fetch interceptor to automatically attach JWT Bearer token to all /api/ requests
  const originalFetch = window.fetch;
  window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
    try {
      const url = typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request).url;
      if (url && (url.startsWith('/api/') || url.includes('/api/')) && !url.includes('/api/auth/')) {
        const token = localStorage.getItem('sso_token');
        if (token) {
          init = init || {};
          const headers = new Headers(init.headers || {});
          if (!headers.has('Authorization')) {
            headers.set('Authorization', `Bearer ${token}`);
          }
          init.headers = headers;
        }
      }
    } catch {
      // Fallback to original fetch if url parsing fails
    }
    return originalFetch(input, init);
  };
}
if (typeof globalThis !== 'undefined') {
  (globalThis as any).Buffer = (globalThis as any).Buffer || Buffer;
}

createRoot(document.getElementById('root')!).render(<App />);
