import { createContext, useContext, useState, useEffect, useCallback } from 'react';

const API_URL = 'http://localhost/AAbank_mob/backend/api.php';
const getAuthHeaders = () => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('iosco_token') || ''}` });

const NotificationsContext = createContext(null);

export const NotificationsProvider = ({ children }) => {
    const [notifications, setNotifications] = useState([]);
    const [unreadCount, setUnreadCount] = useState(0);

    const load = useCallback(async () => {
        try {
            const r = await fetch(`${API_URL}/notifications`, { headers: getAuthHeaders() });
            if (!r.ok) return;
            const data = await r.json();
            setNotifications(data);
            setUnreadCount(data.filter(n => !n.is_read).length);
        } catch { /* silent */ }
    }, []);

    useEffect(() => {
        const token = localStorage.getItem('iosco_token');
        if (!token) return;
        load();
        const interval = setInterval(load, 30000);
        return () => clearInterval(interval);
    }, [load]);

    const markRead = (id) => {
        setNotifications(n => n.map(x => x.id === id ? { ...x, is_read: 1 } : x));
        setUnreadCount(c => Math.max(0, c - 1));
    };

    const markAllRead = async () => {
        try {
            await fetch(`${API_URL}/notifications`, { method: 'PUT', headers: getAuthHeaders() });
            setNotifications(n => n.map(x => ({ ...x, is_read: 1 })));
            setUnreadCount(0);
        } catch { /* silent */ }
    };

    // Add local notification (for instant feedback)
    const pushLocal = (title, message, type = 'info') => {
        const n = { id: Date.now(), title, message, type, is_read: 0, created_at: new Date().toISOString() };
        setNotifications(prev => [n, ...prev]);
        setUnreadCount(c => c + 1);
    };

    return (
        <NotificationsContext.Provider value={{ notifications, unreadCount, markRead, markAllRead, reload: load, pushLocal }}>
            {children}
        </NotificationsContext.Provider>
    );
};

export const useNotifications = () => useContext(NotificationsContext);
