"use client";

import { getAuthTokenFromCookie } from "@/entities/user/serverActions";
import { useEffect, useMemo, useState } from "react";

export const useClientToken = () => {
  const [token, setToken] = useState<string | undefined>(undefined);

  useEffect(() => {
    (async () => {
      try {
        const token = await getAuthTokenFromCookie();
        // If server returned undefined, fall back to a stable mock in Storybook
        if (!token && typeof window !== "undefined") {
          const w = window as Window & { __STORYBOOK_ADDONS?: unknown };
          const isStorybook = Boolean(w.__STORYBOOK_ADDONS) ||
            /:\/\/.*(:6006|storybook)/i.test(w.location.href);
          setToken(isStorybook ? "storybook-token" : undefined);
        } else {
          setToken(token);
        }
      } catch {
        // In Storybook or non-Next runtime, server action may fail; use mock token
        if (typeof window !== "undefined") {
          setToken("storybook-token");
        } else {
          setToken(undefined);
        }
      }
    })();
  }, []);

  return useMemo(() => token, [token]);
};
