import { useEffect } from 'react';

export function usePageMeta(title: string, description: string) {
  useEffect(() => {
    const previousTitle = document.title;
    let descriptionMeta = document.querySelector<HTMLMetaElement>('meta[name="description"]');
    const previousDescription = descriptionMeta?.getAttribute('content') ?? null;
    const createdDescriptionMeta = !descriptionMeta;

    if (!descriptionMeta) {
      descriptionMeta = document.createElement('meta');
      descriptionMeta.setAttribute('name', 'description');
      document.head.appendChild(descriptionMeta);
    }

    document.title = title;
    descriptionMeta.setAttribute('content', description);

    return () => {
      document.title = previousTitle;
      if (!descriptionMeta) return;
      if (createdDescriptionMeta) {
        descriptionMeta.remove();
        return;
      }
      if (previousDescription === null) {
        descriptionMeta.removeAttribute('content');
      } else {
        descriptionMeta.setAttribute('content', previousDescription);
      }
    };
  }, [description, title]);
}
