"use client";

import { useEffect } from 'react';
import { useToast } from '@/components/ui/ToastContext';

// Header that, when present on requests, suppresses global toasts from fetch interceptor
const TOAST_CONTROL_HEADER = 'x-toast-controlled';

export default function ClientToasterBridge() {
  const { showError, showSuccess, showInfo } = useToast();

  useEffect(() => {
    // Patch window.alert to use toast
    const originalAlert = window.alert;
    window.alert = (message?: any) => {
      try {
        const text = typeof message === 'string' ? message : String(message);
        showInfo(text, 'Notice');
      } catch {
        // Fallback to original alert if anything goes wrong
        originalAlert(message);
      }
    };

    // Patch fetch to show success/error toasts for API calls
    const originalFetch = window.fetch.bind(window);

    window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
      let method = (init?.method || (input instanceof Request ? input.method : 'GET') || 'GET').toUpperCase();

      // Determine if toasts should be suppressed via header
      const headersFromInit = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined));
      const suppressToasts = headersFromInit.get(TOAST_CONTROL_HEADER) === 'true';

      try {
        const response = await originalFetch(input, init);

        // Only handle JSON API endpoints under /api/
        const urlString = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
        const isApiCall = urlString.includes('/api/');

        if (!suppressToasts && isApiCall) {
          // Clone so we don't consume the body
          const responseClone = response.clone();
          let parsed: any | null = null;
          try {
            parsed = await responseClone.json();
          } catch {
            parsed = null;
          }

          if (!response.ok) {
            const message =
              (parsed && (parsed.message || parsed.error)) ||
              `${response.status} ${response.statusText}` ||
              'Request failed';
            showError(message, 'Error');
          } else if (parsed && typeof parsed === 'object') {
            const successFlag = typeof parsed.success === 'boolean' ? parsed.success : true;
            if (!successFlag) {
              const message = parsed.error || parsed.message || 'Operation failed';
              showError(message, 'Error');
            } else if (method !== 'GET') {
              const message = parsed.message || 'Operation completed successfully';
              // showSuccess(message);
            }
          }
        }

        return response;
      } catch (err: any) {
        if (!suppressToasts) {
          const isNetworkError = err instanceof TypeError && String(err.message || '').toLowerCase().includes('fetch');
          const message = isNetworkError
            ? 'Network error: Please check your internet connection and try again.'
            : (err?.message || 'An unexpected error occurred');
          showError(message, 'Error');
        }
        throw err; // Re-throw so callers can still handle
      }
    };

    return () => {
      // cleanup: restore originals
      window.alert = originalAlert;
      window.fetch = originalFetch;
    };
  }, [showError, showSuccess, showInfo]);

  return null;
}
