'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSignalRContext } from '@/contexts/signalrProvider';
import FeedToast from './FeedToast';

export default function FeedToastWrapper() {
	const router = useRouter();
	const { lastFeedPost, clearLastFeedPost } = useSignalRContext();
	const [pendingCount, setPendingCount] = useState(0);

	useEffect(() => {
		if (!lastFeedPost) {
			return;
		}
		setPendingCount((c) => c + 1);
		clearLastFeedPost();
	}, [lastFeedPost, clearLastFeedPost]);

	const handleClick = useCallback(() => {
		setPendingCount(0);
		router.refresh();
		window.scrollTo({ top: 0, behavior: 'smooth' });
	}, [router]);

	return <FeedToast count={pendingCount} onClick={handleClick} />;
}