import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { storage } from './firebase'; 

// Expose a clean upload handler to the global window object.
(window as any).uploadFileToStorage = async (file: File): Promise<string | null> => {
  try {
    // 1. Attempt the official live Firebase Storage stream
    const storageRef = ref(storage, `intake_records/${Date.now()}_${file.name}`);
    const snapshot = await uploadBytes(storageRef, file);
    
    // Returns the lightweight secure text URL string back to the form field
    return await getDownloadURL(snapshot.ref);
  } catch (error: any) {
    console.error("Firebase Storage Bridge Upload Error:", error);
    
    // --- SANDBOX PREVIEW FALLBACK ---
    // If the temporary AI Studio test bucket blocks us with a permission error,
    // generate a local browser pointer so the form submission can still be fully tested!
    if (error.code === 'storage/unauthorized' || error.message?.includes('unauthorized')) {
      console.warn("Sandbox security rules active. Swapping to local Object URL for preview testing.");
      
      // Creates a temporary text string pointer (blob:http://...) representing the file
      const localTestUrl = URL.createObjectURL(file);
      return localTestUrl;
    }
    
    return null;
  }
};

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