"use client";

import { useEffect } from "react";

/**
 * Route-level error boundary. Without this, any client-side throw renders
 * Next's generic "Application error: a client-side exception has occurred"
 * page with no message at all.
 */
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error("[app/error]", error);

    // A chunk that 404s is almost always a stale tab left open across a
    // deploy: the HTML references build A, the server now only serves build B.
    // One reload picks up the new manifest. The session flag stops a loop if
    // the reload does not help.
    if (isChunkLoadError(error) && !hasReloadedForChunkError()) {
      markReloadedForChunkError();
      window.location.reload();
    }
  }, [error]);

  return (
    <div className="flex min-h-[60vh] flex-col items-center justify-center gap-4 px-6 text-center text-white">
      <h2 className="text-xl font-semibold">Something went wrong</h2>
      <p className="max-w-xl text-sm text-white/70">
        {error?.message || "An unexpected error occurred."}
      </p>
      {error?.digest && (
        <p className="text-xs text-white/40">Digest: {error.digest}</p>
      )}
      <button
        onClick={reset}
        className="mt-2 rounded-full bg-[#ED3A57] px-5 py-2 text-sm font-semibold text-white"
      >
        Try again
      </button>
    </div>
  );
}

const CHUNK_RELOAD_KEY = "chunk-error-reloaded";

function isChunkLoadError(error: Error) {
  return (
    error?.name === "ChunkLoadError" ||
    /Loading chunk [\d]+ failed|Loading CSS chunk|Failed to fetch dynamically imported module|error loading dynamically imported module/i.test(
      error?.message || ""
    )
  );
}

function hasReloadedForChunkError() {
  try {
    return sessionStorage.getItem(CHUNK_RELOAD_KEY) === "1";
  } catch {
    return true; // no sessionStorage: never auto-reload, a loop is worse
  }
}

function markReloadedForChunkError() {
  try {
    sessionStorage.setItem(CHUNK_RELOAD_KEY, "1");
  } catch {
    /* ignore */
  }
}
