/**
 * Centralized authentication and session management utilities
 */

export const logout = () => {
    console.log('Logging out: Clearing session data and redirecting...');
    localStorage.removeItem('teleems_auth');
    localStorage.removeItem('teleems_token');
    localStorage.removeItem('teleems_user');
    
    // Use window.location for a hard redirect to ensure all states are cleared
    window.location.href = '/';
};

/**
 * Decodes a JWT and checks if it's expired
 */
export const isTokenExpired = (token: string): boolean => {
    if (!token || token === 'dev-super-token-2026' || token.startsWith('dev-token-') || token.startsWith('mock-')) return false; // Bypass for dev and mock tokens
    
    try {
        const base64Url = token.split('.')[1];
        if (!base64Url) return true;
        
        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 { exp } = JSON.parse(jsonPayload);
        
        if (!exp) return false;
        
        // exp is in seconds, Date.now() in milliseconds
        const currentTime = Math.floor(Date.now() / 1000);
        return exp < currentTime;
    } catch (error) {
        console.error('Error decoding token:', error);
        return true; // Assume expired/invalid if error decoding
    }
};

/**
 * Checks if the user is currently authenticated
 */
export const isAuthenticated = (): boolean => {
    const authFlag = localStorage.getItem('teleems_auth') === 'true';
    const token = localStorage.getItem('teleems_token');
    
    if (!authFlag || !token) return false;
    
    // If it's a JWT, check expiration
    if (token.includes('.') && isTokenExpired(token)) {
        return false;
    }
    
    return true;
};
