/**
 * Auth Helper - Unified Authentication Management
 * Handles Token Storage, Retrieval, and Validation
 */

const Auth = {
    // Keys for storage
    TOKEN_KEY: 'token',
    USER_KEY: 'user',

    /**
     * Save authentication data
     * @param {string} token - JWT Token
     * @param {object} user - User object
     */
    setAuth: (token, user) => {
        if (!token) return;

        // Ensure standard Bearer format if missing or clean if duplicate
        // But usually we store raw token and add Bearer in header
        localStorage.setItem(Auth.TOKEN_KEY, token);

        if (user) {
            localStorage.setItem(Auth.USER_KEY, JSON.stringify(user));
            // Backwards compatibility for existing pages
            localStorage.setItem('userId', user._id);
            if (user.role === 'captain') {
                localStorage.setItem('captainName', user.name);
            } else {
                localStorage.setItem('userName', user.name);
            }
        }
    },

    /**
     * Get the raw token
     * @returns {string|null}
     */
    getToken: () => {
        return localStorage.getItem(Auth.TOKEN_KEY);
    },

    /**
     * Get the User object
     * @returns {object|null}
     */
    getUser: () => {
        const userStr = localStorage.getItem(Auth.USER_KEY);
        return userStr ? JSON.parse(userStr) : null;
    },

    /**
     * Check if user is authenticated and token is valid
     * @returns {boolean}
     */
    isAuthenticated: () => {
        const token = Auth.getToken();
        if (!token) return false;

        if (Auth.isTokenExpired(token)) {
            Auth.logout();
            return false;
        }

        return true;
    },

    /**
     * Decode JWT to check expiration
     * @param {string} token 
     * @returns {boolean}
     */
    isTokenExpired: (token) => {
        try {
            const base64Url = token.split('.')[1];
            const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));

            const { exp } = JSON.parse(jsonPayload);
            const now = Date.now() / 1000;

            return exp < now;
        } catch (e) {
            return true; // Assume expired if invalid
        }
    },

    /**
     * clear auth data and redirect
     * @param {string} redirectUrl - URL to redirect to after logout
     */
    logout: async (redirectUrl = 'index.html') => {
        // Clear Google session only for clients (prevent fatal native crash for captains)
        const role = localStorage.getItem('role') || '';
        const userStr = localStorage.getItem(Auth.USER_KEY);
        let isClient = role === 'client' || role === 'customer';
        let isCaptain = role === 'captain';
        if (!isClient && !isCaptain && userStr) {
            try {
                const userObj = JSON.parse(userStr);
                isClient = userObj.role === 'client' || userObj.role === 'customer';
                isCaptain = userObj.role === 'captain';
            } catch(e) {}
        }
        
        if (isClient) {
            try {
                const mod = await import('https://cdn.jsdelivr.net/npm/@codetrix-studio/capacitor-google-auth@3.4.0-rc.4/+esm');
                if (mod && mod.GoogleAuth) {
                    await mod.GoogleAuth.signOut();
                }
            } catch (_) { /* Ignore if plugin fails or is not available */ }
        }

        // ✅ FIX: Set captain offline in DB immediately on logout
        if (isCaptain) {
            try {
                const token = localStorage.getItem(Auth.TOKEN_KEY);
                const apiUrl = (typeof API_URL !== 'undefined') ? API_URL : 'https://wassili.site';
                await fetch(`${apiUrl}/api/captain/logout`, {
                    method: 'POST',
                    headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }
                });
            } catch (_) { /* Non-fatal — captain will be set offline by socket timeout */ }
        }

        localStorage.removeItem(Auth.TOKEN_KEY);
        localStorage.removeItem(Auth.USER_KEY);
        localStorage.removeItem('userId');
        localStorage.removeItem('userName');
        localStorage.removeItem('captainName');
        localStorage.removeItem('role');

        // Redirect to landing page or specified page
        window.location.href = redirectUrl;
    },

    /**
     * Get Authorization Header for Fetch requests
     * @returns {object} Headers object
     */
    getAuthHeader: () => {
        const token = Auth.getToken();
        return token ? { 'Authorization': `Bearer ${token}` } : {};
    },

    getTokenSecondsLeft: () => {
        try {
            const token = Auth.getToken();
            if (!token) return 0;
            const base64Url = token.split('.')[1];
            let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            while (base64.length % 4) base64 += '=';
            const { exp } = JSON.parse(decodeURIComponent(window.atob(base64).split('').map(c =>
                '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')));
            return Math.max(0, exp - Date.now() / 1000);
        } catch (e) { return 0; }
    },

    /**
     * Silently refresh token if it expires in less than 24 hours
     */
    autoRefreshToken: async () => {
        const secondsLeft = Auth.getTokenSecondsLeft();
        if (secondsLeft <= 0 || secondsLeft > 86400) return; // Only refresh if < 24h left

        try {
            const API_BASE = (typeof window !== 'undefined' && window.API_URL)
                ? window.API_URL
                : (localStorage.getItem('API_URL') || 'https://wassili.site');
            const res = await fetch(`${API_BASE}/api/auth/refresh`, {
                method: 'POST',
                headers: Auth.getAuthHeader()
            });
            if (res.ok) {
                const data = await res.json();
                if (data.token) {
                    localStorage.setItem(Auth.TOKEN_KEY, data.token);
                    console.log('🔄 Token refreshed silently');
                }
            }
        } catch (e) { /* Silent fail */ }
    }
};

// Expose globally
window.Auth = Auth;

// 🔄 Auto-refresh on every page load
if (Auth.getToken() && !Auth.isTokenExpired(Auth.getToken())) {
    Auth.autoRefreshToken();
}

// 🏪 Inject "Back to Dashboard" button for merchants exploring client pages
function injectMerchantBtn() {
    if (document.getElementById('merchant-back-btn')) return; // already injected
    const role = localStorage.getItem('role');
    const uName = localStorage.getItem('userName');
    
    // Ensure we're a merchant and NOT on a merchant/dashboard page
    const isMerchantPage = window.location.pathname.includes('merchant-') || 
                           window.location.pathname.includes('captain-') || 
                           window.location.pathname.includes('admin-');
                           
    if (role === 'merchant' && uName && !isMerchantPage) {
        const btn = document.createElement('a');
        btn.id = 'merchant-back-btn';
        btn.href = 'merchant-dashboard.html';
        btn.innerHTML = '<i class="bi bi-shop-window me-2"></i> عودة للوحة المتجر';
        btn.style.cssText = 'position: fixed; top: 10px; left: 50%; transform: translateX(-50%); z-index: 9999; background: #fbbf24; color: #000; padding: 8px 16px; border-radius: 20px; font-weight: bold; font-size: 0.9rem; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-decoration: none; display: flex; align-items: center; border: 2px solid #fff;';
        document.body.appendChild(btn);
    }
}
document.addEventListener('DOMContentLoaded', injectMerchantBtn);
