// Session and Inactivity Manager
class SessionManager {
    constructor() {
        this.warningTime = 5 * 60 * 1000; // 5 minutes before session expires (in milliseconds)
        this.sessionLifetime = 120 * 60 * 1000; // 120 minutes (2 hours) - matches Laravel default
        this.inactivityWarningTime = 15 * 60 * 1000; // Show warning after 15 minutes of inactivity
        this.lastActivity = Date.now();
        this.warningShown = false;
        this.inactivityWarningShown = false;
        this.countdownInterval = null;
        this.inactivityTimer = null;
        
        this.init();
    }
    
    init() {
        // Track user activity
        this.trackActivity();
        
        // Set up inactivity warning
        this.setupInactivityWarning();
        
        // Set up session expiration warning
        this.setupSessionExpirationWarning();
        
        // Handle visibility change (tab switching)
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.checkSessionStatus();
            }
        });
    }
    
    trackActivity() {
        const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
        
        events.forEach(event => {
            document.addEventListener(event, () => {
                this.lastActivity = Date.now();
                if (this.inactivityWarningShown) {
                    this.hideInactivityWarning();
                }
            }, { passive: true });
        });
    }
    
    setupInactivityWarning() {
        this.inactivityTimer = setInterval(() => {
            const timeSinceActivity = Date.now() - this.lastActivity;
            
            if (timeSinceActivity >= this.inactivityWarningTime && !this.inactivityWarningShown) {
                this.showInactivityWarning();
            }
        }, 60000); // Check every minute
    }
    
    setupSessionExpirationWarning() {
        // Check session status periodically
        setInterval(() => {
            this.checkSessionStatus();
        }, 60000); // Check every minute
    }
    
    async checkSessionStatus() {
        try {
            const response = await fetch('/admin/session-check', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
                credentials: 'same-origin'
            });
            
            if (response.status === 401 || response.status === 419) {
                this.handleSessionExpired();
                return;
            }
            
            if (!response.ok) {
                return;
            }
            
            const data = await response.json();
            if (data && data.expired) {
                this.handleSessionExpired();
                return;
            }
            
            if (data && data.time_remaining) {
                const timeUntilExpiry = data.time_remaining * 1000; // Convert to milliseconds
                
                if (timeUntilExpiry <= this.warningTime && !this.warningShown && timeUntilExpiry > 0) {
                    this.showSessionWarning(timeUntilExpiry);
                }
            }
        } catch (error) {
            // If fetch fails, it might be due to session expiration
            if (error.message && (error.message.includes('401') || error.message.includes('419'))) {
                this.handleSessionExpired();
            }
        }
    }
    
    showInactivityWarning() {
        this.inactivityWarningShown = true;
        
        const modal = document.createElement('div');
        modal.id = 'inactivity-warning-modal';
        modal.className = 'fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-2xl max-w-md w-full shadow-2xl border border-[#e8ddd0] animate-slideUp">
                <div class="p-6">
                    <div class="flex items-center gap-4 mb-4">
                        <div class="w-16 h-16 bg-[#fef3c7] rounded-full flex items-center justify-center">
                            <svg class="w-8 h-8 text-[#92400e]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                            </svg>
                        </div>
                        <div class="flex-1">
                            <h3 class="text-2xl font-serif font-bold text-[#524438]">Inactivity Warning</h3>
                            <p class="text-[#645443] mt-1">You've been inactive for a while</p>
                        </div>
                    </div>
                    <p class="text-[#645443] mb-6 leading-relaxed">
                        You haven't interacted with the page for a while. If you remain inactive, you may be automatically logged out for security reasons.
                    </p>
                    <div class="flex gap-3">
                        <button onclick="sessionManager.continueSession()" class="flex-1 bg-[#7d6a52] text-white px-6 py-3 rounded-full hover:bg-[#9d8566] transition-all font-semibold shadow-lg hover:shadow-xl">
                            Continue Session
                        </button>
                        <button onclick="sessionManager.logout()" class="bg-[#e8ddd0] text-[#524438] px-6 py-3 rounded-full hover:bg-[#d4c4b0] transition-all font-semibold">
                            Logout Now
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    }
    
    hideInactivityWarning() {
        this.inactivityWarningShown = false;
        const modal = document.getElementById('inactivity-warning-modal');
        if (modal) {
            modal.remove();
        }
    }
    
    showSessionWarning(timeUntilExpiry) {
        this.warningShown = true;
        const minutes = Math.floor(timeUntilExpiry / 60000);
        const seconds = Math.floor((timeUntilExpiry % 60000) / 1000);
        let countdown = minutes * 60 + seconds;
        
        const modal = document.createElement('div');
        modal.id = 'session-warning-modal';
        modal.className = 'fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-2xl max-w-md w-full shadow-2xl border border-[#e8ddd0] animate-slideUp">
                <div class="p-6">
                    <div class="flex items-center gap-4 mb-4">
                        <div class="w-16 h-16 bg-[#fee2e2] rounded-full flex items-center justify-center">
                            <svg class="w-8 h-8 text-[#991b1b]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="flex-1">
                            <h3 class="text-2xl font-serif font-bold text-[#524438]">Session Expiring Soon</h3>
                            <p class="text-[#645443] mt-1">Your session will expire in <span id="session-countdown">${this.formatTime(countdown)}</span></p>
                        </div>
                    </div>
                    <p class="text-[#645443] mb-6 leading-relaxed">
                        Your session is about to expire. Click "Extend Session" to stay logged in, or you'll be automatically logged out.
                    </p>
                    <div class="flex gap-3">
                        <button onclick="sessionManager.extendSession()" class="flex-1 bg-[#7d6a52] text-white px-6 py-3 rounded-full hover:bg-[#9d8566] transition-all font-semibold shadow-lg hover:shadow-xl">
                            Extend Session
                        </button>
                        <button onclick="sessionManager.logout()" class="bg-[#e8ddd0] text-[#524438] px-6 py-3 rounded-full hover:bg-[#d4c4b0] transition-all font-semibold">
                            Logout Now
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // Start countdown
        this.countdownInterval = setInterval(() => {
            countdown--;
            const countdownEl = document.getElementById('session-countdown');
            if (countdownEl) {
                countdownEl.textContent = this.formatTime(countdown);
            }
            
            if (countdown <= 0) {
                clearInterval(this.countdownInterval);
                this.handleSessionExpired();
            }
        }, 1000);
    }
    
    formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    }
    
    async extendSession() {
        try {
            const response = await fetch('/admin/session-extend', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
                credentials: 'same-origin'
            });
            
            if (response.ok) {
                this.warningShown = false;
                const modal = document.getElementById('session-warning-modal');
                if (modal) {
                    modal.remove();
                }
                if (this.countdownInterval) {
                    clearInterval(this.countdownInterval);
                }
                showToast('Session extended successfully', 'success');
            } else {
                this.handleSessionExpired();
            }
        } catch (error) {
            console.error('Failed to extend session:', error);
            this.handleSessionExpired();
        }
    }
    
    continueSession() {
        this.lastActivity = Date.now();
        this.hideInactivityWarning();
        showToast('Session continued', 'success');
    }
    
    handleSessionExpired() {
        // Clear all intervals
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
        }
        if (this.inactivityTimer) {
            clearInterval(this.inactivityTimer);
        }
        
        // Remove any warning modals
        const warningModal = document.getElementById('session-warning-modal');
        const inactivityModal = document.getElementById('inactivity-warning-modal');
        if (warningModal) warningModal.remove();
        if (inactivityModal) inactivityModal.remove();
        
        // Show session expired message
        showToast('Your session has expired. Redirecting to login...', 'error');
        
        // Redirect to login after a short delay
        setTimeout(() => {
            window.location.href = '/admin/login?expired=1';
        }, 2000);
    }
    
    logout() {
        // Submit logout form
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '/admin/logout';
        
        const csrfToken = document.createElement('input');
        csrfToken.type = 'hidden';
        csrfToken.name = '_token';
        csrfToken.value = document.querySelector('meta[name="csrf-token"]')?.content || '';
        form.appendChild(csrfToken);
        
        document.body.appendChild(form);
        form.submit();
    }
}

// Initialize session manager for admin pages
document.addEventListener('DOMContentLoaded', function() {
    const body = document.querySelector('body');
    if (body && (body.classList.contains('admin-page') || window.location.pathname.startsWith('/admin'))) {
        window.sessionManager = new SessionManager();
    }
});

