'use client'

import { useEffect } from 'react'

/**
 * Captures unhandled client-side errors and forwards them to the server
 * so they appear in `docker logs memento-web`. Loaded in the root layout.
 */
export function ErrorReporter() {
  useEffect(() => {
    function report(payload: object) {
      fetch('/api/debug/client-error', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        keepalive: true,
      }).catch(() => {
        console.error('[ErrorReporter] Failed to report client error (endpoint removed)')
      })
    }

    function onError(event: ErrorEvent) {
      report({
        type: 'uncaught-error',
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        stack: event.error?.stack ?? null,
        url: window.location.href,
        timestamp: new Date().toISOString(),
      })
    }

    function onUnhandledRejection(event: PromiseRejectionEvent) {
      const reason = event.reason
      report({
        type: 'unhandled-rejection',
        message: reason?.message ?? String(reason),
        stack: reason?.stack ?? null,
        url: window.location.href,
        timestamp: new Date().toISOString(),
      })
    }

    window.addEventListener('error', onError)
    window.addEventListener('unhandledrejection', onUnhandledRejection)
    return () => {
      window.removeEventListener('error', onError)
      window.removeEventListener('unhandledrejection', onUnhandledRejection)
    }
  }, [])

  return null
}
