import React from 'react';
import ReactDOM from 'react-dom/client';
import AdminApp from './AdminApp';

class AdminErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

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

  componentDidCatch(error, errorInfo) {
    console.error('CRITICAL ADMIN PANEL ERROR CAUGHT BY BOUNDARY:', error, errorInfo);
    this.setState({ errorInfo });
  }

  handleResetAndReload = () => {
    try {
      localStorage.removeItem('sap_admin_header_footer_v1');
      localStorage.removeItem('sap_admin_theme_colors_v1');
      localStorage.removeItem('sap_admin_services_detail_v1');
    } catch (e) {}
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div
          style={{
            minHeight: '100vh',
            width: '100vw',
            background: '#060810',
            color: '#f1f5f9',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '24px',
            boxSizing: 'border-box',
            fontFamily: "'Nunito Sans', sans-serif"
          }}
        >
          <div
            style={{
              maxWidth: '680px',
              width: '100%',
              background: 'rgba(23, 14, 20, 0.95)',
              border: '1px solid rgba(244, 63, 94, 0.4)',
              borderRadius: '16px',
              padding: '32px',
              boxShadow: '0 25px 60px rgba(0, 0, 0, 0.7)'
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
              <span style={{ fontSize: '28px' }}>⚠️</span>
              <div>
                <h2 style={{ margin: 0, fontSize: '22px', color: '#ff6b6b' }}>
                  Admin Panel Diagnostics &amp; Recovery
                </h2>
                <p style={{ margin: '4px 0 0', fontSize: '13px', color: '#94a3b8' }}>
                  A component error was caught. Use the recovery action below to reset corrupted local state.
                </p>
              </div>
            </div>

            <div
              style={{
                background: '#090d18',
                border: '1px solid rgba(255, 255, 255, 0.1)',
                borderRadius: '8px',
                padding: '16px',
                color: '#fca5a5',
                fontSize: '12.5px',
                fontFamily: 'monospace',
                overflowX: 'auto',
                whiteSpace: 'pre-wrap',
                maxHeight: '220px',
                marginBottom: '20px'
              }}
            >
              {this.state.error?.toString()}
              {this.state.errorInfo?.componentStack}
            </div>

            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
              <button
                onClick={this.handleResetAndReload}
                style={{
                  background: 'linear-gradient(135deg, #fe7a0e, #ea580c)',
                  color: '#fff',
                  border: 'none',
                  borderRadius: '8px',
                  padding: '10px 20px',
                  fontWeight: 700,
                  fontSize: '13.5px',
                  cursor: 'pointer'
                }}
              >
                🔄 Reset Admin Storage &amp; Reload
              </button>

              <button
                onClick={() => { window.location.href = '/'; }}
                style={{
                  background: 'rgba(255, 255, 255, 0.1)',
                  color: '#fff',
                  border: '1px solid rgba(255, 255, 255, 0.2)',
                  borderRadius: '8px',
                  padding: '10px 20px',
                  fontWeight: 600,
                  fontSize: '13.5px',
                  cursor: 'pointer'
                }}
              >
                ← Return to Live Website
              </button>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootElement = document.getElementById('admin-root');
if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <AdminErrorBoundary>
        <AdminApp onExitAdmin={() => { window.location.href = '/'; }} />
      </AdminErrorBoundary>
    </React.StrictMode>
  );
} else {
  console.error('CRITICAL: #admin-root element not found in DOM.');
}
