import { useEffect, useState } from "react";
import { buildNodeDCBrandConfigUrl, buildNodeDCLauncherUrl } from "@/helpers/nodedc-auth";

type TNodeDCBrandPayload = {
  logoLinkUrl?: string | null;
};

export function useNodeDCBrandLinkUrl() {
  const [logoLinkUrl, setLogoLinkUrl] = useState(buildNodeDCLauncherUrl);

  useEffect(() => {
    let isMounted = true;

    fetch(buildNodeDCBrandConfigUrl(), { cache: "no-store" })
      .then((response) => (response.ok ? response.json() : null))
      .then((payload: TNodeDCBrandPayload | null) => {
        const configuredUrl = typeof payload?.logoLinkUrl === "string" ? payload.logoLinkUrl.trim() : "";
        if (isMounted && configuredUrl) setLogoLinkUrl(configuredUrl);
        return undefined;
      })
      .catch((error: unknown) => {
        console.warn(error instanceof Error ? error.message : "Не удалось загрузить brand config NODE.DC");
      });

    return () => {
      isMounted = false;
    };
  }, []);

  return logoLinkUrl;
}
