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

// Parche global para interceptar fetch y agregar el token CSRF de Laravel y Accept JSON
const originalFetch = window.fetch;
window.fetch = async function (...args) {
  let [resource, config] = args;
  if (!config) config = {};
  
  config.credentials = 'same-origin';

  if (typeof resource === 'string' && resource.startsWith('/api')) {
    const match = document.cookie.match(new RegExp('(^| )XSRF-TOKEN=([^;]+)'));
    if (match) {
      const token = decodeURIComponent(match[2]);
      const headers = new Headers(config.headers || {});
      headers.set('X-XSRF-TOKEN', token);
      if (!headers.has('Accept')) headers.set('Accept', 'application/json');
      config.headers = headers;
    }
  }
  
  return originalFetch(resource, config);
};

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