import { createStore } from "@stencil/store";
import { configStore } from "./store";
export const typingStore = createStore({
    typingAdmins: [],
});
/**
 * Returns the current admin's { id, name } from the memberList.
 * Uses `is_current_admin` flag to identify the logged-in admin.
 * If not found, attempts to parse the user ID from the accessToken as a fallback.
 */
export function getCurrentAdmin() {
    const memberList = configStore.get('memberList');
    let currentMember = memberList.find(member => member.is_current_admin);
    // Fallback: attempt to decode JWT accessToken to find current member id
    if (!currentMember) {
        const token = configStore.get('accessToken');
        if (token) {
            try {
                const base64Url = token.split('.')[1];
                if (base64Url) {
                    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                    const jsonPayload = decodeURIComponent(atob(base64)
                        .split('')
                        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                        .join(''));
                    const payload = JSON.parse(jsonPayload);
                    if (payload && payload.id) {
                        currentMember = memberList.find(member => member.id === payload.id);
                    }
                }
            }
            catch (e) {
                // ignore token parsing errors
            }
        }
    }
    if (!currentMember)
        return null;
    const firstName = currentMember.member_account?.first_name || '';
    const lastName = currentMember.member_account?.last_name || '';
    const name = `${firstName} ${lastName}`.trim() || currentMember.member_login_data?.email || 'Admin';
    return {
        id: currentMember.id,
        name,
    };
}
export function getCurrentAdminId() {
    const token = configStore.get('accessToken');
    if (!token)
        return null;
    try {
        const base64Url = token.split('.')[1];
        if (!base64Url)
            return null;
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64)
            .split('')
            .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
            .join(''));
        const payload = JSON.parse(jsonPayload);
        return payload?.id || null;
    }
    catch {
        return null;
    }
}
