"use client";

import { useCallback } from "react";
import { useAppSelector } from "@/store/hooks";
import { useLoginPrompt } from "@/lib/LoginPromptContext";

/**
 * Returns a guard function. Wrap any auth-required callback with it:
 *
 *   const requireAuth = useRequireAuth();
 *   <button onClick={() => requireAuth(() => handleLike())} />
 *
 * If the user is not authenticated the login prompt opens instead of
 * running the callback.
 */
export function useRequireAuth() {
  const isAuthenticated = useAppSelector((s) => s.auth.isAuthenticated);
  const { open } = useLoginPrompt();

  return useCallback(
    (fn: () => void) => {
      if (!isAuthenticated) {
        open();
        return;
      }
      fn();
    },
    [isAuthenticated, open],
  );
}
