"use client";

import { deleteCookie } from "cookies-next";
import { useEffect } from "react";

const STALE_KEY = "stale-resource";
const RELOAD_STORAGE_KEY = "stale-img-reload";
const RELOAD_COOLDOWN_MS = 10 * 1000;

export const useStaleImageReload = () => {
	useEffect(() => {
		// Check for stale resource cookie
		const checkStaleCookie = () => {
			const hasStale = document.cookie.includes(`${STALE_KEY}=1`);

			if (hasStale) {
				//console.log("Stale resource cookie detected");
				// Clear the cookie
				deleteCookie(STALE_KEY);
				attemptReload();
			}
		};

		// Check on mount
		checkStaleCookie();

		// Also check periodically for dynamically loaded images
		const interval = setInterval(checkStaleCookie, 1000);

		return () => clearInterval(interval);
	}, []);
};

function attemptReload() {
	const lastAttempt = sessionStorage.getItem(RELOAD_STORAGE_KEY);
	const now = Date.now();

	if (!lastAttempt) {
		sessionStorage.setItem(RELOAD_STORAGE_KEY, now.toString());
		window.location.reload();
		return;
	}

	const timeSinceLastAttempt = now - parseInt(lastAttempt, 10);

	if (timeSinceLastAttempt > RELOAD_COOLDOWN_MS) {
		sessionStorage.setItem(RELOAD_STORAGE_KEY, now.toString());
		window.location.reload();
	}
}
