export const TOKEN_EVENT = "ivory-token-change";

const getToken = () => {
    try {
        const token = localStorage?.getItem('token') || null;
        return token && token.trim() !== "" ? token : null;
    } catch (err) {
        console.error("Error retrieving token:", err);
        return null;
    }
};

/**
 * حدث "storage" لا يُطلق في نفس التبويب، لذلك نُطلق حدثاً خاصاً
 * حتى تُحدَّث المكوّنات الثابتة في الـ Layout (الشريط العلوي، الملف الشخصي)
 * فور تسجيل الدخول/الخروج دون إعادة تحميل الصفحة.
 */
const notify = () => {
    try { window.dispatchEvent(new Event(TOKEN_EVENT)); } catch { /* ignore */ }
};

export const setToken = (token: string | null | undefined) => {
    try {
        if (token) localStorage.setItem('token', token);
        else localStorage.removeItem('token');
    } catch { /* ignore */ }
    notify();
};

export const clearToken = () => setToken(null);

export default getToken
