import * as React from "react"
import { useRouteError } from "react-router-dom"
import { AlertCircle } from "lucide-react"

import { Button } from "@/components/ui/button"
import { isChunkLoadError } from "@/lib/chunk-load-error"

/**
 * Route error boundary — catches lazy-chunk failures and runtime errors
 * within a route subtree. `useRouteError()` is React Router's equivalent
 * of the Next error.tsx `error` prop. Reset = reload the route via
 * `window.location.reload()` (RR doesn't ship a `reset()` like Next).
 */
export function RouteError() {
  const error = useRouteError() as Error & { digest?: string }
  const chunkStale = isChunkLoadError(error)

  React.useEffect(() => {
    if (import.meta.env.DEV) {
      console.error(error)
    }
  }, [error])

  return (
    <div
      className="flex min-h-[50vh] flex-col items-center justify-center gap-4 px-4 py-12 text-center"
      role="alert"
    >
      <AlertCircle className="size-10 shrink-0 text-destructive" aria-hidden />
      <div className="space-y-2">
        <h1 className="text-lg font-semibold text-foreground">Something went wrong</h1>
        <p className="max-w-md text-sm text-muted-foreground">
          {chunkStale
            ? "The app loaded an outdated script bundle (common after a dev-server rebuild). Reload the page to fetch the latest chunks."
            : import.meta.env.DEV
              ? error?.message
              : "Please try again. If the problem continues, contact support."}
        </p>
      </div>
      <div className="flex flex-wrap items-center justify-center gap-2">
        <Button type="button" onClick={() => window.location.reload()}>
          {chunkStale ? "Reload page" : "Try again"}
        </Button>
      </div>
    </div>
  )
}
