"use client";

import { useEffect, useState } from "react";

/**
 * Without this, a render error shows a blank screen with the detail buried
 * in the console. This surfaces the message on the page so it can be read
 * and reported directly.
 */
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    console.error("[XRcoin] page error:", error);
  }, [error]);

  const details = [
    `Message: ${error.message}`,
    error.digest ? `Digest: ${error.digest}` : null,
    `URL: ${typeof window !== "undefined" ? window.location.pathname : ""}`,
    "",
    error.stack ?? "(no stack)",
  ]
    .filter(Boolean)
    .join("\n");

  return (
    <div className="w-full max-w-2xl mx-auto px-4 py-14">
      <h1 className="text-lg font-bold mb-1">Something broke on this page</h1>
      <p className="text-sm text-neutral-500 mb-4">
        The details below say what went wrong — copy them if you want to report it.
      </p>

      <pre className="text-[11px] leading-relaxed bg-neutral-100 dark:bg-neutral-900 rounded-xl p-3 overflow-auto max-h-72 whitespace-pre-wrap break-words">
        {details}
      </pre>

      <div className="flex gap-2 mt-4">
        <button
          onClick={() => reset()}
          className="rounded-full px-4 py-2 text-sm font-bold text-white bg-gradient-to-r from-fuchsia-500 to-purple-600 hover:brightness-110 active:scale-95 transition-all"
        >
          Try again
        </button>
        <button
          onClick={() => {
            navigator.clipboard?.writeText(details);
            setCopied(true);
            setTimeout(() => setCopied(false), 1600);
          }}
          className="rounded-full px-4 py-2 text-sm font-bold bg-neutral-100 dark:bg-neutral-900 hover:bg-neutral-200 dark:hover:bg-neutral-800 transition-colors"
        >
          {copied ? "Copied ✓" : "Copy details"}
        </button>
        <a
          href="/"
          className="rounded-full px-4 py-2 text-sm font-bold bg-neutral-100 dark:bg-neutral-900 hover:bg-neutral-200 dark:hover:bg-neutral-800 transition-colors"
        >
          Back to feed
        </a>
      </div>
    </div>
  );
}
