import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import './gin.css'; // Import Gin CSS after index.css for overrides
import App from './App';

// Initialize the application
function initializeApp() {
  // Get the base URL from the data attributes
  // Try both the new ID and legacy ID to handle both
  let container = document.getElementById('jsonapi-query-builder-root');

  // Add safeguards against missing elements
  if (!container) {
    // Check if we need to fall back to the old ID
    const legacyContainer = document.getElementById('jsonapi-explorer-root');
    if (legacyContainer) {
      container = legacyContainer;
    } else {
      // If neither container exists, show an error
      if (document.body) {
        const errorDiv = document.createElement('div');
        errorDiv.style.color = 'red';
        errorDiv.style.padding = '20px';
        errorDiv.style.fontWeight = 'bold';
        errorDiv.textContent = 'Error: Could not initialize the JSON:API Query Builder application.';
        document.body.appendChild(errorDiv);
      }
      return; // Exit initialization
    }
  }

  // Safely get the base URL
  let baseUrl = '';
  try {
    baseUrl = container.getAttribute('data-base-url') || '';
  } catch (e) {
    baseUrl = '/jsonapi/'; // Default fallback
  }

  // If there's no trailing slash, add one
  if (baseUrl && !baseUrl.endsWith('/')) {
    baseUrl += '/';
  }

  // Create root and render app
  const root = createRoot(container);
  root.render(
    <React.StrictMode>
      <App baseUrl={baseUrl} />
    </React.StrictMode>
  );
}

// Call the initialization function
initializeApp();
