import { useEffect } from "react";

export function useExternalSessionBrand(session, fallbackTitle) {
  const appName = String(session?.appName || session?.appCode || fallbackTitle || "External Admin").trim();
  const logoUrl = String(session?.logoUrl || "").trim();

  useEffect(() => {
    // 认证后的 App 品牌只采用服务端 session；session 又来自 apps 行，前端不解析账号名称猜租户。
    globalThis.document.title = appName;
    syncBrandFavicon(logoUrl);
    return () => {
      globalThis.document.title = fallbackTitle || "External Admin";
      syncBrandFavicon("");
    };
  }, [appName, fallbackTitle, logoUrl]);
}

function syncBrandFavicon(logoUrl) {
  const selector = 'link[data-external-app-favicon="true"]';
  const current = globalThis.document?.head?.querySelector(selector);
  if (!logoUrl) {
    current?.remove();
    return;
  }
  const link = current || globalThis.document.createElement("link");
  link.dataset.externalAppFavicon = "true";
  link.rel = "icon";
  link.href = logoUrl;
  if (!current) {
    globalThis.document.head.append(link);
  }
}
