import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/modeler.css';
import 'reactflow/dist/style.css';

// Wait for Drupal to be ready
(function (Drupal) {
  // Store initial settings and Drupal object to prevent issues with window changes
  let storedSettings = null;
  let storedDrupal = null;

  // Register both behavior names for compatibility
  const behaviorConfig = {
    attach: function (context, settings) {
      // Look for either the form container or the wrapper container
      let container = context.querySelector('#workflow-modeler-react-root');
      if (!container) {
        container = context.querySelector('#workflow-modeler-wrapper');
      }

      if (container && !container.dataset.reactInitialized) {
        // Store settings and Drupal for each new container
        // Deep clone settings to prevent reference issues
        storedSettings = JSON.parse(JSON.stringify(settings));

        // Store reference to Drupal object
        storedDrupal = Drupal;

        container.dataset.reactInitialized = 'true';

        // Clear any existing content
        container.innerHTML = '';

        // Pass all stored settings and Drupal to the App
        // The modeler settings contain the actual model data and components
        const appSettings = {
          ...storedSettings,  // Include all settings
          modeler: storedSettings.modeler || {},
          modeler_api: storedSettings.modeler_api || {}
        };

        const root = ReactDOM.createRoot(container);
        root.render(
          <React.StrictMode>
            <App settings={appSettings} drupal={storedDrupal} />
          </React.StrictMode>
        );
      }
    }
  };

  // Register the Drupal behavior
  Drupal.behaviors.workflowModelerReact = behaviorConfig;
})(Drupal);
