"use client";

import { useEffect } from "react";

import { reportClientError } from "@/lib/client-error-report";

/**
 * Last-resort boundary: replaces the ROOT layout when the layout itself (or something
 * above app/error.tsx) throws, so it has to render its own <html> and <body>.
 *
 * Styled inline on purpose: the layout's stylesheets and fonts are not guaranteed to
 * be present when this renders, and a crash screen that depends on the thing that
 * crashed is worse than an unstyled one.
 */
export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    reportClientError({
      type: "render_error",
      errorName: error.name,
      digest: error.digest,
      message: error.message,
    });
  }, [error]);

  return (
    <html lang="en">
      <body
        style={{
          margin: 0,
          minHeight: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          fontFamily: "system-ui, -apple-system, Segoe UI, Roboto, sans-serif",
          background: "#f6f9fa",
          color: "#243238",
        }}
      >
        <main style={{ maxWidth: 480, padding: 24, textAlign: "center" }}>
          <h1 style={{ fontSize: 22, margin: "0 0 8px" }}>Something went wrong</h1>
          <p style={{ fontSize: 14, color: "#5b6a70", margin: "0 0 24px" }}>
            We hit an unexpected problem. It has been reported. You can try again, or reload from the start.
          </p>
          <button
            type="button"
            onClick={reset}
            style={{
              height: 44,
              padding: "0 20px",
              border: 0,
              borderRadius: 8,
              background: "#f45d6b",
              color: "#fff",
              fontSize: 15,
              fontWeight: 600,
              cursor: "pointer",
              marginRight: 12,
            }}
          >
            Try again
          </button>
          {/* Full reload on purpose: the router itself may be what crashed. */}
          {/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
          <a href="/" style={{ color: "#243238", fontSize: 15, fontWeight: 600 }}>
            Go to home
          </a>
          {error.digest && <p style={{ marginTop: 24, fontSize: 12, color: "#5b6a70" }}>Reference: {error.digest}</p>}
        </main>
      </body>
    </html>
  );
}
