/**
 * ProRank SEO Editor Meta Box Entry Point
 *
 * This file uses window.wp.* directly instead of ES module imports to avoid
 * timing issues where the shim evaluates before WordPress scripts initialize.
 *
 * Runtime hardened for 2025 - includes createRoot fallback and error handling.
 *
 * @package
 */

// Import styles first (no dependencies)
import './styles.css';

/**
 * Ensure React globals are available
 * Some WP setups may not expose these globally
 */
const ensureReactGlobals = () => {
  if (typeof window === 'undefined') return;

  // Ensure React is available globally
  if (!window.React && window.wp?.element) {
    window.React = window.wp.element;
  }

  // Ensure ReactDOM is available globally
  if (!window.ReactDOM && window.wp?.element?.createRoot) {
    window.ReactDOM = { createRoot: window.wp.element.createRoot };
  }

  // Polyfill createRoot for older WP versions using ReactDOM.render
  if (window.wp?.element && !window.wp.element.createRoot && window.ReactDOM) {
    if (window.ReactDOM.createRoot) {
      window.wp.element.createRoot = window.ReactDOM.createRoot;
    } else if (window.ReactDOM.render) {
      // Fallback to legacy ReactDOM.render API
      window.wp.element.createRoot = function(container) {
        return {
          render: function(element) {
            return window.ReactDOM.render(element, container);
          },
          unmount: function() {
            return window.ReactDOM.unmountComponentAtNode(container);
          }
        };
      };
    }
  }
};

/**
 * Show error notice in WordPress admin
 */
const showErrorNotice = (container, message) => {
  if (!container) return;

  container.innerHTML = `
    <div style="padding: 16px; background: #fff3cd; border-left: 4px solid #ffc107; margin: 10px 0;">
      <p style="margin: 0; color: #856404;">
        <strong>ProRank SEO:</strong> ${message}
      </p>
      <p style="margin: 8px 0 0; font-size: 12px; color: #666;">
        Try refreshing the page. If the problem persists, check the browser console for details.
      </p>
    </div>
  `;
};

/**
 * Wait for WordPress to be fully initialized
 * Checks for wp.components.TabPanel and wp.element.createRoot (or fallback)
 */
const waitForWordPress = (callback, maxAttempts = 50) => {
  let attempts = 0;

  const check = () => {
    attempts++;

    // Ensure React globals on each check
    ensureReactGlobals();

    // Check if all required WordPress APIs are available
    const hasComponents = window.wp?.components?.TabPanel;
    const hasElement = window.wp?.element?.createRoot || window.wp?.element?.render;
    const hasI18n = window.wp?.i18n?.__;

    if (hasComponents && hasElement && hasI18n) {
      callback();
      return;
    }

    if (attempts < maxAttempts) {
      setTimeout(check, 100);
    } else {
      console.warn('[ProRank SEO] WordPress not fully initialized after timeout');
      const container = document.getElementById('prorank-seo-metabox-root');
      showErrorNotice(container, 'SEO meta box requires WordPress components. Please refresh the page.');
    }
  };

  check();
};

/**
 * Initialize the meta box
 * Uses window.wp.* directly to avoid ES module timing issues
 */
const initMetaBox = () => {
  const wpElement = window.wp.element;
  const { Component, createElement, lazy, Suspense } = wpElement;
  const { __ = (text) => text } = window.wp?.i18n || {};
  const { Spinner } = window.wp.components;

  // Get createRoot (either native or polyfilled)
  const createRoot = wpElement.createRoot;

  const metaBoxContainer = document.getElementById('prorank-seo-metabox-root');
  if (!metaBoxContainer) return;

  // Verify createRoot is available
  if (!createRoot) {
    showErrorNotice(metaBoxContainer, 'React rendering not available. Your WordPress version may not be supported.');
    return;
  }

  // Error boundary component
  class MetaBoxErrorBoundary extends Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false, errorMessage: '' };
    }

    static getDerivedStateFromError(error) {
      return { hasError: true, errorMessage: error?.message || 'Unknown error' };
    }

    componentDidCatch(error, errorInfo) {
      console.warn('[ProRank SEO] Meta box error:', error?.message || error);
      console.warn('[ProRank SEO] Component stack:', errorInfo?.componentStack);
    }

    render() {
      if (this.state.hasError) {
        return createElement('div', {
          style: {
            padding: '16px',
            background: '#fff3cd',
            borderLeft: '4px solid #ffc107',
            margin: '10px 0'
          }
        },
          createElement('p', { style: { margin: 0, color: '#856404' } },
            createElement('strong', null, 'ProRank SEO: '),
            __('SEO meta box encountered an error.', 'prorank-seo')
          ),
          createElement('p', { style: { margin: '8px 0 0', fontSize: '12px', color: '#666' } },
            __('Try refreshing the page. Check the browser console for details.', 'prorank-seo')
          )
        );
      }
      return this.props.children;
    }
  }

  // Loading fallback
  const LoadingFallback = createElement('div', {
    style: { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px', gap: '10px' }
  },
    Spinner && createElement(Spinner, null),
    createElement('span', null, __('Loading...', 'prorank-seo'))
  );

  // Lazy load MetaBoxShell with error catching
  const MetaBoxShell = lazy(() =>
    import(/* webpackMode: "eager" */ './MetaBoxShell.jsx').catch(err => {
      console.error('[ProRank SEO] Failed to load MetaBoxShell:', err);
      // Return a fallback module that renders an error
      return {
        default: () => createElement('div', {
          style: { padding: '16px', color: '#856404', background: '#fff3cd', borderLeft: '4px solid #ffc107' }
        },
          createElement('p', { style: { margin: 0 } },
            createElement('strong', null, 'ProRank SEO: '),
            __('Failed to load SEO meta box. Please refresh the page.', 'prorank-seo')
          )
        )
      };
    })
  );

  // Render with error boundary and suspense
  try {
    const root = createRoot(metaBoxContainer);
    root.render(
      createElement(MetaBoxErrorBoundary, null,
        createElement(Suspense, { fallback: LoadingFallback },
          createElement(MetaBoxShell, null)
        )
      )
    );
  } catch (renderError) {
    console.error('[ProRank SEO] Failed to render meta box:', renderError);
    showErrorNotice(metaBoxContainer, 'Failed to initialize SEO meta box. Please refresh the page.');
  }
};

// Start initialization when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    waitForWordPress(initMetaBox);
  });
} else {
  waitForWordPress(initMetaBox);
}
