import { onMounted, onUnmounted, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useCollaborationStore } from '@/features/collaboration/collaboration/collaboration.store';
import { DEBOUNCE_TIME, getDebounceTime } from '@/app/constants/durations';

export function useActivityDetection() {
	const collaborationStore = useCollaborationStore();

	const recordActivity = useDebounceFn(() => {
		collaborationStore.recordActivity();
	}, getDebounceTime(DEBOUNCE_TIME.COLLABORATION.ACTIVITY));

	const events = ['mousedown', 'keydown', 'touchstart'];

	const attachListeners = () => {
		events.forEach((event) => {
			document.addEventListener(event, recordActivity, { passive: true });
		});
	};

	const detachListeners = () => {
		events.forEach((event) => {
			document.removeEventListener(event, recordActivity);
		});
	};

	// Watch for writer status changes
	watch(
		() => collaborationStore.isCurrentTabWriter,
		(isWriter) => {
			if (isWriter) {
				attachListeners();
			} else {
				detachListeners();
			}
		},
	);

	onMounted(() => {
		// Attach listeners if current tab is writer
		if (collaborationStore.isCurrentTabWriter) {
			attachListeners();
		}
	});

	onUnmounted(() => {
		detachListeners();
	});

	return {
		recordActivity,
	};
}
