import { useCallback, useState } from 'react';

/**
 * Manages a single error message string with clear/set helpers.
 * Formats raw HTTP/technical errors into friendly user-facing messages
 * consistent with the ErrorMessage component.
 *
 * Usage:
 *   const { error, setError, clearError } = useErrorMessage();
 *   // In a catch block:
 *   setError('network');
 *   setError('403');
 *   setError('Something specific happened');
 */

const FRIENDLY: Record<string, string> = {
  network: 'Check your internet connection and try again.',
  timeout: 'The request took too long. Try again.',
  unauthorized: 'You are not authorized to perform this action.',
  '401': 'You are not authorized to perform this action.',
  forbidden: 'You do not have permission to do that.',
  '403': 'You do not have permission to do that.',
  'not found': 'That item could not be found. It may have been deleted.',
  '404': 'That item could not be found. It may have been deleted.',
  'rate limit': 'Too many requests. Wait a moment and try again.',
  '429': 'Too many requests. Wait a moment and try again.',
  validation: 'Check your input and try again.',
  server: 'Something went wrong on our end. Try again.',
  '500': 'Something went wrong on our end. Try again.',
  generic: 'Something went wrong. Try again.',
};

function normalize(raw: string): string {
  const lower = raw.toLowerCase();
  for (const [key, friendly] of Object.entries(FRIENDLY)) {
    if (lower.includes(key)) return friendly;
  }
  return raw;
}

export function useErrorMessage(initial?: string) {
  const [error, setRaw] = useState<string | null>(initial != null ? normalize(initial) : null);

  const setError = useCallback((raw: string) => {
    setRaw(normalize(raw));
  }, []);

  const clearError = useCallback(() => {
    setRaw(null);
  }, []);

  return { error, setError, clearError };
}
