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

const originalFetch = window.fetch;
Object.defineProperty(window, 'fetch', {
  value: async function (input: RequestInfo | URL, init?: RequestInit) {
    const url = typeof input === 'string' ? input : (input instanceof Request ? input.url : '');
    
    if (url && url.toString().includes('/api/')) {
      const localSessionId = localStorage.getItem("lucia_session_id");
      if (localSessionId) {
        if (!init) init = {};
        if (!init.headers) init.headers = {};
        
        const headers = new Headers(init.headers);
        if (!headers.has("Authorization")) {
          headers.set("Authorization", `Bearer ${localSessionId}`);
        }
        if (!headers.has("X-Session-ID")) {
          headers.set("X-Session-ID", localSessionId);
        }
        
        init.headers = headers;
      }
    }
    
    return originalFetch.call(this, input, init as RequestInit);
  },
  writable: true,
  configurable: true,
});

// Bulletproof monkey patch Response.prototype.json to gracefully handle the Vite/Express HTML 502 response
// and prevent "Unexpected token '<', "<!doctype "... is not valid JSON" crashes across all frontend components.
const originalJson = Response.prototype.json;
Response.prototype.json = async function () {
  try {
    const text = await this.clone().text();
    // Quick check if it's an HTML doc before attempting to parse
    if (text.trim().toLowerCase().startsWith('<!doctype html>') || text.trim().toLowerCase().startsWith('<html')) {
      console.warn(`[Fetch Workaround] Intercepted HTML document instead of JSON for URL: ${this.url}. Returning safe error boundary object.`);
      if (!this.ok) return { error: "Server returned HTML (e.g. 502/503 gateway timeout or offline)" };
    }
    return JSON.parse(text);
  } catch (e: any) {
    if (e.name === 'AbortError' || e.message?.includes('aborted')) {
      throw e; // Rethrow AbortError directly
    }
    console.error("[Fetch JSON Parse Error] URL:", this.url, "Error:", e.message);
    throw new Error(`Invalid JSON response: ${e.message}`);
  }
};

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ThemeProvider defaultTheme="dark" storageKey="nexus-theme">
      <App />
    </ThemeProvider>
  </StrictMode>,
);
