/**
 * @docs ARCHITECTURE:State
 * 
 * ### AI Assist Note
 * **Zustand State**: Swarm-wide alert and notification bus. 
 * Orchestrates the queueing, display, and auto-dismissal of system alerts, mission milestones, and security warnings.
 * 
 * ### 🔍 Debugging & Observability
 * - **Failure Path**: Notification queue starvation (alerts not showing), or persistent "zombie" toasts after manual dismissal.
 * - **Telemetry Link**: Search for `[NotificationStore]` or ALERT_PULSE in UI logs.
 */

import { create } from 'zustand';
import { subscribe_api_errors } from '../services/base_api_service';


export type Notification_Severity = 'info' | 'success' | 'warning' | 'error';

export interface Notification {
    id: string;
    severity: Notification_Severity;
    title: string;
    message: string;
    type_id?: string;
    persistent: boolean;
    timestamp: Date;
}

interface Notification_State {
    notifications: Notification[];
    add_notification: (notification: Omit<Notification, 'id' | 'timestamp'>) => void;
    remove_notification: (id: string) => void;
    clear_all: () => void;
}

/** 
 * generate_id
 * Utility to generate unique notification IDs.
 */
const generate_id = () => (typeof crypto !== 'undefined' && crypto.randomUUID) 
    ? crypto.randomUUID() 
    : `nt-${Date.now().toString(36)}-${(typeof performance !== 'undefined' ? Math.floor(performance.now() * 1000) : 0).toString(36)}`;

// Module-level registry for active auto-dismiss timers
const active_timers = new Map<string, ReturnType<typeof setTimeout>>();

/**
 * use_notification_store
 * Manages global application notifications and toast alerts.
 * Features automatic dismissal for non-persistent alerts and severity-based grouping.
 */
export const use_notification_store = create<Notification_State>((set) => ({
    notifications: [],

    add_notification: (notification) => {
        const id = generate_id();
        const new_notification: Notification = {
            ...notification,
            id,
            timestamp: new Date(),
        };

        set((state) => ({
            notifications: [new_notification, ...state.notifications],
        }));

        // Auto-dismiss logic for non-persistent notifications
        if (!notification.persistent) {
            const timer = setTimeout(() => {
                set((state) => ({
                    notifications: state.notifications.filter((n) => n.id !== id),
                }));
                active_timers.delete(id);
            }, 6000); // 6 seconds for standard toasts
            active_timers.set(id, timer);
        }
    },

    remove_notification: (id) => {
        const timer = active_timers.get(id);
        if (timer) {
            clearTimeout(timer);
            active_timers.delete(id);
        }
        set((state) => ({
            notifications: state.notifications.filter((n) => n.id !== id),
        }));
    },

    clear_all: () => {
        active_timers.forEach(clearTimeout);
        active_timers.clear();
        set({ notifications: [] });
    },
}));

// Subscribe to critical API error events
subscribe_api_errors((error) => {
    const normalized_code = (error.error_code || '').toUpperCase().replace(/-/g, '_');
    if (normalized_code === 'BUDGET_LIMIT_EXCEEDED' || normalized_code === 'BUDGET_EXHAUSTED') {
        use_notification_store.getState().add_notification({
            severity: 'warning',
            title: 'Quota Limit Intercepted',
            message: 'Mission budget exceeded. Adjust the budget in the Quotas tab of the Security Dashboard or change default settings.',
            persistent: true
        });
    } else if (normalized_code === 'OLLAMA_OFFLINE' || normalized_code === 'OLLAMA_SERVICE_UNAVAILABLE') {
        use_notification_store.getState().add_notification({
            severity: 'error',
            title: 'Model Provider Offline',
            message: 'Local Ollama service is unreachable. Try starting Ollama, changing model provider in Settings, or verifying local address resolution.',
            persistent: true
        });
    }
});

// Metadata: [notification_store]
