'use client'; import React, { useEffect, useState, useRef, useCallback } from 'react'; import { useRouter, usePathname } from 'next/navigation'; import { AlertTriangle, Clock, LogOut, ShieldAlert } from 'lucide-react'; import { authService } from '@/services/api/authService'; import { getAccessToken } from '@/services/api/client'; import { toast } from 'sonner'; // Idle timeout: 30 minutes in ms const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // Warning prompt starts at 28 minutes (2 minutes before auto-logout) const WARNING_BEFORE_MS = 2 * 60 * 1000; const WARNING_THRESHOLD_MS = IDLE_TIMEOUT_MS - WARNING_BEFORE_MS; // 28 minutes const STORAGE_KEY_LAST_ACTIVITY = 'ifixkart_last_active_timestamp'; export function IdleSessionManager() { const router = useRouter(); const pathname = usePathname(); const [showWarning, setShowWarning] = useState(false); const [secondsRemaining, setSecondsRemaining] = useState(120); const lastActivityRef = useRef(Date.now()); const timerCheckIntervalRef = useRef(null); const recordActivity = useCallback(() => { const now = Date.now(); lastActivityRef.current = now; if (typeof window !== 'undefined') { try { localStorage.setItem(STORAGE_KEY_LAST_ACTIVITY, String(now)); } catch { // Storage access fallback } } if (showWarning) { setShowWarning(false); } }, [showWarning]); const handleLogout = useCallback(async (reason: string = 'idle') => { setShowWarning(false); if (timerCheckIntervalRef.current) { clearInterval(timerCheckIntervalRef.current); } toast.error('Session expired due to 30 minutes of inactivity. Please log in again.'); try { await authService.logout(); } catch { // Ignore network errors during logout } router.push(`/login?reason=${reason}`); }, [router]); const handleStayLoggedIn = () => { recordActivity(); setShowWarning(false); toast.success('Session extended. You are still securely signed in.'); }; useEffect(() => { // Only monitor authenticated pages (exclude login / forgot password pages) if (pathname?.includes('/login') || pathname?.includes('/forgot-password')) { return; } const token = getAccessToken(); if (!token) return; // Initialize timestamp const now = Date.now(); lastActivityRef.current = now; try { localStorage.setItem(STORAGE_KEY_LAST_ACTIVITY, String(now)); } catch {} // Throttle activity capture let lastRecorded = 0; const onUserInteraction = () => { const current = Date.now(); if (current - lastRecorded > 10000) { // Throttle every 10 seconds lastRecorded = current; recordActivity(); } }; const events = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click']; events.forEach((evt) => { window.addEventListener(evt, onUserInteraction, { passive: true }); }); // Cross-tab synchronization listener const onStorageUpdate = (e: StorageEvent) => { if (e.key === STORAGE_KEY_LAST_ACTIVITY && e.newValue) { const remoteTimestamp = parseInt(e.newValue, 10); if (!isNaN(remoteTimestamp) && remoteTimestamp > lastActivityRef.current) { lastActivityRef.current = remoteTimestamp; setShowWarning(false); } } }; window.addEventListener('storage', onStorageUpdate); // Heartbeat ticker checks every 1000ms timerCheckIntervalRef.current = setInterval(() => { const currentTimestamp = Date.now(); const elapsed = currentTimestamp - lastActivityRef.current; if (elapsed >= IDLE_TIMEOUT_MS) { handleLogout('idle_timeout'); } else if (elapsed >= WARNING_THRESHOLD_MS) { setShowWarning(true); const rem = Math.max(0, Math.ceil((IDLE_TIMEOUT_MS - elapsed) / 1000)); setSecondsRemaining(rem); } else { setShowWarning(false); } }, 1000); return () => { events.forEach((evt) => { window.removeEventListener(evt, onUserInteraction); }); window.removeEventListener('storage', onStorageUpdate); if (timerCheckIntervalRef.current) { clearInterval(timerCheckIntervalRef.current); } }; }, [pathname, recordActivity, handleLogout]); if (!showWarning) return null; const minutes = Math.floor(secondsRemaining / 60); const seconds = secondsRemaining % 60; const formattedCountdown = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; return (
{/* Glow Accent Header */}

Inactivity Security Notice

30-Minute Automatic Session Protection

You have been inactive for nearly 30 minutes. To protect internal e-commerce and CRM data, your session will automatically terminate in:

{/* Big Countdown Timer */}
{formattedCountdown}
Minutes Remaining Before Auto-Logout
{/* Action Buttons */}
); }