"use client";

import { useEffect } from "react";
import { AlertTriangle, RefreshCw, ChevronDown } from "lucide-react";

/**
 * src/app/error.tsx — Global Error Boundary (Next.js App Router)
 * Se activa cuando un Server Component o Client Component lanza un error no capturado.
 * En modo testing muestra el stack completo; en producción muestra un mensaje genérico.
 */
export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const isDebug = process.env.NODE_ENV !== "production"
    || typeof window !== "undefined" && window.location.search.includes("debug=1");

  useEffect(() => {
    // Log al servidor vía console (capturado por cPanel)
    console.error("[GlobalError]", error);
  }, [error]);

  return (
    <html lang="es">
      <body style={{ margin: 0, fontFamily: "system-ui, sans-serif", background: "#0f172a", color: "#f1f5f9", minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ maxWidth: 700, width: "100%", padding: "2rem", margin: "0 auto" }}>

          {/* Cabecera */}
          <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "1.5rem" }}>
            <div style={{ background: "#ef4444", borderRadius: "50%", width: 56, height: 56, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <AlertTriangle size={28} color="white" />
            </div>
            <div>
              <h1 style={{ margin: 0, fontSize: "1.5rem", fontWeight: 800, color: "#f8fafc" }}>Error en la aplicación</h1>
              <p style={{ margin: "0.25rem 0 0", fontSize: "0.875rem", color: "#94a3b8" }}>
                {isDebug ? "Modo debug activo — detalles completos" : "Ocurrió un error inesperado"}
              </p>
            </div>
          </div>

          {/* Mensaje principal */}
          <div style={{ background: "#1e293b", borderRadius: 12, padding: "1.25rem 1.5rem", marginBottom: "1rem", border: "1px solid #334155" }}>
            <p style={{ margin: 0, color: "#fca5a5", fontWeight: 600, fontSize: "1rem" }}>
              {error.message || "Error desconocido"}
            </p>
            {error.digest && (
              <p style={{ margin: "0.5rem 0 0", fontSize: "0.75rem", color: "#64748b", fontFamily: "monospace" }}>
                Digest: {error.digest}
              </p>
            )}
          </div>

          {/* Stack trace — solo en debug */}
          {isDebug && error.stack && (
            <details open style={{ marginBottom: "1rem" }}>
              <summary style={{ cursor: "pointer", color: "#f59e0b", fontWeight: 600, fontSize: "0.875rem", marginBottom: "0.75rem", display: "flex", alignItems: "center", gap: "0.5rem", userSelect: "none" }}>
                <ChevronDown size={16} /> Stack Trace
              </summary>
              <pre style={{
                background: "#020617", color: "#e2e8f0", padding: "1rem 1.25rem",
                borderRadius: 8, fontSize: "0.75rem", overflowX: "auto",
                lineHeight: 1.6, border: "1px solid #1e293b", whiteSpace: "pre-wrap", wordBreak: "break-all"
              }}>
                {error.stack}
              </pre>
            </details>
          )}

          {/* Variables de entorno relevantes — solo en debug */}
          {isDebug && (
            <details style={{ marginBottom: "1rem" }}>
              <summary style={{ cursor: "pointer", color: "#60a5fa", fontWeight: 600, fontSize: "0.875rem", marginBottom: "0.75rem", display: "flex", alignItems: "center", gap: "0.5rem", userSelect: "none" }}>
                <ChevronDown size={16} /> Entorno
              </summary>
              <div style={{ background: "#020617", borderRadius: 8, padding: "1rem", border: "1px solid #1e293b", fontSize: "0.75rem", fontFamily: "monospace", color: "#94a3b8" }}>
                <div><span style={{ color: "#38bdf8" }}>NODE_ENV:</span> {process.env.NODE_ENV}</div>
                <div><span style={{ color: "#38bdf8" }}>NEXTAUTH_URL:</span> {process.env.NEXTAUTH_URL || "—"}</div>
                <div><span style={{ color: "#38bdf8" }}>DATABASE_URL:</span> {process.env.DATABASE_URL ? "✅ definida" : "❌ no definida"}</div>
              </div>
            </details>
          )}

          {/* Acciones */}
          <div style={{ display: "flex", gap: "1rem", flexWrap: "wrap" }}>
            <button
              onClick={reset}
              style={{
                display: "flex", alignItems: "center", gap: "0.5rem",
                background: "#3b82f6", color: "white", border: "none",
                borderRadius: 8, padding: "0.75rem 1.5rem", fontSize: "0.875rem",
                fontWeight: 700, cursor: "pointer"
              }}
            >
              <RefreshCw size={16} /> Reintentar
            </button>
            <a
              href="/"
              style={{
                display: "flex", alignItems: "center", gap: "0.5rem",
                background: "#1e293b", color: "#94a3b8", border: "1px solid #334155",
                borderRadius: 8, padding: "0.75rem 1.5rem", fontSize: "0.875rem",
                fontWeight: 600, textDecoration: "none"
              }}
            >
              Ir al inicio
            </a>
            {isDebug && (
              <a
                href={`/api/debug?token=${typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("dbtoken") || "" : ""}`}
                target="_blank"
                rel="noreferrer"
                style={{
                  display: "flex", alignItems: "center", gap: "0.5rem",
                  background: "#1e293b", color: "#f59e0b", border: "1px solid #78350f",
                  borderRadius: 8, padding: "0.75rem 1.5rem", fontSize: "0.875rem",
                  fontWeight: 600, textDecoration: "none"
                }}
              >
                Ver logs del servidor
              </a>
            )}
          </div>

        </div>
      </body>
    </html>
  );
}
