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 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) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <div className="w-9 h-9 rounded-xl bg-primary flex items-center justify-center animate-pulse">
            <svg className="w-4 h-4 text-primary-foreground" fill="none" viewBox="0 0 24 24">
              <rect x="3" y="3" width="7" height="7" rx="1" fill="currentColor" />
              <rect x="14" y="3" width="7" height="7" rx="1" fill="currentColor" opacity="0.5" />
              <rect x="3" y="14" width="7" height="7" rx="1" fill="currentColor" opacity="0.5" />
              <rect x="14" y="14" width="7" height="7" rx="1" fill="currentColor" />
            </svg>
          </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>
  );
}
