import React, { Component, ReactNode } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { AuthProvider, useAuth } from "@/context/AuthContext";
import { LoginScreen } from "@/components/LoginScreen";
import { GLMLogo } from "@/components/GLMLogo";
import BoardPage from "./pages/BoardPage";
import { Toaster } from "@/components/ui/sonner";

// ─── Error Boundary ──────────────────────────────────────────────────────────

interface EBProps {
  children: ReactNode;
}
interface EBState {
  hasError: boolean;
}

class ErrorBoundary extends Component<EBProps, EBState> {
  constructor(props: EBProps) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error("Uncaught error:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex min-h-screen items-center justify-center bg-background px-4">
          <div className="max-w-md text-center">
            <h1 className="text-xl font-semibold tracking-tight text-foreground">
              Ocurrió un error al cargar el tablero.
            </h1>
            <p className="mt-2 text-sm text-muted-foreground">Intenta recargar la página.</p>
            <div className="mt-6">
              <button
                onClick={() => window.location.reload()}
                className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
              >
                Recargar
              </button>
            </div>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// ─── Auth Gate ───────────────────────────────────────────────────────────────

function AuthGate() {
  const { user, loading } = useAuth();

  if (loading && !user) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <div className="animate-pulse">
            <GLMLogo showWordmark={false} />
          </div>
          <p className="text-sm text-muted-foreground">Cargando tablero…</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return <LoginScreen />;
  }

  return (
    <Routes>
      <Route path="/*" element={<BoardPage />} />
    </Routes>
  );
}

// ─── App ─────────────────────────────────────────────────────────────────────

export function App() {
  return (
    <ErrorBoundary>
      <AuthProvider>
        <BrowserRouter basename="/tablero-cdc/">
          <AuthGate />
          <Toaster richColors position="top-right" />
        </BrowserRouter>
      </AuthProvider>
    </ErrorBoundary>
  );
}
