import { Component, StrictMode, type ErrorInfo, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";

class AppErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
  state: { error: Error | null } = { error: null };

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error("Application render error:", error, info);
  }

  render() {
    if (this.state.error) {
      return (
        <div dir="rtl" style={{
          minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
          padding: "24px", background: "#05070d", color: "#fff", fontFamily: "Tahoma, sans-serif"
        }}>
          <div style={{
            width: "min(720px, 100%)", border: "1px solid rgba(248,113,113,.35)",
            borderRadius: "18px", padding: "24px", background: "#111827",
            boxShadow: "0 20px 60px rgba(0,0,0,.35)"
          }}>
            <h1 style={{ margin: "0 0 12px", fontSize: "22px" }}>خطا در اجرای برنامه</h1>
            <p style={{ margin: "0 0 14px", color: "#cbd5e1", lineHeight: 1.8 }}>
              خطای اجرای رابط کاربری شناسایی شد. برنامه را ببندید و دوباره اجرا کنید.
            </p>
            <pre style={{
              whiteSpace: "pre-wrap", direction: "ltr", textAlign: "left", margin: 0,
              padding: "14px", borderRadius: "12px", background: "#020617",
              color: "#fca5a5", overflow: "auto"
            }}>
              {this.state.error.message || String(this.state.error)}
            </pre>
            <button type="button" onClick={() => window.location.reload()} style={{
              marginTop: "16px", border: 0, borderRadius: "10px", padding: "10px 16px",
              background: "#2563eb", color: "#fff", cursor: "pointer"
            }}>
              تلاش دوباره
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  </StrictMode>
);
