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

/** يمنع الشاشة البيضاء: أي خطأ يظهر كرسالة مع زر إصلاح بدل صفحة فارغة */
class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { error: Error | null }> {
  state = { error: null as Error | null };
  static getDerivedStateFromError(error: Error) {
    return { error };
  }
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div dir="rtl" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f4efe2', padding: 24, fontFamily: 'system-ui, sans-serif' }}>
        <div style={{ maxWidth: 420, width: '100%', background: '#fff', border: '1px solid #e3dccb', borderRadius: 16, padding: 24, textAlign: 'center' }}>
          <h1 style={{ fontSize: 20, fontWeight: 800, marginBottom: 12 }}>حدث خطأ غير متوقع</h1>
          <p style={{ fontSize: 13, color: '#6b7a73', lineHeight: 1.9, marginBottom: 12, direction: 'ltr', wordBreak: 'break-word' }}>
            {String(this.state.error.message || this.state.error)}
          </p>
          <button
            type="button"
            onClick={() => location.reload()}
            style={{ width: '100%', padding: 12, borderRadius: 12, background: '#0f4a38', color: '#fff', fontWeight: 700, border: 0, marginBottom: 8 }}
          >
            إعادة التحميل
          </button>
          <button
            type="button"
            onClick={async () => {
              try {
                const regs = await navigator.serviceWorker?.getRegistrations?.();
                await Promise.all((regs || []).map((r) => r.unregister()));
                const keys = await caches?.keys?.();
                await Promise.all((keys || []).map((k) => caches.delete(k)));
              } catch { /* تجاهل */ }
              location.reload();
            }}
            style={{ width: '100%', padding: 12, borderRadius: 12, background: '#fff', color: '#0f4a38', fontWeight: 700, border: '1px solid #0f4a38' }}
          >
            مسح الكاش وإعادة التحميل (البيانات تبقى)
          </button>
        </div>
      </div>
    );
  }
}

createRoot(document.getElementById('root')!).render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>,
);
