import React, { Component, ErrorInfo, ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

interface ErrorBoundaryProps {
  children: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
  errorInfo?: ErrorInfo;
}

class RootErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('IPTVSMRT Application Runtime Error:', error, errorInfo);
    this.setState({ errorInfo });
  }

  render() {
    if (this.state.hasError) {
      const errorMsg = this.state.error?.message || 'Unknown runtime error';
      const errorStack = this.state.error?.stack || this.state.errorInfo?.componentStack || '';

      return (
        <div style={{
          minHeight: '100vh',
          backgroundColor: '#07111F',
          color: '#ffffff',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '24px',
          fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          textAlign: 'center',
          boxSizing: 'border-box'
        }}>
          <div style={{
            maxWidth: '640px',
            width: '100%',
            backgroundColor: '#0F1E33',
            border: '1px solid #1E293B',
            borderRadius: '16px',
            padding: '32px',
            boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.5)'
          }}>
            <h1 style={{ fontSize: '24px', fontWeight: '800', marginBottom: '8px', color: '#FACC15' }}>
              IPTVSMRT.COM
            </h1>
            <h2 style={{ fontSize: '18px', fontWeight: '700', marginBottom: '16px', color: '#F87171' }}>
              Application Diagnostics
            </h2>
            <p style={{ color: '#94A3B8', fontSize: '14px', marginBottom: '20px', lineHeight: '1.6' }}>
              A client runtime error was intercepted. Below is the diagnostic trace:
            </p>

            <div style={{
              backgroundColor: '#020617',
              border: '1px solid #334155',
              borderRadius: '8px',
              padding: '12px',
              marginBottom: '20px',
              textAlign: 'left',
              overflowX: 'auto'
            }}>
              <div style={{ color: '#EF4444', fontWeight: 'bold', fontSize: '13px', marginBottom: '6px' }}>
                {errorMsg}
              </div>
              {errorStack && (
                <pre style={{
                  color: '#64748B',
                  fontSize: '11px',
                  fontFamily: 'monospace',
                  margin: 0,
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-word',
                  maxHeight: '160px',
                  overflowY: 'auto'
                }}>
                  {errorStack}
                </pre>
              )}
            </div>

            <div style={{ display: 'flex', gap: '12px', justifyContent: 'center', flexWrap: 'wrap' }}>
              <button
                onClick={() => window.location.reload()}
                style={{
                  backgroundColor: '#FACC15',
                  color: '#020617',
                  border: 'none',
                  padding: '10px 20px',
                  borderRadius: '10px',
                  fontWeight: 'bold',
                  cursor: 'pointer',
                  fontSize: '13px'
                }}
              >
                Reload Page
              </button>

              <button
                onClick={() => {
                  window.location.href = '/';
                }}
                style={{
                  backgroundColor: '#1E293B',
                  color: '#F1F5F9',
                  border: '1px solid #475569',
                  padding: '10px 20px',
                  borderRadius: '10px',
                  fontWeight: 'bold',
                  cursor: 'pointer',
                  fontSize: '13px'
                }}
              >
                Return to Homepage
              </button>
            </div>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// Resilient Mounting Logic: ensure #root always exists
let rootElement = document.getElementById('root');
if (!rootElement) {
  console.warn("Target #root element was not found in HTML. Creating fallback #root container.");
  rootElement = document.createElement('div');
  rootElement.id = 'root';
  document.body.appendChild(rootElement);
}

try {
  createRoot(rootElement).render(
    <RootErrorBoundary>
      <App />
    </RootErrorBoundary>
  );
  (window as unknown as { __IPTVSMRT_MOUNTED__?: boolean }).__IPTVSMRT_MOUNTED__ = true;
} catch (err: unknown) {
  console.error("Fatal Root Mount Error:", err);
  if (rootElement) {
    rootElement.innerHTML = `
      <div style="min-height:100vh;background:#07111F;color:#ffffff;display:flex;align-items:center;justify-content:center;padding:24px;font-family:sans-serif;text-align:center;">
        <div style="max-width:500px;background:#0F1E33;padding:24px;border-radius:12px;border:1px solid #1E293B;">
          <h1 style="color:#FACC15;font-size:22px;margin-bottom:8px;">IPTVSMRT Initialization Error</h1>
          <p style="color:#F87171;font-size:14px;margin-bottom:16px;">${(err as Error)?.message || 'Failed to mount React'}</p>
          <button onclick="window.location.reload()" style="background:#FACC15;color:#000;border:none;padding:8px 16px;border-radius:8px;font-weight:bold;cursor:pointer;">Retry</button>
        </div>
      </div>
    `;
  }
}
