import { useEffect } from "react";
import { useIntl } from "react-intl";

export default function usePageTitle(messageIdOrText) {
  const intl = useIntl();

  useEffect(() => {
    let pageTitle;
    let systemName;
    let gldName;

    // If string looks like an intl id, try translate
    try {
      pageTitle = intl.formatMessage({ id: messageIdOrText });
      systemName = intl.formatMessage({ id: "PNSPS_fullname" });
      gldName = intl.formatMessage({ id: "HKGLD" });
    } catch {
      pageTitle = messageIdOrText;
    }

    const fullTitle = `${pageTitle} - ${systemName} | ${gldName}`;

    // Update document title (tab title)
    document.title = fullTitle;

    // Update <meta name="title"> and <meta name="description"> so they're language-dependent too
    const metaTitle = document.querySelector('meta[name="title"]');
    if (metaTitle) {
      metaTitle.setAttribute("content", fullTitle);
    }

    const metaDescription = document.querySelector('meta[name="description"]');
    if (metaDescription) {
      metaDescription.setAttribute("content", fullTitle);
    }

    // Keep <html lang="..."> in sync with current locale
    if (document.documentElement) {
      document.documentElement.lang = intl.locale || "en";
    }
  }, [messageIdOrText, intl]);
}