import { StrictMode, Component } from "react";
import { createRoot } from "react-dom/client";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./lib/queryClient.js";
import "./lib/icons.jsx";
import "./index.css";
import App from "./App.jsx";
import { Fa } from "./lib/icons.jsx";

class ErrorBoundary extends Component {
  state = { error: null };

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

  componentDidCatch(error, info) {
    console.error("[V2X Pulse] Render crash:", error, info?.componentStack);
  }

  render() {
    if (this.state.error) {
      return (
        <div style={{
          minHeight: "100vh", background: "#F3F2EF",
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: 24, fontFamily: "'Space Grotesk', sans-serif",
        }}>
          <div style={{ maxWidth: 480, textAlign: "center" }}>
            <div style={{
              width: 52, height: 52, borderRadius: 16, margin: "0 auto 20px",
              background: "rgba(220,38,38,0.08)", border: "1px solid rgba(220,38,38,0.22)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <Fa c="fa-solid fa-triangle-exclamation" style={{ color: "#DC2626", fontSize: 20 }} />
            </div>
            <div style={{ fontSize: 15, fontWeight: 700, color: "#191919", marginBottom: 10 }}>
              Application Error
            </div>
            <div style={{
              fontSize: 12, color: "#666666", fontFamily: "'Space Mono', monospace",
              background: "#FFFFFF", border: "1px solid #E0E0E0",
              borderRadius: 8, padding: "12px 16px", marginBottom: 20,
              textAlign: "left", wordBreak: "break-word",
            }}>
              {this.state.error?.message || String(this.state.error)}
            </div>
            <button
              onClick={() => window.location.reload()}
              style={{
                background: "#0A66C2",
                color: "#fff", border: "none", borderRadius: 24,
                padding: "11px 28px", cursor: "pointer",
                fontFamily: "'Space Grotesk', sans-serif", fontSize: 14, fontWeight: 700,
              }}
            >
              Reload Application
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </QueryClientProvider>
  </StrictMode>
);
