"use client";

import { useEffect } from "react";

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

/**
 * Error boundary for every page: a thrown render error shows this instead of a
 * blank page, and is reported to /api/log (page, error name, Next's digest, a
 * scrubbed message, and company / employee / role) so it can be found afterwards.
 *
 * The `digest` is the same id Next.js writes on the server for the same error
 * (see instrumentation.ts), which is what ties the browser report to the server log.
 */
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    reportClientError({
      type: "render_error",
      errorName: error.name,
      digest: error.digest,
      message: error.message,
    });
  }, [error]);

  return (
    <section className="mx-auto flex min-h-[60vh] w-full max-w-[520px] flex-col items-center justify-center px-[16px] py-[48px] text-center">
      <h1 className="mb-[8px] text-[22px] font-extrabold text-[var(--fra-heading)]">Something went wrong</h1>
      <p className="mb-[24px] text-[14px] text-[var(--fra-muted)]">
        We hit an unexpected problem loading this page. It has been reported. You can try again, or
        go back to the start.
      </p>
      <div className="flex flex-wrap justify-center gap-[12px]">
        <button
          type="button"
          onClick={reset}
          className="h-11 rounded-[var(--fra-radius-sm)] bg-[var(--fra-coral)] px-[20px] text-[15px] font-semibold text-white hover:bg-[var(--fra-coral-dark)]"
        >
          Try again
        </button>
        {/* A plain anchor, not <Link>: after a crash a full reload is the safest way back. */}
        {/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
        <a
          href="/"
          className="inline-flex h-11 items-center rounded-[var(--fra-radius-sm)] border border-[var(--fra-border-strong)] px-[20px] text-[15px] font-semibold text-[var(--fra-text)] hover:bg-[var(--fra-hover)]"
        >
          Go to home
        </a>
      </div>
      {error.digest && (
        <p className="mt-[24px] text-[12px] text-[var(--fra-muted)]">Reference: {error.digest}</p>
      )}
    </section>
  );
}
