"use client";

import { useEffect } from "react";
import { useBranding } from "./branding";

function syncIconLink(rel: string, href: string) {
  let link = document.head.querySelector(`link[rel="${rel}"]`) as HTMLLinkElement | null;
  if (!link) {
    link = document.createElement("link");
    link.rel = rel;
    document.head.appendChild(link);
  }
  if (link.href !== href) {
    link.href = href;
  }
}

export function useRuntimeBranding(domain = "") {
  const branding = useBranding(domain);

  useEffect(() => {
    if (branding.name) {
      document.title = branding.name;
    }
    if (branding.faviconUrl) {
      syncIconLink("icon", branding.faviconUrl);
      syncIconLink("apple-touch-icon", branding.faviconUrl);
    }
  }, [branding.faviconUrl, branding.name]);

  return branding;
}
