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

// Attach the verified SCC session token to every same-origin /api call (the server now rejects
// anything without one and ignores any client-claimed admin identity header).
const _origFetch = window.fetch.bind(window);
window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
  try {
    const url = typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request).url;
    const isApi = url.startsWith('/api/') || url.startsWith('/scc/') || url.startsWith(window.location.origin + '/api/');
    const token = localStorage.getItem('scc_session_token') || sessionStorage.getItem('scc_session_token');
    if (isApi && token) {
      const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined));
      if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`);
      return _origFetch(input, { ...init, headers });
    }
  } catch { /* fall through to plain fetch */ }
  return _origFetch(input, init);
};

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