'use client'

import { useEffect } from 'react'

/**
 * Error boundary for the (app) segment. Catches anything thrown during
 * a page render or a server action invocation. Renders a friendly
 * "your page might be out of date" message — the most common cause is
 * a stale tab clicking a button whose server-action hash no longer
 * exists on the new deploy.
 *
 * Production Next.js obscures the original error message and only
 * gives us `error.digest`. So we can't reliably branch on the message
 * to differentiate stale-action from a real bug. Instead we lean on
 * "refresh first, then escalate" as the primary affordance, and tuck
 * the digest into a <details> for the dev console.
 */
export default function AppErrorBoundary({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    // Surface it in the browser console for inspection.
    // eslint-disable-next-line no-console
    console.error('[(app) error boundary]', error)
  }, [error])

  // Heuristic: if dev mode leaked the original message, prefer the
  // tailored copy for the stale-action case.
  const looksStale =
    typeof error.message === 'string' &&
    error.message.includes('Failed to find Server Action')

  return (
    <main>
      <div className="page-head">
        <h1>{looksStale ? 'Page is out of date' : 'Something went wrong'}</h1>
        <p className="subtitle">
          {looksStale
            ? "This tab loaded before a recent deploy, so the buttons on it are pointing at code that no longer exists on the server. Refresh the page and try again."
            : "The action couldn't complete. Most of the time a hard refresh fixes it; if it keeps happening, send the error digest to Rian."}
        </p>
      </div>

      <div className="panel" style={{ display: 'grid', gap: '0.75rem' }}>
        <div className="flex-row" style={{ gap: '0.5rem', flexWrap: 'wrap' }}>
          <button
            type="button"
            onClick={() => {
              // Force a fresh fetch of the page from the server — bypasses
              // the browser's bfcache and re-pulls the latest JS bundle.
              window.location.reload()
            }}
          >
            Refresh page
          </button>
          <button type="button" className="secondary" onClick={() => reset()}>
            Try again without refreshing
          </button>
        </div>

        <details
          className="muted"
          style={{ fontSize: '0.85em', marginTop: '0.5rem' }}
        >
          <summary style={{ cursor: 'pointer' }}>Technical details</summary>
          <div style={{ marginTop: '0.5rem' }}>
            {error.digest && (
              <div>
                <strong>Digest:</strong>{' '}
                <code style={{ fontSize: '0.85em' }}>{error.digest}</code>
              </div>
            )}
            {error.message && (
              <div style={{ marginTop: '0.25rem' }}>
                <strong>Message:</strong>{' '}
                <code style={{ fontSize: '0.85em' }}>{error.message}</code>
              </div>
            )}
          </div>
        </details>
      </div>
    </main>
  )
}
