"use client";

import { useEffect } from "react";

// Root-level error boundary. Catches errors thrown in the root layout / during
// rendering that no nested error.tsx caught. Must render its own <html>/<body>.
// Reports the crash to /api/errors so it shows up in the admin error tracker.
export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    try {
      const body = JSON.stringify({
        message: error?.message || "Unknown global error",
        stack: error?.stack,
        digest: error?.digest,
        url: typeof window !== "undefined" ? window.location.pathname : undefined,
        level: "fatal",
        metadata: { boundary: "global" },
      });
      // keepalive so the report survives the page being torn down
      fetch("/api/errors", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body,
        keepalive: true,
      }).catch(() => {});
    } catch {}
  }, [error]);

  return (
    <html lang="en">
      <body style={{ fontFamily: "system-ui, sans-serif", background: "#fdf2f2", color: "#1a1a1a" }}>
        <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 16, padding: 24, textAlign: "center" }}>
          <div style={{ fontSize: 40 }}>😵</div>
          <h1 style={{ fontSize: 20, fontWeight: 700 }}>Something went wrong</h1>
          <p style={{ color: "#6b7280", maxWidth: 360 }}>
            The app hit an unexpected error. It&apos;s been reported automatically — please try again.
          </p>
          <button
            onClick={() => reset()}
            style={{ background: "#fb7185", color: "white", border: "none", padding: "10px 20px", borderRadius: 12, fontWeight: 600, cursor: "pointer" }}
          >
            Try again
          </button>
        </div>
      </body>
    </html>
  );
}
