import { create } from 'zustand';

export interface AppError {
  id: string;
  status: number;
  message: string;
  page: string;
  timestamp: string;
  reported: boolean;
}

interface ErrorState {
  currentError: AppError | null;
  showLightbox: boolean;
  setError: (status: number, message: string) => void;
  markReported: () => void;
  dismiss: () => void;
}

export const useErrorStore = create<ErrorState>((set) => ({
  currentError: null,
  showLightbox: false,

  setError: (status, message) => {
    // Only show lightbox for SERVER errors (500+) and network errors (0)
    // 400 = validation (handled by forms), 401 = auth (redirect login),
    // 403 = forbidden, 404 = not found — all handled locally by components
    if (status >= 400 && status < 500) return;

    const error: AppError = {
      id: crypto.randomUUID?.() || Date.now().toString(36),
      status,
      message,
      page: typeof window !== 'undefined' ? window.location.pathname : '',
      timestamp: new Date().toISOString(),
      reported: false,
    };
    set({ currentError: error, showLightbox: true });
  },

  markReported: () =>
    set((s) => ({
      currentError: s.currentError ? { ...s.currentError, reported: true } : null,
    })),

  dismiss: () => set({ showLightbox: false }),
}));
