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

// Intercept global fetch to automatically inject authorization header
const originalFetch = window.fetch;
window.fetch = async function (input, init) {
  const url = typeof input === 'string' ? input : (input instanceof Request ? input.url : String(input));
  
  if (url.startsWith('/api/') && !url.startsWith('/api/login')) {
    const token = localStorage.getItem('sagiakos_session_token');
    if (token) {
      init = init || {};
      const headers = new Headers(init.headers || {});
      headers.set('Authorization', `Bearer ${token}`);
      init.headers = headers;
    }
  }

  const response = await originalFetch(input, init);

  if (response.status === 401 && url.startsWith('/api/') && !url.startsWith('/api/login')) {
    localStorage.removeItem('sagiakos_session_token');
    window.dispatchEvent(new Event('sagiakos_unauthorized'));
  }

  return response;
};

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