import { useEffect, useState } from "react";

//helper function to get cookie
export const cookieGrabber = (key = "") => {
  const cookies = document.cookie;
  const string = cookies.split(";").find((cookie) => {
    cookie = cookie.trim();
    if (cookie.startsWith(key.trim() + "=")) return true;
  });

  if (!string) return "";
  return string.split("=")[1].trim();
};

/**
 * Custom hook to poll a specific cookie and update state on change.
 *
 * @param {string} cookieName The name of the cookie to monitor.
 * @param {number} intervalMs The polling interval in milliseconds (e.g., 1000 for 1 second).
 * @returns {string | null} The current value of the cookie.
 */
export function useCookiePolling(cookieName, intervalMs = 500) {
  const [cookieValue, setCookieValue] = useState(() =>
    cookieGrabber(cookieName)
  );

  useEffect(() => {
    const intervalId = setInterval(() => {
      const currentValue = cookieGrabber(cookieName);
      // Update state only if the value has actually changed
      if (currentValue !== cookieValue) {
        console.log(
          `Cookie '${cookieName}' changed from '${cookieValue}' to '${currentValue}'`
        );
        setCookieValue(currentValue);
      }
    }, intervalMs);

    // Cleanup: clear the interval when the component unmounts or dependencies change
    return () => clearInterval(intervalId);
  }, [cookieName, intervalMs, cookieValue]); // Re-run effect if cookieName or interval changes, or if cookieValue was updated

  return cookieValue;
}
export default useCookiePolling;
