'use client';

import { useEffect, useRef, useCallback } from 'react';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/components/AuthContext';

/** Default 45 minutes of inactivity before auto-logout (kasir counters left open). */
const IDLE_MS = Number(process.env.NEXT_PUBLIC_IDLE_LOGOUT_MS) || 45 * 60 * 1000;
/** Warn 60s before logout */
const WARN_MS = 60 * 1000;

/** Intentional activity only — ignore pure mousemove (prevents zombie sessions). */
const ACTIVITY_EVENTS: (keyof WindowEventMap)[] = [
  'mousedown',
  'keydown',
  'touchstart',
  'click',
  'scroll',
];

/**
 * Auto-logout after idle period while authenticated.
 * Skips /login. Resets on user activity.
 */
export default function IdleLogout() {
  const { user, logout } = useAuth();
  const pathname = usePathname();
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const warnRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const warnedRef = useRef(false);

  const clearTimers = useCallback(() => {
    if (timerRef.current) clearTimeout(timerRef.current);
    if (warnRef.current) clearTimeout(warnRef.current);
    timerRef.current = null;
    warnRef.current = null;
  }, []);

  const arm = useCallback(() => {
    if (!user || pathname === '/login') {
      clearTimers();
      return;
    }

    clearTimers();
    warnedRef.current = false;

    if (IDLE_MS > WARN_MS) {
      warnRef.current = setTimeout(() => {
        warnedRef.current = true;
        // Lightweight warn — avoid blocking modal on busy counter
        if (typeof window !== 'undefined') {
          console.info('[security] Session akan logout otomatis karena tidak aktif.');
        }
      }, IDLE_MS - WARN_MS);
    }

    timerRef.current = setTimeout(() => {
      void logout();
    }, IDLE_MS);
  }, [user, pathname, logout, clearTimers]);

  useEffect(() => {
    if (!user || pathname === '/login') {
      clearTimers();
      return;
    }

    arm();

    const onActivity = () => {
      arm();
    };

    for (const ev of ACTIVITY_EVENTS) {
      window.addEventListener(ev, onActivity, { passive: true });
    }

    // Cross-tab: storage heartbeat optional — session cookie is shared via browser
    return () => {
      clearTimers();
      for (const ev of ACTIVITY_EVENTS) {
        window.removeEventListener(ev, onActivity);
      }
    };
  }, [user, pathname, arm, clearTimers]);

  return null;
}
