import React from 'react';
import { createPortal } from 'react-dom';

export function MathLiveLoadingOverlay({ children }: { children: React.ReactNode }) {
  const overlay = (
    <div
      className="fixed right-4 bottom-4 z-[190] rounded-md border bg-background px-3 py-2 text-sm shadow-lg"
      data-testid="mathlive-loading-overlay"
    >
      {children}
    </div>
  );
  return typeof document === 'undefined' ? overlay : createPortal(overlay, document.body);
}

/**
 * MathLive is an enhancement to the canonical `.tex` document, never an app
 * authority. Dynamic-import/custom-element failures stay local to the math UI
 * so neither Source nor Visual can be blanked by the application ErrorBoundary.
 */
export class MathLiveLocalBoundary extends React.Component<
  { children: React.ReactNode; onClose: () => void; sourceFallback?: string },
  { failed: boolean }
> {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  componentDidCatch(error: unknown) {
    console.error('MathLive editor unavailable', error);
  }

  render() {
    if (!this.state.failed) return this.props.children;
    const fallback = (
      <div
        className="fixed right-4 bottom-4 z-[190] max-w-md rounded-lg border bg-background p-3 text-sm shadow-xl"
        role="alert"
        data-testid="mathlive-local-fallback"
      >
        <div className="font-medium">Equation editor unavailable</div>
        <p className="mt-1 text-muted-foreground">
          The canonical LaTeX source was not changed. You can continue editing in Source mode.
        </p>
        {this.props.sourceFallback && (
          <code className="mt-2 block max-h-24 overflow-auto rounded bg-muted p-2 text-xs">
            {this.props.sourceFallback}
          </code>
        )}
        <button
          type="button"
          className="mt-3 rounded-md border px-2 py-1 text-xs hover:bg-muted"
          onClick={this.props.onClose}
        >
          Close
        </button>
      </div>
    );
    return typeof document === 'undefined' ? fallback : createPortal(fallback, document.body);
  }
}
