import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ExportProvider } from './contexts/ExportContext';
import './index.css';

/**
 * Error Boundary for graceful error handling.
 */
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error?: Error }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('GetMD Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      const { i18n } = window.summixGetmdData || {};
      return (
        <div className="smx-p-6 smx-bg-red-50 smx-border smx-border-red-200 smx-rounded-md">
          <h2 className="smx-text-lg smx-font-semibold smx-text-red-800 smx-mb-2">
            {i18n?.somethingBroke || 'Something broke'}
          </h2>
          <p className="smx-text-sm smx-text-red-700">
            {this.state.error?.message || (i18n?.errorDesc || "GetMD couldn't load. This is usually temporary.")}
          </p>
          <button
            onClick={() => window.location.reload()}
            className="smx-mt-4 smx-px-4 smx-py-2 smx-bg-red-600 smx-text-white smx-rounded smx-text-sm hover:smx-bg-red-700"
          >
            {i18n?.reload || 'Reload'}
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

/**
 * Initialize the React application.
 */
const initApp = () => {
  const root = document.getElementById('summix-getmd-export-root');

  if (root) {
    // Set RTL direction if WordPress is in RTL mode
    if (window.summixGetmdData?.isRtl) {
      root.setAttribute('dir', 'rtl');
    }

    ReactDOM.createRoot(root).render(
      <React.StrictMode>
        <ErrorBoundary>
          <ExportProvider>
            <App />
          </ExportProvider>
        </ErrorBoundary>
      </React.StrictMode>
    );
  } else {
    console.error('GetMD: Mount point #summix-getmd-export-root not found');
  }
};

// Initialize after DOM is ready to prevent race conditions
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initApp);
} else {
  initApp();
}
