import { Controller } from '@hotwired/stimulus';

/* Déconnexion automatique après 2h d'inactivité (port de useInactivityLogout.ts). */
const TIMEOUT_MS = 2 * 60 * 60 * 1000;
const EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'click'];

export default class extends Controller {
    connect() {
        this.reset = this.reset.bind(this);
        this.reset();
        EVENTS.forEach((e) => window.addEventListener(e, this.reset, { passive: true }));
    }

    disconnect() {
        clearTimeout(this.timer);
        EVENTS.forEach((e) => window.removeEventListener(e, this.reset));
    }

    reset() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            window.location.href = '/api/auth/logout?reason=inactivity';
        }, TIMEOUT_MS);
    }
}
