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

import { initializeSupabase } from './supabaseClient'

// Global fetch interceptor to append custom Gemini API Key header if available
const originalFetch = window.fetch;
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
  const customKey = localStorage.getItem('sandbox_gemini_api_key');
  if (customKey) {
    const urlStr = typeof input === 'string'
      ? input
      : 'url' in input
        ? (input as any).url
        : input.toString();
    if (urlStr && urlStr.includes('/api/')) {
      const newInit = init ? { ...init } : {};
      const headers = new Headers(newInit.headers || {});
      headers.set('X-Gemini-API-Key', customKey);
      newInit.headers = headers;
      return originalFetch(input, newInit);
    }
  }
  return originalFetch(input, init);
};

async function init() {
  try {
    const apiBase = import.meta.env.VITE_API_BASE_URL || '';
    const res = await fetch(`${apiBase}/api/config`);
    if (!res.ok) throw new Error("Failed to load runtime configuration");
    const config = await res.json();
    initializeSupabase(config.supabaseUrl, config.supabaseAnonKey);
  } catch (err) {
    console.error("Failed to load config from API, falling back to build environment:", err);
    const url = import.meta.env.VITE_SUPABASE_URL || '';
    const key = import.meta.env.VITE_SUPABASE_ANON_KEY || '';
    initializeSupabase(url, key);
  }

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

init();
